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