1 /* $OpenBSD: sshd.c,v 1.492 2017/09/12 06:32:07 djm 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"
77 #include <openssl/dh.h>
78 #include <openssl/bn.h>
79 #include <openssl/rand.h>
80 #include "openbsd-compat/openssl-compat.h"
83 #ifdef HAVE_SECUREWARE
84 #include <sys/security.h>
104 #include "myproposal.h"
105 #include "authfile.h"
106 #include "pathnames.h"
107 #include "atomicio.h"
108 #include "canohost.h"
109 #include "hostfile.h"
113 #include "dispatch.h"
114 #include "channels.h"
120 #include "monitor_wrap.h"
121 #include "ssh-sandbox.h"
126 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
127 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
128 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
129 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
131 extern char *__progname
;
133 /* Server configuration options. */
134 ServerOptions options
;
136 /* Name of the server configuration file. */
137 char *config_file_name
= _PATH_SERVER_CONFIG_FILE
;
140 * Debug mode flag. This can be set on the command line. If debug
141 * mode is enabled, extra debugging output will be sent to the system
142 * log, the daemon will not go to background, and will exit after processing
143 * the first connection.
147 /* Flag indicating that the daemon should only test the configuration and keys. */
150 /* Flag indicating that the daemon is being started from inetd. */
153 /* Flag indicating that sshd should not detach and become a daemon. */
154 int no_daemon_flag
= 0;
156 /* debug goes to stderr unless inetd_flag is set */
159 /* Saved arguments to main(). */
164 int rexeced_flag
= 0;
170 * The sockets that the server is listening; this is used in the SIGHUP
173 #define MAX_LISTEN_SOCKS 16
174 int listen_socks
[MAX_LISTEN_SOCKS
];
175 int num_listen_socks
= 0;
178 * the client's version string, passed by sshd2 in compat mode. if != NULL,
179 * sshd will skip the version-number exchange
181 char *client_version_string
= NULL
;
182 char *server_version_string
= NULL
;
184 /* Daemon's agent connection */
189 * Any really sensitive data in the application is contained in this
190 * structure. The idea is that this structure could be locked into memory so
191 * that the pages do not get written into swap. However, there are some
192 * problems. The private key contains BIGNUMs, and we do not (in principle)
193 * have access to the internals of them, and locking just the structure is
194 * not very useful. Currently, memory locking is not implemented.
197 struct sshkey
**host_keys
; /* all private host keys */
198 struct sshkey
**host_pubkeys
; /* all public host keys */
199 struct sshkey
**host_certificates
; /* all public host certificates */
203 /* This is set to true when a signal is received. */
204 static volatile sig_atomic_t received_sighup
= 0;
205 static volatile sig_atomic_t received_sigterm
= 0;
207 /* session identifier, used by RSA-auth */
208 u_char session_id
[16];
211 u_char
*session_id2
= NULL
;
212 u_int session_id2_len
= 0;
214 /* record remote hostname or ip */
215 u_int utmp_len
= HOST_NAME_MAX
+1;
217 /* options.max_startup sized array of fd ints */
218 int *startup_pipes
= NULL
;
219 int startup_pipe
; /* in child */
221 /* variables used for privilege separation */
222 int use_privsep
= -1;
223 struct monitor
*pmonitor
= NULL
;
224 int privsep_is_preauth
= 1;
225 static int privsep_chroot
= 1;
227 /* global authentication context */
228 Authctxt
*the_authctxt
= NULL
;
230 /* sshd_config buffer */
233 /* message to be displayed after login */
236 /* Unprivileged user */
237 struct passwd
*privsep_pw
= NULL
;
239 /* Prototypes for various functions defined later in this file. */
240 void destroy_sensitive_data(void);
241 void demote_sensitive_data(void);
242 static void do_ssh2_kex(void);
245 * Close all listening sockets
248 close_listen_socks(void)
252 for (i
= 0; i
< num_listen_socks
; i
++)
253 close(listen_socks
[i
]);
254 num_listen_socks
= -1;
258 close_startup_pipes(void)
263 for (i
= 0; i
< options
.max_startups
; i
++)
264 if (startup_pipes
[i
] != -1)
265 close(startup_pipes
[i
]);
269 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
270 * the effect is to reread the configuration file (and to regenerate
276 sighup_handler(int sig
)
278 int save_errno
= errno
;
281 signal(SIGHUP
, sighup_handler
);
286 * Called from the main program after receiving SIGHUP.
287 * Restarts the server.
292 logit("Received SIGHUP; restarting.");
293 if (options
.pid_file
!= NULL
)
294 unlink(options
.pid_file
);
295 platform_pre_restart();
296 close_listen_socks();
297 close_startup_pipes();
298 alarm(0); /* alarm timer persists across exec */
299 signal(SIGHUP
, SIG_IGN
); /* will be restored after exec */
300 execv(saved_argv
[0], saved_argv
);
301 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv
[0],
307 * Generic signal handler for terminating signals in the master daemon.
311 sigterm_handler(int sig
)
313 received_sigterm
= sig
;
317 * SIGCHLD handler. This is called whenever a child dies. This will then
318 * reap any zombies left by exited children.
322 main_sigchld_handler(int sig
)
324 int save_errno
= errno
;
328 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0 ||
329 (pid
< 0 && errno
== EINTR
))
332 signal(SIGCHLD
, main_sigchld_handler
);
337 * Signal handler for the alarm after the login grace period has expired.
341 grace_alarm_handler(int sig
)
343 if (use_privsep
&& pmonitor
!= NULL
&& pmonitor
->m_pid
> 0)
344 kill(pmonitor
->m_pid
, SIGALRM
);
347 * Try to kill any processes that we have spawned, E.g. authorized
348 * keys command helpers.
350 if (getpgid(0) == getpid()) {
351 signal(SIGTERM
, SIG_IGN
);
355 /* Log error and exit. */
356 sigdie("Timeout before authentication for %s port %d",
357 ssh_remote_ipaddr(active_state
), ssh_remote_port(active_state
));
361 sshd_exchange_identification(struct ssh
*ssh
, int sock_in
, int sock_out
)
364 int remote_major
, remote_minor
;
366 char buf
[256]; /* Must not be larger than remote_version. */
367 char remote_version
[256]; /* Must be at least as big as buf. */
369 xasprintf(&server_version_string
, "SSH-%d.%d-%.100s%s%s\r\n",
370 PROTOCOL_MAJOR_2
, PROTOCOL_MINOR_2
, SSH_VERSION
,
371 *options
.version_addendum
== '\0' ? "" : " ",
372 options
.version_addendum
);
374 /* Send our protocol version identification. */
375 if (atomicio(vwrite
, sock_out
, server_version_string
,
376 strlen(server_version_string
))
377 != strlen(server_version_string
)) {
378 logit("Could not write ident string to %s port %d",
379 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
383 /* Read other sides version identification. */
384 memset(buf
, 0, sizeof(buf
));
385 for (i
= 0; i
< sizeof(buf
) - 1; i
++) {
386 if (atomicio(read
, sock_in
, &buf
[i
], 1) != 1) {
387 logit("Did not receive identification string "
389 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
392 if (buf
[i
] == '\r') {
394 /* Kludge for F-Secure Macintosh < 1.0.2 */
396 strncmp(buf
, "SSH-1.5-W1.0", 12) == 0)
400 if (buf
[i
] == '\n') {
405 buf
[sizeof(buf
) - 1] = 0;
406 client_version_string
= xstrdup(buf
);
409 * Check that the versions match. In future this might accept
410 * several versions and set appropriate flags to handle them.
412 if (sscanf(client_version_string
, "SSH-%d.%d-%[^\n]\n",
413 &remote_major
, &remote_minor
, remote_version
) != 3) {
414 s
= "Protocol mismatch.\n";
415 (void) atomicio(vwrite
, sock_out
, s
, strlen(s
));
416 logit("Bad protocol version identification '%.100s' "
417 "from %s port %d", client_version_string
,
418 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
423 debug("Client protocol version %d.%d; client software version %.100s",
424 remote_major
, remote_minor
, remote_version
);
426 ssh
->compat
= compat_datafellows(remote_version
);
428 if ((ssh
->compat
& SSH_BUG_PROBE
) != 0) {
429 logit("probed from %s port %d with %s. Don't panic.",
430 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
),
431 client_version_string
);
434 if ((ssh
->compat
& SSH_BUG_SCANNER
) != 0) {
435 logit("scanned from %s port %d with %s. Don't panic.",
436 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
),
437 client_version_string
);
440 if ((ssh
->compat
& SSH_BUG_RSASIGMD5
) != 0) {
441 logit("Client version \"%.100s\" uses unsafe RSA signature "
442 "scheme; disabling use of RSA keys", remote_version
);
444 if ((ssh
->compat
& SSH_BUG_DERIVEKEY
) != 0) {
445 fatal("Client version \"%.100s\" uses unsafe key agreement; "
446 "refusing connection", remote_version
);
449 chop(server_version_string
);
450 debug("Local version string %.200s", server_version_string
);
452 if (remote_major
!= 2 ||
453 (remote_major
== 1 && remote_minor
!= 99)) {
454 s
= "Protocol major versions differ.\n";
455 (void) atomicio(vwrite
, sock_out
, s
, strlen(s
));
458 logit("Protocol major versions differ for %s port %d: "
460 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
),
461 server_version_string
, client_version_string
);
466 /* Destroy the host and server keys. They will no longer be needed. */
468 destroy_sensitive_data(void)
472 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
473 if (sensitive_data
.host_keys
[i
]) {
474 key_free(sensitive_data
.host_keys
[i
]);
475 sensitive_data
.host_keys
[i
] = NULL
;
477 if (sensitive_data
.host_certificates
[i
]) {
478 key_free(sensitive_data
.host_certificates
[i
]);
479 sensitive_data
.host_certificates
[i
] = NULL
;
484 /* Demote private to public keys for network child */
486 demote_sensitive_data(void)
491 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
492 if (sensitive_data
.host_keys
[i
]) {
493 tmp
= key_demote(sensitive_data
.host_keys
[i
]);
494 key_free(sensitive_data
.host_keys
[i
]);
495 sensitive_data
.host_keys
[i
] = tmp
;
497 /* Certs do not need demotion */
509 arc4random_stir(); /* noop on recent arc4random() implementations */
510 arc4random_buf(rnd
, sizeof(rnd
)); /* let arc4random notice PID change */
513 RAND_seed(rnd
, sizeof(rnd
));
514 /* give libcrypto a chance to notice the PID change */
515 if ((RAND_bytes((u_char
*)rnd
, 1)) != 1)
516 fatal("%s: RAND_bytes failed", __func__
);
519 explicit_bzero(rnd
, sizeof(rnd
));
523 privsep_preauth_child(void)
527 /* Enable challenge-response authentication for privilege separation */
528 privsep_challenge_enable();
531 /* Cache supported mechanism OIDs for later use */
532 if (options
.gss_authentication
)
533 ssh_gssapi_prepare_supported_oids();
538 /* Demote the private keys to public keys. */
539 demote_sensitive_data();
541 /* Demote the child */
542 if (privsep_chroot
) {
543 /* Change our root directory */
544 if (chroot(_PATH_PRIVSEP_CHROOT_DIR
) == -1)
545 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR
,
547 if (chdir("/") == -1)
548 fatal("chdir(\"/\"): %s", strerror(errno
));
550 /* Drop our privileges */
551 debug3("privsep user:group %u:%u", (u_int
)privsep_pw
->pw_uid
,
552 (u_int
)privsep_pw
->pw_gid
);
553 gidset
[0] = privsep_pw
->pw_gid
;
554 if (setgroups(1, gidset
) < 0)
555 fatal("setgroups: %.100s", strerror(errno
));
556 permanently_set_uid(privsep_pw
);
561 privsep_preauth(Authctxt
*authctxt
)
565 struct ssh_sandbox
*box
= NULL
;
567 /* Set up unprivileged child process to deal with network data */
568 pmonitor
= monitor_init();
569 /* Store a pointer to the kex for later rekeying */
570 pmonitor
->m_pkex
= &active_state
->kex
;
572 if (use_privsep
== PRIVSEP_ON
)
573 box
= ssh_sandbox_init(pmonitor
);
576 fatal("fork of unprivileged child failed");
577 } else if (pid
!= 0) {
578 debug2("Network child is on pid %ld", (long)pid
);
580 pmonitor
->m_pid
= pid
;
582 r
= ssh_get_authentication_socket(&auth_sock
);
584 error("Could not get agent socket: %s",
590 ssh_sandbox_parent_preauth(box
, pid
);
591 monitor_child_preauth(authctxt
, pmonitor
);
593 /* Wait for the child's exit status */
594 while (waitpid(pid
, &status
, 0) < 0) {
597 pmonitor
->m_pid
= -1;
598 fatal("%s: waitpid: %s", __func__
, strerror(errno
));
600 privsep_is_preauth
= 0;
601 pmonitor
->m_pid
= -1;
602 if (WIFEXITED(status
)) {
603 if (WEXITSTATUS(status
) != 0)
604 fatal("%s: preauth child exited with status %d",
605 __func__
, WEXITSTATUS(status
));
606 } else if (WIFSIGNALED(status
))
607 fatal("%s: preauth child terminated by signal %d",
608 __func__
, WTERMSIG(status
));
610 ssh_sandbox_parent_finish(box
);
614 close(pmonitor
->m_sendfd
);
615 close(pmonitor
->m_log_recvfd
);
617 /* Arrange for logging to be sent to the monitor */
618 set_log_handler(mm_log_handler
, pmonitor
);
620 privsep_preauth_child();
621 setproctitle("%s", "[net]");
623 ssh_sandbox_child(box
);
630 privsep_postauth(Authctxt
*authctxt
)
632 #ifdef DISABLE_FD_PASSING
635 if (authctxt
->pw
->pw_uid
== 0) {
637 /* File descriptor passing is broken or root login */
642 /* New socket pair */
643 monitor_reinit(pmonitor
);
645 pmonitor
->m_pid
= fork();
646 if (pmonitor
->m_pid
== -1)
647 fatal("fork of unprivileged child failed");
648 else if (pmonitor
->m_pid
!= 0) {
649 verbose("User child is on pid %ld", (long)pmonitor
->m_pid
);
650 buffer_clear(&loginmsg
);
651 monitor_clear_keystate(pmonitor
);
652 monitor_child_postauth(pmonitor
);
660 close(pmonitor
->m_sendfd
);
661 pmonitor
->m_sendfd
= -1;
663 /* Demote the private keys to public keys. */
664 demote_sensitive_data();
668 /* Drop privileges */
669 do_setusercontext(authctxt
->pw
);
672 /* It is safe now to apply the key state */
673 monitor_apply_keystate(pmonitor
);
676 * Tell the packet layer that authentication was successful, since
677 * this information is not part of the key state.
679 packet_set_authenticated();
683 list_hostkey_types(void)
692 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
693 key
= sensitive_data
.host_keys
[i
];
695 key
= sensitive_data
.host_pubkeys
[i
];
698 /* Check that the key is accepted in HostkeyAlgorithms */
699 if (match_pattern_list(sshkey_ssh_name(key
),
700 options
.hostkeyalgorithms
, 0) != 1) {
701 debug3("%s: %s key not permitted by HostkeyAlgorithms",
702 __func__
, sshkey_ssh_name(key
));
710 if (buffer_len(&b
) > 0)
711 buffer_append(&b
, ",", 1);
712 p
= key_ssh_name(key
);
713 buffer_append(&b
, p
, strlen(p
));
715 /* for RSA we also support SHA2 signatures */
716 if (key
->type
== KEY_RSA
) {
717 p
= ",rsa-sha2-512,rsa-sha2-256";
718 buffer_append(&b
, p
, strlen(p
));
722 /* If the private key has a cert peer, then list that too */
723 key
= sensitive_data
.host_certificates
[i
];
730 case KEY_ED25519_CERT
:
731 if (buffer_len(&b
) > 0)
732 buffer_append(&b
, ",", 1);
733 p
= key_ssh_name(key
);
734 buffer_append(&b
, p
, strlen(p
));
738 if ((ret
= sshbuf_dup_string(&b
)) == NULL
)
739 fatal("%s: sshbuf_dup_string failed", __func__
);
741 debug("list_hostkey_types: %s", ret
);
745 static struct sshkey
*
746 get_hostkey_by_type(int type
, int nid
, int need_private
, struct ssh
*ssh
)
751 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
756 case KEY_ED25519_CERT
:
757 key
= sensitive_data
.host_certificates
[i
];
760 key
= sensitive_data
.host_keys
[i
];
761 if (key
== NULL
&& !need_private
)
762 key
= sensitive_data
.host_pubkeys
[i
];
765 if (key
!= NULL
&& key
->type
== type
&&
766 (key
->type
!= KEY_ECDSA
|| key
->ecdsa_nid
== nid
))
767 return need_private
?
768 sensitive_data
.host_keys
[i
] : key
;
774 get_hostkey_public_by_type(int type
, int nid
, struct ssh
*ssh
)
776 return get_hostkey_by_type(type
, nid
, 0, ssh
);
780 get_hostkey_private_by_type(int type
, int nid
, struct ssh
*ssh
)
782 return get_hostkey_by_type(type
, nid
, 1, ssh
);
786 get_hostkey_by_index(int ind
)
788 if (ind
< 0 || ind
>= options
.num_host_key_files
)
790 return (sensitive_data
.host_keys
[ind
]);
794 get_hostkey_public_by_index(int ind
, struct ssh
*ssh
)
796 if (ind
< 0 || ind
>= options
.num_host_key_files
)
798 return (sensitive_data
.host_pubkeys
[ind
]);
802 get_hostkey_index(struct sshkey
*key
, int compare
, struct ssh
*ssh
)
806 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
807 if (key_is_cert(key
)) {
808 if (key
== sensitive_data
.host_certificates
[i
] ||
809 (compare
&& sensitive_data
.host_certificates
[i
] &&
811 sensitive_data
.host_certificates
[i
])))
814 if (key
== sensitive_data
.host_keys
[i
] ||
815 (compare
&& sensitive_data
.host_keys
[i
] &&
816 sshkey_equal(key
, sensitive_data
.host_keys
[i
])))
818 if (key
== sensitive_data
.host_pubkeys
[i
] ||
819 (compare
&& sensitive_data
.host_pubkeys
[i
] &&
820 sshkey_equal(key
, sensitive_data
.host_pubkeys
[i
])))
827 /* Inform the client of all hostkeys */
829 notify_hostkeys(struct ssh
*ssh
)
836 /* Some clients cannot cope with the hostkeys message, skip those. */
837 if (datafellows
& SSH_BUG_HOSTKEYS
)
840 if ((buf
= sshbuf_new()) == NULL
)
841 fatal("%s: sshbuf_new", __func__
);
842 for (i
= nkeys
= 0; i
< options
.num_host_key_files
; i
++) {
843 key
= get_hostkey_public_by_index(i
, ssh
);
844 if (key
== NULL
|| key
->type
== KEY_UNSPEC
||
847 fp
= sshkey_fingerprint(key
, options
.fingerprint_hash
,
849 debug3("%s: key %d: %s %s", __func__
, i
,
850 sshkey_ssh_name(key
), fp
);
853 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
854 packet_put_cstring("hostkeys-00@openssh.com");
855 packet_put_char(0); /* want-reply */
858 if ((r
= sshkey_putb(key
, buf
)) != 0)
859 fatal("%s: couldn't put hostkey %d: %s",
860 __func__
, i
, ssh_err(r
));
861 packet_put_string(sshbuf_ptr(buf
), sshbuf_len(buf
));
864 debug3("%s: sent %d hostkeys", __func__
, nkeys
);
866 fatal("%s: no hostkeys", __func__
);
872 * returns 1 if connection should be dropped, 0 otherwise.
873 * dropping starts at connection #max_startups_begin with a probability
874 * of (max_startups_rate/100). the probability increases linearly until
875 * all connections are dropped for startups > max_startups
878 drop_connection(int startups
)
882 if (startups
< options
.max_startups_begin
)
884 if (startups
>= options
.max_startups
)
886 if (options
.max_startups_rate
== 100)
889 p
= 100 - options
.max_startups_rate
;
890 p
*= startups
- options
.max_startups_begin
;
891 p
/= options
.max_startups
- options
.max_startups_begin
;
892 p
+= options
.max_startups_rate
;
893 r
= arc4random_uniform(100);
895 debug("drop_connection: p %d, r %d", p
, r
);
896 return (r
< p
) ? 1 : 0;
902 fprintf(stderr
, "%s, %s\n",
905 SSLeay_version(SSLEAY_VERSION
)
911 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
912 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
913 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
919 send_rexec_state(int fd
, struct sshbuf
*conf
)
924 debug3("%s: entering fd = %d config len %zu", __func__
, fd
,
928 * Protocol from reexec master to child:
929 * string configuration
930 * string rngseed (only if OpenSSL is not self-seeded)
932 if ((m
= sshbuf_new()) == NULL
)
933 fatal("%s: sshbuf_new failed", __func__
);
934 if ((r
= sshbuf_put_stringb(m
, conf
)) != 0)
935 fatal("%s: buffer error: %s", __func__
, ssh_err(r
));
937 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
938 rexec_send_rng_seed(m
);
941 if (ssh_msg_send(fd
, 0, m
) == -1)
942 fatal("%s: ssh_msg_send failed", __func__
);
946 debug3("%s: done", __func__
);
950 recv_rexec_state(int fd
, Buffer
*conf
)
956 debug3("%s: entering fd = %d", __func__
, fd
);
960 if (ssh_msg_recv(fd
, &m
) == -1)
961 fatal("%s: ssh_msg_recv failed", __func__
);
962 if (buffer_get_char(&m
) != 0)
963 fatal("%s: rexec version mismatch", __func__
);
965 cp
= buffer_get_string(&m
, &len
);
967 buffer_append(conf
, cp
, len
);
970 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
971 rexec_recv_rng_seed(&m
);
976 debug3("%s: done", __func__
);
979 /* Accept a connection from inetd */
981 server_accept_inetd(int *sock_in
, int *sock_out
)
987 close(REEXEC_CONFIG_PASS_FD
);
988 *sock_in
= *sock_out
= dup(STDIN_FILENO
);
990 startup_pipe
= dup(REEXEC_STARTUP_PIPE_FD
);
991 close(REEXEC_STARTUP_PIPE_FD
);
994 *sock_in
= dup(STDIN_FILENO
);
995 *sock_out
= dup(STDOUT_FILENO
);
998 * We intentionally do not close the descriptors 0, 1, and 2
999 * as our code for setting the descriptors won't work if
1000 * ttyfd happens to be one of those.
1002 if ((fd
= open(_PATH_DEVNULL
, O_RDWR
, 0)) != -1) {
1003 dup2(fd
, STDIN_FILENO
);
1004 dup2(fd
, STDOUT_FILENO
);
1006 dup2(fd
, STDERR_FILENO
);
1007 if (fd
> (log_stderr
? STDERR_FILENO
: STDOUT_FILENO
))
1010 debug("inetd sockets after dupping: %d, %d", *sock_in
, *sock_out
);
1014 * Listen for TCP connections
1019 int ret
, listen_sock
, on
= 1;
1020 struct addrinfo
*ai
;
1021 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
1023 for (ai
= options
.listen_addrs
; ai
; ai
= ai
->ai_next
) {
1024 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
1026 if (num_listen_socks
>= MAX_LISTEN_SOCKS
)
1027 fatal("Too many listen sockets. "
1028 "Enlarge MAX_LISTEN_SOCKS");
1029 if ((ret
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
,
1030 ntop
, sizeof(ntop
), strport
, sizeof(strport
),
1031 NI_NUMERICHOST
|NI_NUMERICSERV
)) != 0) {
1032 error("getnameinfo failed: %.100s",
1033 ssh_gai_strerror(ret
));
1036 /* Create socket for listening. */
1037 listen_sock
= socket(ai
->ai_family
, ai
->ai_socktype
,
1039 if (listen_sock
< 0) {
1040 /* kernel may not support ipv6 */
1041 verbose("socket: %.100s", strerror(errno
));
1044 if (set_nonblock(listen_sock
) == -1) {
1048 if (fcntl(listen_sock
, F_SETFD
, FD_CLOEXEC
) == -1) {
1049 verbose("socket: CLOEXEC: %s", strerror(errno
));
1054 * Set socket options.
1055 * Allow local port reuse in TIME_WAIT.
1057 if (setsockopt(listen_sock
, SOL_SOCKET
, SO_REUSEADDR
,
1058 &on
, sizeof(on
)) == -1)
1059 error("setsockopt SO_REUSEADDR: %s", strerror(errno
));
1061 /* Only communicate in IPv6 over AF_INET6 sockets. */
1062 if (ai
->ai_family
== AF_INET6
)
1063 sock_set_v6only(listen_sock
);
1065 debug("Bind to port %s on %s.", strport
, ntop
);
1067 /* Bind the socket to the desired port. */
1068 if (bind(listen_sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1069 error("Bind to port %s on %s failed: %.200s.",
1070 strport
, ntop
, strerror(errno
));
1074 listen_socks
[num_listen_socks
] = listen_sock
;
1077 /* Start listening on the port. */
1078 if (listen(listen_sock
, SSH_LISTEN_BACKLOG
) < 0)
1079 fatal("listen on [%s]:%s: %.100s",
1080 ntop
, strport
, strerror(errno
));
1081 logit("Server listening on %s port %s.", ntop
, strport
);
1083 freeaddrinfo(options
.listen_addrs
);
1085 if (!num_listen_socks
)
1086 fatal("Cannot bind any address.");
1090 * The main TCP accept loop. Note that, for the non-debug case, returns
1091 * from this function are in a forked subprocess.
1094 server_accept_loop(int *sock_in
, int *sock_out
, int *newsock
, int *config_s
)
1097 int i
, j
, ret
, maxfd
;
1099 int startup_p
[2] = { -1 , -1 };
1100 struct sockaddr_storage from
;
1105 /* setup fd set for accept */
1108 for (i
= 0; i
< num_listen_socks
; i
++)
1109 if (listen_socks
[i
] > maxfd
)
1110 maxfd
= listen_socks
[i
];
1111 /* pipes connected to unauthenticated childs */
1112 startup_pipes
= xcalloc(options
.max_startups
, sizeof(int));
1113 for (i
= 0; i
< options
.max_startups
; i
++)
1114 startup_pipes
[i
] = -1;
1117 * Stay listening for connections until the system crashes or
1118 * the daemon is killed with a signal.
1121 if (received_sighup
)
1124 fdset
= xcalloc(howmany(maxfd
+ 1, NFDBITS
),
1127 for (i
= 0; i
< num_listen_socks
; i
++)
1128 FD_SET(listen_socks
[i
], fdset
);
1129 for (i
= 0; i
< options
.max_startups
; i
++)
1130 if (startup_pipes
[i
] != -1)
1131 FD_SET(startup_pipes
[i
], fdset
);
1133 /* Wait in select until there is a connection. */
1134 ret
= select(maxfd
+1, fdset
, NULL
, NULL
, NULL
);
1135 if (ret
< 0 && errno
!= EINTR
)
1136 error("select: %.100s", strerror(errno
));
1137 if (received_sigterm
) {
1138 logit("Received signal %d; terminating.",
1139 (int) received_sigterm
);
1140 close_listen_socks();
1141 if (options
.pid_file
!= NULL
)
1142 unlink(options
.pid_file
);
1143 exit(received_sigterm
== SIGTERM
? 0 : 255);
1148 for (i
= 0; i
< options
.max_startups
; i
++)
1149 if (startup_pipes
[i
] != -1 &&
1150 FD_ISSET(startup_pipes
[i
], fdset
)) {
1152 * the read end of the pipe is ready
1153 * if the child has closed the pipe
1154 * after successful authentication
1155 * or if the child has died
1157 close(startup_pipes
[i
]);
1158 startup_pipes
[i
] = -1;
1161 for (i
= 0; i
< num_listen_socks
; i
++) {
1162 if (!FD_ISSET(listen_socks
[i
], fdset
))
1164 fromlen
= sizeof(from
);
1165 *newsock
= accept(listen_socks
[i
],
1166 (struct sockaddr
*)&from
, &fromlen
);
1168 if (errno
!= EINTR
&& errno
!= EWOULDBLOCK
&&
1169 errno
!= ECONNABORTED
&& errno
!= EAGAIN
)
1170 error("accept: %.100s",
1172 if (errno
== EMFILE
|| errno
== ENFILE
)
1176 if (unset_nonblock(*newsock
) == -1) {
1180 if (drop_connection(startups
) == 1) {
1181 char *laddr
= get_local_ipaddr(*newsock
);
1182 char *raddr
= get_peer_ipaddr(*newsock
);
1184 verbose("drop connection #%d from [%s]:%d "
1185 "on [%s]:%d past MaxStartups", startups
,
1186 raddr
, get_peer_port(*newsock
),
1187 laddr
, get_local_port(*newsock
));
1193 if (pipe(startup_p
) == -1) {
1198 if (rexec_flag
&& socketpair(AF_UNIX
,
1199 SOCK_STREAM
, 0, config_s
) == -1) {
1200 error("reexec socketpair: %s",
1203 close(startup_p
[0]);
1204 close(startup_p
[1]);
1208 for (j
= 0; j
< options
.max_startups
; j
++)
1209 if (startup_pipes
[j
] == -1) {
1210 startup_pipes
[j
] = startup_p
[0];
1211 if (maxfd
< startup_p
[0])
1212 maxfd
= startup_p
[0];
1218 * Got connection. Fork a child to handle it, unless
1219 * we are in debugging mode.
1223 * In debugging mode. Close the listening
1224 * socket, and start processing the
1225 * connection without forking.
1227 debug("Server will not fork when running in debugging mode.");
1228 close_listen_socks();
1229 *sock_in
= *newsock
;
1230 *sock_out
= *newsock
;
1231 close(startup_p
[0]);
1232 close(startup_p
[1]);
1236 send_rexec_state(config_s
[0],
1244 * Normal production daemon. Fork, and have
1245 * the child process the connection. The
1246 * parent continues listening.
1248 platform_pre_fork();
1249 if ((pid
= fork()) == 0) {
1251 * Child. Close the listening and
1252 * max_startup sockets. Start using
1253 * the accepted socket. Reinitialize
1254 * logging (since our pid has changed).
1255 * We break out of the loop to handle
1258 platform_post_fork_child();
1259 startup_pipe
= startup_p
[1];
1260 close_startup_pipes();
1261 close_listen_socks();
1262 *sock_in
= *newsock
;
1263 *sock_out
= *newsock
;
1264 log_init(__progname
,
1266 options
.log_facility
,
1273 /* Parent. Stay in the loop. */
1274 platform_post_fork_parent(pid
);
1276 error("fork: %.100s", strerror(errno
));
1278 debug("Forked child %ld.", (long)pid
);
1280 close(startup_p
[1]);
1283 send_rexec_state(config_s
[0], &cfg
);
1290 * Ensure that our random state differs
1291 * from that of the child
1294 arc4random_buf(rnd
, sizeof(rnd
));
1296 RAND_seed(rnd
, sizeof(rnd
));
1297 if ((RAND_bytes((u_char
*)rnd
, 1)) != 1)
1298 fatal("%s: RAND_bytes failed", __func__
);
1300 explicit_bzero(rnd
, sizeof(rnd
));
1303 /* child process check (or debug mode) */
1304 if (num_listen_socks
< 0)
1310 * If IP options are supported, make sure there are none (log and
1311 * return an error if any are found). Basically we are worried about
1312 * source routing; it can be used to pretend you are somebody
1313 * (ip-address) you are not. That itself may be "almost acceptable"
1314 * under certain circumstances, but rhosts autentication is useless
1315 * if source routing is accepted. Notice also that if we just dropped
1316 * source routing here, the other side could use IP spoofing to do
1317 * rest of the interaction and could still bypass security. So we
1318 * exit here if we detect any IP options.
1321 check_ip_options(struct ssh
*ssh
)
1324 int sock_in
= ssh_packet_get_connection_in(ssh
);
1325 struct sockaddr_storage from
;
1327 socklen_t i
, option_size
= sizeof(opts
), fromlen
= sizeof(from
);
1328 char text
[sizeof(opts
) * 3 + 1];
1330 memset(&from
, 0, sizeof(from
));
1331 if (getpeername(sock_in
, (struct sockaddr
*)&from
,
1334 if (from
.ss_family
!= AF_INET
)
1336 /* XXX IPv6 options? */
1338 if (getsockopt(sock_in
, IPPROTO_IP
, IP_OPTIONS
, opts
,
1339 &option_size
) >= 0 && option_size
!= 0) {
1341 for (i
= 0; i
< option_size
; i
++)
1342 snprintf(text
+ i
*3, sizeof(text
) - i
*3,
1344 fatal("Connection from %.100s port %d with IP opts: %.800s",
1345 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
), text
);
1348 #endif /* IP_OPTIONS */
1352 * Main program for the daemon.
1355 main(int ac
, char **av
)
1357 struct ssh
*ssh
= NULL
;
1358 extern char *optarg
;
1360 int r
, opt
, i
, j
, on
= 1, already_daemon
;
1361 int sock_in
= -1, sock_out
= -1, newsock
= -1;
1362 const char *remote_ip
;
1364 char *fp
, *line
, *laddr
, *logfile
= NULL
;
1365 int config_s
[2] = { -1 , -1 };
1367 u_int64_t ibytes
, obytes
;
1370 struct sshkey
*pubkey
;
1373 struct connection_info
*connection_info
= get_connection_info(0, 0);
1375 ssh_malloc_init(); /* must be called before any mallocs */
1377 #ifdef HAVE_SECUREWARE
1378 (void)set_auth_parameters(ac
, av
);
1380 __progname
= ssh_get_progname(av
[0]);
1382 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1385 saved_argv
= xcalloc(ac
+ 1, sizeof(*saved_argv
));
1386 for (i
= 0; i
< ac
; i
++)
1387 saved_argv
[i
] = xstrdup(av
[i
]);
1388 saved_argv
[i
] = NULL
;
1390 #ifndef HAVE_SETPROCTITLE
1391 /* Prepare for later setproctitle emulation */
1392 compat_init_setproctitle(ac
, av
);
1396 if (geteuid() == 0 && setgroups(0, NULL
) == -1)
1397 debug("setgroups(): %.200s", strerror(errno
));
1399 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1402 /* Initialize configuration options to their default values. */
1403 initialize_server_options(&options
);
1405 /* Parse command-line arguments. */
1406 while ((opt
= getopt(ac
, av
,
1407 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1410 options
.address_family
= AF_INET
;
1413 options
.address_family
= AF_INET6
;
1416 config_file_name
= optarg
;
1419 if (options
.num_host_cert_files
>= MAX_HOSTCERTS
) {
1420 fprintf(stderr
, "too many host certificates.\n");
1423 options
.host_cert_files
[options
.num_host_cert_files
++] =
1424 derelativise_path(optarg
);
1427 if (debug_flag
== 0) {
1429 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
1430 } else if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
1431 options
.log_level
++;
1456 options
.log_level
= SYSLOG_LEVEL_QUIET
;
1459 /* protocol 1, ignored */
1462 options
.ports_from_cmdline
= 1;
1463 if (options
.num_ports
>= MAX_PORTS
) {
1464 fprintf(stderr
, "too many ports.\n");
1467 options
.ports
[options
.num_ports
++] = a2port(optarg
);
1468 if (options
.ports
[options
.num_ports
-1] <= 0) {
1469 fprintf(stderr
, "Bad port number.\n");
1474 if ((options
.login_grace_time
= convtime(optarg
)) == -1) {
1475 fprintf(stderr
, "Invalid login grace time.\n");
1480 /* protocol 1, ignored */
1483 if (options
.num_host_key_files
>= MAX_HOSTKEYS
) {
1484 fprintf(stderr
, "too many host keys.\n");
1487 options
.host_key_files
[options
.num_host_key_files
++] =
1488 derelativise_path(optarg
);
1497 if (parse_server_match_testspec(connection_info
,
1502 utmp_len
= (u_int
)strtonum(optarg
, 0, HOST_NAME_MAX
+1+1, NULL
);
1503 if (utmp_len
> HOST_NAME_MAX
+1) {
1504 fprintf(stderr
, "Invalid utmp length.\n");
1509 line
= xstrdup(optarg
);
1510 if (process_server_config_line(&options
, line
,
1511 "command-line", 0, NULL
, NULL
) != 0)
1521 if (rexeced_flag
|| inetd_flag
)
1523 if (!test_flag
&& (rexec_flag
&& (av
[0] == NULL
|| *av
[0] != '/')))
1524 fatal("sshd re-exec requires execution with an absolute path");
1526 closefrom(REEXEC_MIN_FREE_FD
);
1528 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD
);
1531 OpenSSL_add_all_algorithms();
1534 /* If requested, redirect the logs to the specified logfile. */
1535 if (logfile
!= NULL
)
1536 log_redirect_stderr_to(logfile
);
1538 * Force logging to stderr until we have loaded the private host
1539 * key (unless started from inetd)
1541 log_init(__progname
,
1542 options
.log_level
== SYSLOG_LEVEL_NOT_SET
?
1543 SYSLOG_LEVEL_INFO
: options
.log_level
,
1544 options
.log_facility
== SYSLOG_FACILITY_NOT_SET
?
1545 SYSLOG_FACILITY_AUTH
: options
.log_facility
,
1546 log_stderr
|| !inetd_flag
);
1549 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1550 * root's environment
1552 if (getenv("KRB5CCNAME") != NULL
)
1553 (void) unsetenv("KRB5CCNAME");
1556 /* Cray can define user privs drop all privs now!
1557 * Not needed on PRIV_SU systems!
1562 sensitive_data
.have_ssh2_key
= 0;
1565 * If we're doing an extended config test, make sure we have all of
1566 * the parameters we need. If we're not doing an extended test,
1567 * do not silently ignore connection test params.
1569 if (test_flag
>= 2 && server_match_spec_complete(connection_info
) == 0)
1570 fatal("user, host and addr are all required when testing "
1572 if (test_flag
< 2 && server_match_spec_complete(connection_info
) >= 0)
1573 fatal("Config test connection parameter (-C) provided without "
1576 /* Fetch our configuration */
1579 recv_rexec_state(REEXEC_CONFIG_PASS_FD
, &cfg
);
1580 else if (strcasecmp(config_file_name
, "none") != 0)
1581 load_server_config(config_file_name
, &cfg
);
1583 parse_server_config(&options
, rexeced_flag
? "rexec" : config_file_name
,
1588 /* Fill in default values for those options not explicitly set. */
1589 fill_default_server_options(&options
);
1591 /* challenge-response is implemented via keyboard interactive */
1592 if (options
.challenge_response_authentication
)
1593 options
.kbd_interactive_authentication
= 1;
1595 /* Check that options are sensible */
1596 if (options
.authorized_keys_command_user
== NULL
&&
1597 (options
.authorized_keys_command
!= NULL
&&
1598 strcasecmp(options
.authorized_keys_command
, "none") != 0))
1599 fatal("AuthorizedKeysCommand set without "
1600 "AuthorizedKeysCommandUser");
1601 if (options
.authorized_principals_command_user
== NULL
&&
1602 (options
.authorized_principals_command
!= NULL
&&
1603 strcasecmp(options
.authorized_principals_command
, "none") != 0))
1604 fatal("AuthorizedPrincipalsCommand set without "
1605 "AuthorizedPrincipalsCommandUser");
1608 * Check whether there is any path through configured auth methods.
1609 * Unfortunately it is not possible to verify this generally before
1610 * daemonisation in the presence of Match block, but this catches
1611 * and warns for trivial misconfigurations that could break login.
1613 if (options
.num_auth_methods
!= 0) {
1614 for (n
= 0; n
< options
.num_auth_methods
; n
++) {
1615 if (auth2_methods_valid(options
.auth_methods
[n
],
1619 if (n
>= options
.num_auth_methods
)
1620 fatal("AuthenticationMethods cannot be satisfied by "
1621 "enabled authentication methods");
1624 /* Check that there are no remaining arguments. */
1626 fprintf(stderr
, "Extra argument %s.\n", av
[optind
]);
1630 debug("sshd version %s, %s", SSH_VERSION
,
1632 SSLeay_version(SSLEAY_VERSION
)
1638 /* Store privilege separation user for later use if required. */
1639 privsep_chroot
= use_privsep
&& (getuid() == 0 || geteuid() == 0);
1640 if ((privsep_pw
= getpwnam(SSH_PRIVSEP_USER
)) == NULL
) {
1641 if (privsep_chroot
|| options
.kerberos_authentication
)
1642 fatal("Privilege separation user %s does not exist",
1645 explicit_bzero(privsep_pw
->pw_passwd
,
1646 strlen(privsep_pw
->pw_passwd
));
1647 privsep_pw
= pwcopy(privsep_pw
);
1648 free(privsep_pw
->pw_passwd
);
1649 privsep_pw
->pw_passwd
= xstrdup("*");
1653 /* load host keys */
1654 sensitive_data
.host_keys
= xcalloc(options
.num_host_key_files
,
1655 sizeof(struct sshkey
*));
1656 sensitive_data
.host_pubkeys
= xcalloc(options
.num_host_key_files
,
1657 sizeof(struct sshkey
*));
1659 if (options
.host_key_agent
) {
1660 if (strcmp(options
.host_key_agent
, SSH_AUTHSOCKET_ENV_NAME
))
1661 setenv(SSH_AUTHSOCKET_ENV_NAME
,
1662 options
.host_key_agent
, 1);
1663 if ((r
= ssh_get_authentication_socket(NULL
)) == 0)
1666 error("Could not connect to agent \"%s\": %s",
1667 options
.host_key_agent
, ssh_err(r
));
1670 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
1671 if (options
.host_key_files
[i
] == NULL
)
1673 key
= key_load_private(options
.host_key_files
[i
], "", NULL
);
1674 pubkey
= key_load_public(options
.host_key_files
[i
], NULL
);
1676 if (pubkey
== NULL
&& key
!= NULL
)
1677 pubkey
= key_demote(key
);
1678 sensitive_data
.host_keys
[i
] = key
;
1679 sensitive_data
.host_pubkeys
[i
] = pubkey
;
1681 if (key
== NULL
&& pubkey
!= NULL
&& have_agent
) {
1682 debug("will rely on agent for hostkey %s",
1683 options
.host_key_files
[i
]);
1684 keytype
= pubkey
->type
;
1685 } else if (key
!= NULL
) {
1686 keytype
= key
->type
;
1688 error("Could not load host key: %s",
1689 options
.host_key_files
[i
]);
1690 sensitive_data
.host_keys
[i
] = NULL
;
1691 sensitive_data
.host_pubkeys
[i
] = NULL
;
1700 if (have_agent
|| key
!= NULL
)
1701 sensitive_data
.have_ssh2_key
= 1;
1704 if ((fp
= sshkey_fingerprint(pubkey
, options
.fingerprint_hash
,
1705 SSH_FP_DEFAULT
)) == NULL
)
1706 fatal("sshkey_fingerprint failed");
1707 debug("%s host key #%d: %s %s",
1708 key
? "private" : "agent", i
, sshkey_ssh_name(pubkey
), fp
);
1711 if (!sensitive_data
.have_ssh2_key
) {
1712 logit("sshd: no hostkeys available -- exiting.");
1717 * Load certificates. They are stored in an array at identical
1718 * indices to the public keys that they relate to.
1720 sensitive_data
.host_certificates
= xcalloc(options
.num_host_key_files
,
1721 sizeof(struct sshkey
*));
1722 for (i
= 0; i
< options
.num_host_key_files
; i
++)
1723 sensitive_data
.host_certificates
[i
] = NULL
;
1725 for (i
= 0; i
< options
.num_host_cert_files
; i
++) {
1726 if (options
.host_cert_files
[i
] == NULL
)
1728 key
= key_load_public(options
.host_cert_files
[i
], NULL
);
1730 error("Could not load host certificate: %s",
1731 options
.host_cert_files
[i
]);
1734 if (!key_is_cert(key
)) {
1735 error("Certificate file is not a certificate: %s",
1736 options
.host_cert_files
[i
]);
1740 /* Find matching private key */
1741 for (j
= 0; j
< options
.num_host_key_files
; j
++) {
1742 if (key_equal_public(key
,
1743 sensitive_data
.host_keys
[j
])) {
1744 sensitive_data
.host_certificates
[j
] = key
;
1748 if (j
>= options
.num_host_key_files
) {
1749 error("No matching private key for certificate: %s",
1750 options
.host_cert_files
[i
]);
1754 sensitive_data
.host_certificates
[j
] = key
;
1755 debug("host certificate: #%d type %d %s", j
, key
->type
,
1759 if (privsep_chroot
) {
1762 if ((stat(_PATH_PRIVSEP_CHROOT_DIR
, &st
) == -1) ||
1763 (S_ISDIR(st
.st_mode
) == 0))
1764 fatal("Missing privilege separation directory: %s",
1765 _PATH_PRIVSEP_CHROOT_DIR
);
1768 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR
) &&
1769 (st
.st_uid
!= getuid () ||
1770 (st
.st_mode
& (S_IWGRP
|S_IWOTH
)) != 0))
1772 if (st
.st_uid
!= 0 || (st
.st_mode
& (S_IWGRP
|S_IWOTH
)) != 0)
1774 fatal("%s must be owned by root and not group or "
1775 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR
);
1778 if (test_flag
> 1) {
1779 if (server_match_spec_complete(connection_info
) == 1)
1780 parse_server_match_config(&options
, connection_info
);
1781 dump_config(&options
);
1784 /* Configuration looks good, so exit if in test mode. */
1789 * Clear out any supplemental groups we may have inherited. This
1790 * prevents inadvertent creation of files with bad modes (in the
1791 * portable version at least, it's certainly possible for PAM
1792 * to create a file, and we can't control the code in every
1793 * module which might be used).
1795 if (setgroups(0, NULL
) < 0)
1796 debug("setgroups() failed: %.200s", strerror(errno
));
1799 rexec_argv
= xcalloc(rexec_argc
+ 2, sizeof(char *));
1800 for (i
= 0; i
< rexec_argc
; i
++) {
1801 debug("rexec_argv[%d]='%s'", i
, saved_argv
[i
]);
1802 rexec_argv
[i
] = saved_argv
[i
];
1804 rexec_argv
[rexec_argc
] = "-R";
1805 rexec_argv
[rexec_argc
+ 1] = NULL
;
1808 /* Ensure that umask disallows at least group and world write */
1809 new_umask
= umask(0077) | 0022;
1810 (void) umask(new_umask
);
1812 /* Initialize the log (it is reinitialized below in case we forked). */
1813 if (debug_flag
&& (!inetd_flag
|| rexeced_flag
))
1815 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
1818 * If not in debugging mode, not started from inetd and not already
1819 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1820 * terminal, and fork. The original process exits.
1822 already_daemon
= daemonized();
1823 if (!(debug_flag
|| inetd_flag
|| no_daemon_flag
|| already_daemon
)) {
1825 if (daemon(0, 0) < 0)
1826 fatal("daemon() failed: %.200s", strerror(errno
));
1828 disconnect_controlling_tty();
1830 /* Reinitialize the log (because of the fork above). */
1831 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
1833 /* Chdir to the root directory so that the current disk can be
1834 unmounted if desired. */
1835 if (chdir("/") == -1)
1836 error("chdir(\"/\"): %s", strerror(errno
));
1838 /* ignore SIGPIPE */
1839 signal(SIGPIPE
, SIG_IGN
);
1841 /* Get a connection, either from inetd or a listening TCP socket */
1843 server_accept_inetd(&sock_in
, &sock_out
);
1845 platform_pre_listen();
1848 signal(SIGHUP
, sighup_handler
);
1849 signal(SIGCHLD
, main_sigchld_handler
);
1850 signal(SIGTERM
, sigterm_handler
);
1851 signal(SIGQUIT
, sigterm_handler
);
1854 * Write out the pid file after the sigterm handler
1855 * is setup and the listen sockets are bound
1857 if (options
.pid_file
!= NULL
&& !debug_flag
) {
1858 FILE *f
= fopen(options
.pid_file
, "w");
1861 error("Couldn't create pid file \"%s\": %s",
1862 options
.pid_file
, strerror(errno
));
1864 fprintf(f
, "%ld\n", (long) getpid());
1869 /* Accept a connection and return in a forked child */
1870 server_accept_loop(&sock_in
, &sock_out
,
1871 &newsock
, config_s
);
1874 /* This is the child processing a new connection. */
1875 setproctitle("%s", "[accepted]");
1878 * Create a new session and process group since the 4.4BSD
1879 * setlogin() affects the entire process group. We don't
1880 * want the child to be able to affect the parent.
1882 #if !defined(SSHD_ACQUIRES_CTTY)
1884 * If setsid is called, on some platforms sshd will later acquire a
1885 * controlling terminal which will result in "could not set
1886 * controlling tty" errors.
1888 if (!debug_flag
&& !inetd_flag
&& setsid() < 0)
1889 error("setsid: %.100s", strerror(errno
));
1895 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1896 sock_in
, sock_out
, newsock
, startup_pipe
, config_s
[0]);
1897 dup2(newsock
, STDIN_FILENO
);
1898 dup2(STDIN_FILENO
, STDOUT_FILENO
);
1899 if (startup_pipe
== -1)
1900 close(REEXEC_STARTUP_PIPE_FD
);
1901 else if (startup_pipe
!= REEXEC_STARTUP_PIPE_FD
) {
1902 dup2(startup_pipe
, REEXEC_STARTUP_PIPE_FD
);
1903 close(startup_pipe
);
1904 startup_pipe
= REEXEC_STARTUP_PIPE_FD
;
1907 dup2(config_s
[1], REEXEC_CONFIG_PASS_FD
);
1910 execv(rexec_argv
[0], rexec_argv
);
1912 /* Reexec has failed, fall back and continue */
1913 error("rexec of %s failed: %s", rexec_argv
[0], strerror(errno
));
1914 recv_rexec_state(REEXEC_CONFIG_PASS_FD
, NULL
);
1915 log_init(__progname
, options
.log_level
,
1916 options
.log_facility
, log_stderr
);
1919 close(REEXEC_CONFIG_PASS_FD
);
1920 newsock
= sock_out
= sock_in
= dup(STDIN_FILENO
);
1921 if ((fd
= open(_PATH_DEVNULL
, O_RDWR
, 0)) != -1) {
1922 dup2(fd
, STDIN_FILENO
);
1923 dup2(fd
, STDOUT_FILENO
);
1924 if (fd
> STDERR_FILENO
)
1927 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1928 sock_in
, sock_out
, newsock
, startup_pipe
, config_s
[0]);
1931 /* Executed child processes don't need these. */
1932 fcntl(sock_out
, F_SETFD
, FD_CLOEXEC
);
1933 fcntl(sock_in
, F_SETFD
, FD_CLOEXEC
);
1936 * Disable the key regeneration alarm. We will not regenerate the
1937 * key since we are no longer in a position to give it to anyone. We
1938 * will not restart on SIGHUP since it no longer makes sense.
1941 signal(SIGALRM
, SIG_DFL
);
1942 signal(SIGHUP
, SIG_DFL
);
1943 signal(SIGTERM
, SIG_DFL
);
1944 signal(SIGQUIT
, SIG_DFL
);
1945 signal(SIGCHLD
, SIG_DFL
);
1946 signal(SIGINT
, SIG_DFL
);
1949 * Register our connection. This turns encryption off because we do
1952 packet_set_connection(sock_in
, sock_out
);
1953 packet_set_server();
1954 ssh
= active_state
; /* XXX */
1956 check_ip_options(ssh
);
1958 /* Prepare the channels layer */
1959 channel_init_channels(ssh
);
1960 channel_set_af(ssh
, options
.address_family
);
1961 process_permitopen(ssh
, &options
);
1963 /* Set SO_KEEPALIVE if requested. */
1964 if (options
.tcp_keep_alive
&& packet_connection_is_on_socket() &&
1965 setsockopt(sock_in
, SOL_SOCKET
, SO_KEEPALIVE
, &on
, sizeof(on
)) < 0)
1966 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno
));
1968 if ((remote_port
= ssh_remote_port(ssh
)) < 0) {
1969 debug("ssh_remote_port failed");
1974 * The rest of the code depends on the fact that
1975 * ssh_remote_ipaddr() caches the remote ip, even if
1976 * the socket goes away.
1978 remote_ip
= ssh_remote_ipaddr(ssh
);
1980 #ifdef SSH_AUDIT_EVENTS
1981 audit_connection_from(remote_ip
, remote_port
);
1984 /* Log the connection. */
1985 laddr
= get_local_ipaddr(sock_in
);
1986 verbose("Connection from %s port %d on %s port %d",
1987 remote_ip
, remote_port
, laddr
, ssh_local_port(ssh
));
1991 * We don't want to listen forever unless the other side
1992 * successfully authenticates itself. So we set up an alarm which is
1993 * cleared after successful authentication. A limit of zero
1994 * indicates no limit. Note that we don't set the alarm in debugging
1995 * mode; it is just annoying to have the server exit just when you
1996 * are about to discover the bug.
1998 signal(SIGALRM
, grace_alarm_handler
);
2000 alarm(options
.login_grace_time
);
2002 sshd_exchange_identification(ssh
, sock_in
, sock_out
);
2003 packet_set_nonblocking();
2005 /* allocate authentication context */
2006 authctxt
= xcalloc(1, sizeof(*authctxt
));
2008 authctxt
->loginmsg
= &loginmsg
;
2010 /* XXX global for cleanup, access from other modules */
2011 the_authctxt
= authctxt
;
2013 /* prepare buffer to collect messages to display to user after login */
2014 buffer_init(&loginmsg
);
2018 if (privsep_preauth(authctxt
) == 1)
2020 } else if (have_agent
) {
2021 if ((r
= ssh_get_authentication_socket(&auth_sock
)) != 0) {
2022 error("Unable to get agent socket: %s", ssh_err(r
));
2027 /* perform the key exchange */
2028 /* authenticate user and start session */
2030 do_authentication2(authctxt
);
2033 * If we use privilege separation, the unprivileged child transfers
2034 * the current keystate and exits
2037 mm_send_keystate(pmonitor
);
2038 packet_clear_keys();
2044 * Cancel the alarm we set to limit the time taken for
2048 signal(SIGALRM
, SIG_DFL
);
2049 authctxt
->authenticated
= 1;
2050 if (startup_pipe
!= -1) {
2051 close(startup_pipe
);
2055 #ifdef SSH_AUDIT_EVENTS
2056 audit_event(SSH_AUTH_SUCCESS
);
2060 if (options
.gss_authentication
) {
2061 temporarily_use_uid(authctxt
->pw
);
2062 ssh_gssapi_storecreds();
2067 if (options
.use_pam
) {
2074 * In privilege separation, we fork another child and prepare
2075 * file descriptor passing.
2078 privsep_postauth(authctxt
);
2079 /* the monitor process [priv] will not return */
2082 packet_set_timeout(options
.client_alive_interval
,
2083 options
.client_alive_count_max
);
2085 /* Try to send all our hostkeys to the client */
2086 notify_hostkeys(ssh
);
2088 /* Start session. */
2089 do_authenticated(ssh
, authctxt
);
2091 /* The connection has been terminated. */
2092 packet_get_bytes(&ibytes
, &obytes
);
2093 verbose("Transferred: sent %llu, received %llu bytes",
2094 (unsigned long long)obytes
, (unsigned long long)ibytes
);
2096 verbose("Closing connection to %.500s port %d", remote_ip
, remote_port
);
2099 if (options
.use_pam
)
2101 #endif /* USE_PAM */
2103 #ifdef SSH_AUDIT_EVENTS
2104 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE
));
2116 sshd_hostkey_sign(struct sshkey
*privkey
, struct sshkey
*pubkey
,
2117 u_char
**signature
, size_t *slen
, const u_char
*data
, size_t dlen
,
2118 const char *alg
, u_int flag
)
2121 u_int xxx_slen
, xxx_dlen
= dlen
;
2124 if (PRIVSEP(key_sign(privkey
, signature
, &xxx_slen
, data
, xxx_dlen
,
2126 fatal("%s: key_sign failed", __func__
);
2129 } else if (use_privsep
) {
2130 if (mm_key_sign(pubkey
, signature
, &xxx_slen
, data
, xxx_dlen
,
2132 fatal("%s: pubkey_sign failed", __func__
);
2136 if ((r
= ssh_agent_sign(auth_sock
, pubkey
, signature
, slen
,
2137 data
, dlen
, alg
, datafellows
)) != 0)
2138 fatal("%s: ssh_agent_sign failed: %s",
2139 __func__
, ssh_err(r
));
2144 /* SSH2 key exchange */
2148 char *myproposal
[PROPOSAL_MAX
] = { KEX_SERVER
};
2152 myproposal
[PROPOSAL_KEX_ALGS
] = compat_kex_proposal(
2153 options
.kex_algorithms
);
2154 myproposal
[PROPOSAL_ENC_ALGS_CTOS
] = compat_cipher_proposal(
2156 myproposal
[PROPOSAL_ENC_ALGS_STOC
] = compat_cipher_proposal(
2158 myproposal
[PROPOSAL_MAC_ALGS_CTOS
] =
2159 myproposal
[PROPOSAL_MAC_ALGS_STOC
] = options
.macs
;
2161 if (options
.compression
== COMP_NONE
) {
2162 myproposal
[PROPOSAL_COMP_ALGS_CTOS
] =
2163 myproposal
[PROPOSAL_COMP_ALGS_STOC
] = "none";
2166 if (options
.rekey_limit
|| options
.rekey_interval
)
2167 packet_set_rekey_limits(options
.rekey_limit
,
2168 options
.rekey_interval
);
2170 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = compat_pkalg_proposal(
2171 list_hostkey_types());
2173 /* start key exchange */
2174 if ((r
= kex_setup(active_state
, myproposal
)) != 0)
2175 fatal("kex_setup: %s", ssh_err(r
));
2176 kex
= active_state
->kex
;
2178 kex
->kex
[KEX_DH_GRP1_SHA1
] = kexdh_server
;
2179 kex
->kex
[KEX_DH_GRP14_SHA1
] = kexdh_server
;
2180 kex
->kex
[KEX_DH_GRP14_SHA256
] = kexdh_server
;
2181 kex
->kex
[KEX_DH_GRP16_SHA512
] = kexdh_server
;
2182 kex
->kex
[KEX_DH_GRP18_SHA512
] = kexdh_server
;
2183 kex
->kex
[KEX_DH_GEX_SHA1
] = kexgex_server
;
2184 kex
->kex
[KEX_DH_GEX_SHA256
] = kexgex_server
;
2185 # ifdef OPENSSL_HAS_ECC
2186 kex
->kex
[KEX_ECDH_SHA2
] = kexecdh_server
;
2189 kex
->kex
[KEX_C25519_SHA256
] = kexc25519_server
;
2191 kex
->client_version_string
=client_version_string
;
2192 kex
->server_version_string
=server_version_string
;
2193 kex
->load_host_public_key
=&get_hostkey_public_by_type
;
2194 kex
->load_host_private_key
=&get_hostkey_private_by_type
;
2195 kex
->host_key_index
=&get_hostkey_index
;
2196 kex
->sign
= sshd_hostkey_sign
;
2198 ssh_dispatch_run_fatal(active_state
, DISPATCH_BLOCK
, &kex
->done
);
2200 session_id2
= kex
->session_id
;
2201 session_id2_len
= kex
->session_id_len
;
2204 /* send 1st encrypted/maced/compressed message */
2205 packet_start(SSH2_MSG_IGNORE
);
2206 packet_put_cstring("markus");
2208 packet_write_wait();
2213 /* server specific fatal cleanup */
2217 struct ssh
*ssh
= active_state
; /* XXX */
2220 do_cleanup(ssh
, the_authctxt
);
2221 if (use_privsep
&& privsep_is_preauth
&&
2222 pmonitor
!= NULL
&& pmonitor
->m_pid
> 1) {
2223 debug("Killing privsep child %d", pmonitor
->m_pid
);
2224 if (kill(pmonitor
->m_pid
, SIGKILL
) != 0 &&
2226 error("%s: kill(%d): %s", __func__
,
2227 pmonitor
->m_pid
, strerror(errno
));
2230 #ifdef SSH_AUDIT_EVENTS
2231 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2232 if (!use_privsep
|| mm_is_monitor())
2233 audit_event(SSH_CONNECTION_ABANDON
);