blob: a1e48b9325fbb0b6dc5d1fa448c3f502df1a5d36 [file] [log] [blame]
Greg Hartman9768ca42017-06-22 20:49:52 -07001/* $OpenBSD: sshd.c,v 1.485 2017/03/15 03:52:30 deraadt Exp $ */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
11 *
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
17 *
18 * SSH2 implementation:
19 * Privilege Separation:
20 *
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
23 *
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
26 * are met:
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 */
44
45#include "includes.h"
46
47#include <sys/types.h>
48#include <sys/ioctl.h>
49#include <sys/socket.h>
50#ifdef HAVE_SYS_STAT_H
51# include <sys/stat.h>
52#endif
53#ifdef HAVE_SYS_TIME_H
54# include <sys/time.h>
55#endif
56#include "openbsd-compat/sys-tree.h"
57#include "openbsd-compat/sys-queue.h"
58#include <sys/wait.h>
59
60#include <errno.h>
61#include <fcntl.h>
62#include <netdb.h>
63#ifdef HAVE_PATHS_H
64#include <paths.h>
65#endif
66#include <grp.h>
67#include <pwd.h>
68#include <signal.h>
69#include <stdarg.h>
70#include <stdio.h>
71#include <stdlib.h>
72#include <string.h>
73#include <unistd.h>
Adam Langleyd0592972015-03-30 14:49:51 -070074#include <limits.h>
Greg Hartmanbd77cf72015-02-25 13:21:06 -080075
Adam Langleyd0592972015-03-30 14:49:51 -070076#ifdef WITH_OPENSSL
Greg Hartmanbd77cf72015-02-25 13:21:06 -080077#include <openssl/dh.h>
78#include <openssl/bn.h>
Greg Hartmanbd77cf72015-02-25 13:21:06 -080079#include <openssl/rand.h>
80#include "openbsd-compat/openssl-compat.h"
Adam Langleyd0592972015-03-30 14:49:51 -070081#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -080082
83#ifdef HAVE_SECUREWARE
84#include <sys/security.h>
85#include <prot.h>
86#endif
87
88#include "xmalloc.h"
89#include "ssh.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -080090#include "ssh2.h"
91#include "rsa.h"
92#include "sshpty.h"
93#include "packet.h"
94#include "log.h"
95#include "buffer.h"
Adam Langleyd0592972015-03-30 14:49:51 -070096#include "misc.h"
Greg Hartmanccacbc92016-02-03 09:59:44 -080097#include "match.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -080098#include "servconf.h"
99#include "uidswap.h"
100#include "compat.h"
101#include "cipher.h"
Adam Langleyd0592972015-03-30 14:49:51 -0700102#include "digest.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800103#include "key.h"
104#include "kex.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800105#include "myproposal.h"
106#include "authfile.h"
107#include "pathnames.h"
108#include "atomicio.h"
109#include "canohost.h"
110#include "hostfile.h"
111#include "auth.h"
Adam Langleyd0592972015-03-30 14:49:51 -0700112#include "authfd.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800113#include "msg.h"
114#include "dispatch.h"
115#include "channels.h"
116#include "session.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800117#include "monitor.h"
118#ifdef GSSAPI
119#include "ssh-gss.h"
120#endif
121#include "monitor_wrap.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800122#include "ssh-sandbox.h"
123#include "version.h"
Adam Langleyd0592972015-03-30 14:49:51 -0700124#include "ssherr.h"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800125
Greg Hartman786d35e2017-10-25 07:25:43 -0700126#if defined(ANDROID_GCE) && defined(GCE_PLATFORM_SDK_VERSION) && GCE_PLATFORM_SDK_VERSION >= 28
127#define GNU_SOURCE
128#include <sched.h>
129#endif
130
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800131/* Re-exec fds */
132#define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
133#define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
134#define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
135#define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
136
137extern char *__progname;
138
139/* Server configuration options. */
140ServerOptions options;
141
142/* Name of the server configuration file. */
143char *config_file_name = _PATH_SERVER_CONFIG_FILE;
144
145/*
146 * Debug mode flag. This can be set on the command line. If debug
147 * mode is enabled, extra debugging output will be sent to the system
148 * log, the daemon will not go to background, and will exit after processing
149 * the first connection.
150 */
151int debug_flag = 0;
152
153/* Flag indicating that the daemon should only test the configuration and keys. */
154int test_flag = 0;
155
156/* Flag indicating that the daemon is being started from inetd. */
157int inetd_flag = 0;
158
159/* Flag indicating that sshd should not detach and become a daemon. */
160int no_daemon_flag = 0;
161
162/* debug goes to stderr unless inetd_flag is set */
163int log_stderr = 0;
164
165/* Saved arguments to main(). */
166char **saved_argv;
167int saved_argc;
168
169/* re-exec */
170int rexeced_flag = 0;
171int rexec_flag = 1;
172int rexec_argc = 0;
173char **rexec_argv;
174
175/*
176 * The sockets that the server is listening; this is used in the SIGHUP
177 * signal handler.
178 */
179#define MAX_LISTEN_SOCKS 16
180int listen_socks[MAX_LISTEN_SOCKS];
181int num_listen_socks = 0;
182
183/*
184 * the client's version string, passed by sshd2 in compat mode. if != NULL,
185 * sshd will skip the version-number exchange
186 */
187char *client_version_string = NULL;
188char *server_version_string = NULL;
189
Adam Langleyd0592972015-03-30 14:49:51 -0700190/* Daemon's agent connection */
191int auth_sock = -1;
192int have_agent = 0;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800193
194/*
195 * Any really sensitive data in the application is contained in this
196 * structure. The idea is that this structure could be locked into memory so
197 * that the pages do not get written into swap. However, there are some
198 * problems. The private key contains BIGNUMs, and we do not (in principle)
199 * have access to the internals of them, and locking just the structure is
200 * not very useful. Currently, memory locking is not implemented.
201 */
202struct {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800203 Key **host_keys; /* all private host keys */
Adam Langleyd0592972015-03-30 14:49:51 -0700204 Key **host_pubkeys; /* all public host keys */
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800205 Key **host_certificates; /* all public host certificates */
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800206 int have_ssh2_key;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800207} sensitive_data;
208
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800209/* This is set to true when a signal is received. */
210static volatile sig_atomic_t received_sighup = 0;
211static volatile sig_atomic_t received_sigterm = 0;
212
213/* session identifier, used by RSA-auth */
214u_char session_id[16];
215
216/* same for ssh2 */
217u_char *session_id2 = NULL;
218u_int session_id2_len = 0;
219
220/* record remote hostname or ip */
Adam Langleyd0592972015-03-30 14:49:51 -0700221u_int utmp_len = HOST_NAME_MAX+1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800222
223/* options.max_startup sized array of fd ints */
224int *startup_pipes = NULL;
225int startup_pipe; /* in child */
226
227/* variables used for privilege separation */
228int use_privsep = -1;
229struct monitor *pmonitor = NULL;
Adam Langleyd0592972015-03-30 14:49:51 -0700230int privsep_is_preauth = 1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800231
232/* global authentication context */
233Authctxt *the_authctxt = NULL;
234
235/* sshd_config buffer */
236Buffer cfg;
237
238/* message to be displayed after login */
239Buffer loginmsg;
240
241/* Unprivileged user */
242struct passwd *privsep_pw = NULL;
243
244/* Prototypes for various functions defined later in this file. */
245void destroy_sensitive_data(void);
246void demote_sensitive_data(void);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800247static void do_ssh2_kex(void);
248
249/*
250 * Close all listening sockets
251 */
252static void
253close_listen_socks(void)
254{
255 int i;
256
257 for (i = 0; i < num_listen_socks; i++)
258 close(listen_socks[i]);
259 num_listen_socks = -1;
260}
261
262static void
263close_startup_pipes(void)
264{
265 int i;
266
267 if (startup_pipes)
268 for (i = 0; i < options.max_startups; i++)
269 if (startup_pipes[i] != -1)
270 close(startup_pipes[i]);
271}
272
273/*
274 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
275 * the effect is to reread the configuration file (and to regenerate
276 * the server key).
277 */
278
279/*ARGSUSED*/
280static void
281sighup_handler(int sig)
282{
283 int save_errno = errno;
284
285 received_sighup = 1;
286 signal(SIGHUP, sighup_handler);
287 errno = save_errno;
288}
289
290/*
291 * Called from the main program after receiving SIGHUP.
292 * Restarts the server.
293 */
294static void
295sighup_restart(void)
296{
297 logit("Received SIGHUP; restarting.");
Greg Hartman9768ca42017-06-22 20:49:52 -0700298 if (options.pid_file != NULL)
299 unlink(options.pid_file);
Adam Langleyd0592972015-03-30 14:49:51 -0700300 platform_pre_restart();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800301 close_listen_socks();
302 close_startup_pipes();
303 alarm(0); /* alarm timer persists across exec */
304 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
305 execv(saved_argv[0], saved_argv);
306 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
307 strerror(errno));
308 exit(1);
309}
310
311/*
312 * Generic signal handler for terminating signals in the master daemon.
313 */
314/*ARGSUSED*/
315static void
316sigterm_handler(int sig)
317{
318 received_sigterm = sig;
319}
320
321/*
322 * SIGCHLD handler. This is called whenever a child dies. This will then
323 * reap any zombies left by exited children.
324 */
325/*ARGSUSED*/
326static void
327main_sigchld_handler(int sig)
328{
329 int save_errno = errno;
330 pid_t pid;
331 int status;
332
333 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
334 (pid < 0 && errno == EINTR))
335 ;
336
337 signal(SIGCHLD, main_sigchld_handler);
338 errno = save_errno;
339}
340
341/*
342 * Signal handler for the alarm after the login grace period has expired.
343 */
344/*ARGSUSED*/
345static void
346grace_alarm_handler(int sig)
347{
348 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
349 kill(pmonitor->m_pid, SIGALRM);
350
Adam Langleyd0592972015-03-30 14:49:51 -0700351 /*
352 * Try to kill any processes that we have spawned, E.g. authorized
353 * keys command helpers.
354 */
355 if (getpgid(0) == getpid()) {
356 signal(SIGTERM, SIG_IGN);
357 kill(0, SIGTERM);
358 }
359
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800360 /* Log error and exit. */
Greg Hartman9768ca42017-06-22 20:49:52 -0700361 sigdie("Timeout before authentication for %s port %d",
362 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800363}
364
365static void
Greg Hartman9768ca42017-06-22 20:49:52 -0700366sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800367{
368 u_int i;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800369 int remote_major, remote_minor;
Greg Hartman9768ca42017-06-22 20:49:52 -0700370 char *s;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800371 char buf[256]; /* Must not be larger than remote_version. */
372 char remote_version[256]; /* Must be at least as big as buf. */
373
Greg Hartman9768ca42017-06-22 20:49:52 -0700374 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
375 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
Adam Langleyd0592972015-03-30 14:49:51 -0700376 *options.version_addendum == '\0' ? "" : " ",
Greg Hartman9768ca42017-06-22 20:49:52 -0700377 options.version_addendum);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800378
379 /* Send our protocol version identification. */
Greg Hartman9768ca42017-06-22 20:49:52 -0700380 if (atomicio(vwrite, sock_out, server_version_string,
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800381 strlen(server_version_string))
382 != strlen(server_version_string)) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700383 logit("Could not write ident string to %s port %d",
384 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800385 cleanup_exit(255);
386 }
387
388 /* Read other sides version identification. */
389 memset(buf, 0, sizeof(buf));
390 for (i = 0; i < sizeof(buf) - 1; i++) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700391 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
392 logit("Did not receive identification string "
393 "from %s port %d",
394 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800395 cleanup_exit(255);
396 }
397 if (buf[i] == '\r') {
398 buf[i] = 0;
399 /* Kludge for F-Secure Macintosh < 1.0.2 */
400 if (i == 12 &&
401 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
402 break;
403 continue;
404 }
405 if (buf[i] == '\n') {
406 buf[i] = 0;
407 break;
408 }
409 }
410 buf[sizeof(buf) - 1] = 0;
411 client_version_string = xstrdup(buf);
412
413 /*
414 * Check that the versions match. In future this might accept
415 * several versions and set appropriate flags to handle them.
416 */
417 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
418 &remote_major, &remote_minor, remote_version) != 3) {
419 s = "Protocol mismatch.\n";
420 (void) atomicio(vwrite, sock_out, s, strlen(s));
Adam Langleyd0592972015-03-30 14:49:51 -0700421 logit("Bad protocol version identification '%.100s' "
422 "from %s port %d", client_version_string,
Greg Hartman9768ca42017-06-22 20:49:52 -0700423 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800424 close(sock_in);
425 close(sock_out);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800426 cleanup_exit(255);
427 }
428 debug("Client protocol version %d.%d; client software version %.100s",
429 remote_major, remote_minor, remote_version);
430
Greg Hartman9768ca42017-06-22 20:49:52 -0700431 ssh->compat = compat_datafellows(remote_version);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800432
Greg Hartman9768ca42017-06-22 20:49:52 -0700433 if ((ssh->compat & SSH_BUG_PROBE) != 0) {
434 logit("probed from %s port %d with %s. Don't panic.",
435 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
436 client_version_string);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800437 cleanup_exit(255);
438 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700439 if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
440 logit("scanned from %s port %d with %s. Don't panic.",
441 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
442 client_version_string);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800443 cleanup_exit(255);
444 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700445 if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
Adam Langleyd0592972015-03-30 14:49:51 -0700446 logit("Client version \"%.100s\" uses unsafe RSA signature "
447 "scheme; disabling use of RSA keys", remote_version);
448 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700449 if ((ssh->compat & SSH_BUG_DERIVEKEY) != 0) {
Adam Langleyd0592972015-03-30 14:49:51 -0700450 fatal("Client version \"%.100s\" uses unsafe key agreement; "
451 "refusing connection", remote_version);
452 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800453
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800454 chop(server_version_string);
455 debug("Local version string %.200s", server_version_string);
456
Greg Hartman9768ca42017-06-22 20:49:52 -0700457 if (remote_major == 2 ||
458 (remote_major == 1 && remote_minor == 99)) {
459 enable_compat20();
460 } else {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800461 s = "Protocol major versions differ.\n";
462 (void) atomicio(vwrite, sock_out, s, strlen(s));
463 close(sock_in);
464 close(sock_out);
Greg Hartman9768ca42017-06-22 20:49:52 -0700465 logit("Protocol major versions differ for %s port %d: "
466 "%.200s vs. %.200s",
467 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800468 server_version_string, client_version_string);
469 cleanup_exit(255);
470 }
471}
472
473/* Destroy the host and server keys. They will no longer be needed. */
474void
475destroy_sensitive_data(void)
476{
477 int i;
478
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800479 for (i = 0; i < options.num_host_key_files; i++) {
480 if (sensitive_data.host_keys[i]) {
481 key_free(sensitive_data.host_keys[i]);
482 sensitive_data.host_keys[i] = NULL;
483 }
484 if (sensitive_data.host_certificates[i]) {
485 key_free(sensitive_data.host_certificates[i]);
486 sensitive_data.host_certificates[i] = NULL;
487 }
488 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800489}
490
491/* Demote private to public keys for network child */
492void
493demote_sensitive_data(void)
494{
495 Key *tmp;
496 int i;
497
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800498 for (i = 0; i < options.num_host_key_files; i++) {
499 if (sensitive_data.host_keys[i]) {
500 tmp = key_demote(sensitive_data.host_keys[i]);
501 key_free(sensitive_data.host_keys[i]);
502 sensitive_data.host_keys[i] = tmp;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800503 }
504 /* Certs do not need demotion */
505 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700506}
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800507
Greg Hartman9768ca42017-06-22 20:49:52 -0700508static void
509reseed_prngs(void)
510{
511 u_int32_t rnd[256];
512
513#ifdef WITH_OPENSSL
514 RAND_poll();
515#endif
516 arc4random_stir(); /* noop on recent arc4random() implementations */
517 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
518
519#ifdef WITH_OPENSSL
520 RAND_seed(rnd, sizeof(rnd));
521 /* give libcrypto a chance to notice the PID change */
522 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
523 fatal("%s: RAND_bytes failed", __func__);
524#endif
525
526 explicit_bzero(rnd, sizeof(rnd));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800527}
528
529static void
530privsep_preauth_child(void)
531{
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800532 gid_t gidset[1];
533
534 /* Enable challenge-response authentication for privilege separation */
535 privsep_challenge_enable();
536
Adam Langleyd0592972015-03-30 14:49:51 -0700537#ifdef GSSAPI
538 /* Cache supported mechanism OIDs for later use */
539 if (options.gss_authentication)
540 ssh_gssapi_prepare_supported_oids();
541#endif
542
Greg Hartman9768ca42017-06-22 20:49:52 -0700543 reseed_prngs();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800544
545 /* Demote the private keys to public keys. */
546 demote_sensitive_data();
547
Greg Hartman9768ca42017-06-22 20:49:52 -0700548 /* Demote the child */
549 if (getuid() == 0 || geteuid() == 0) {
550 /* Change our root directory */
551 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
552 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
553 strerror(errno));
554 if (chdir("/") == -1)
555 fatal("chdir(\"/\"): %s", strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800556
Greg Hartman9768ca42017-06-22 20:49:52 -0700557 /* Drop our privileges */
558 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
559 (u_int)privsep_pw->pw_gid);
560 gidset[0] = privsep_pw->pw_gid;
561 if (setgroups(1, gidset) < 0)
562 fatal("setgroups: %.100s", strerror(errno));
563 permanently_set_uid(privsep_pw);
564 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800565}
566
567static int
568privsep_preauth(Authctxt *authctxt)
569{
Adam Langleyd0592972015-03-30 14:49:51 -0700570 int status, r;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800571 pid_t pid;
572 struct ssh_sandbox *box = NULL;
573
574 /* Set up unprivileged child process to deal with network data */
575 pmonitor = monitor_init();
576 /* Store a pointer to the kex for later rekeying */
Adam Langleyd0592972015-03-30 14:49:51 -0700577 pmonitor->m_pkex = &active_state->kex;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800578
Adam Langleyd0592972015-03-30 14:49:51 -0700579 if (use_privsep == PRIVSEP_ON)
580 box = ssh_sandbox_init(pmonitor);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800581 pid = fork();
582 if (pid == -1) {
583 fatal("fork of unprivileged child failed");
584 } else if (pid != 0) {
585 debug2("Network child is on pid %ld", (long)pid);
586
Adam Langleyd0592972015-03-30 14:49:51 -0700587 pmonitor->m_pid = pid;
588 if (have_agent) {
589 r = ssh_get_authentication_socket(&auth_sock);
590 if (r != 0) {
591 error("Could not get agent socket: %s",
592 ssh_err(r));
593 have_agent = 0;
594 }
595 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800596 if (box != NULL)
597 ssh_sandbox_parent_preauth(box, pid);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800598 monitor_child_preauth(authctxt, pmonitor);
599
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800600 /* Wait for the child's exit status */
601 while (waitpid(pid, &status, 0) < 0) {
Adam Langleyd0592972015-03-30 14:49:51 -0700602 if (errno == EINTR)
603 continue;
604 pmonitor->m_pid = -1;
605 fatal("%s: waitpid: %s", __func__, strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800606 }
Adam Langleyd0592972015-03-30 14:49:51 -0700607 privsep_is_preauth = 0;
608 pmonitor->m_pid = -1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800609 if (WIFEXITED(status)) {
610 if (WEXITSTATUS(status) != 0)
611 fatal("%s: preauth child exited with status %d",
612 __func__, WEXITSTATUS(status));
613 } else if (WIFSIGNALED(status))
614 fatal("%s: preauth child terminated by signal %d",
615 __func__, WTERMSIG(status));
616 if (box != NULL)
617 ssh_sandbox_parent_finish(box);
618 return 1;
619 } else {
620 /* child */
621 close(pmonitor->m_sendfd);
622 close(pmonitor->m_log_recvfd);
623
624 /* Arrange for logging to be sent to the monitor */
625 set_log_handler(mm_log_handler, pmonitor);
626
Greg Hartman9768ca42017-06-22 20:49:52 -0700627 privsep_preauth_child();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800628 setproctitle("%s", "[net]");
629 if (box != NULL)
630 ssh_sandbox_child(box);
631
632 return 0;
633 }
634}
635
636static void
637privsep_postauth(Authctxt *authctxt)
638{
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800639#ifdef DISABLE_FD_PASSING
640 if (1) {
641#else
Greg Hartman9768ca42017-06-22 20:49:52 -0700642 if (authctxt->pw->pw_uid == 0) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800643#endif
644 /* File descriptor passing is broken or root login */
645 use_privsep = 0;
646 goto skip;
647 }
648
649 /* New socket pair */
650 monitor_reinit(pmonitor);
651
652 pmonitor->m_pid = fork();
653 if (pmonitor->m_pid == -1)
654 fatal("fork of unprivileged child failed");
655 else if (pmonitor->m_pid != 0) {
656 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
657 buffer_clear(&loginmsg);
658 monitor_child_postauth(pmonitor);
659
660 /* NEVERREACHED */
661 exit(0);
662 }
663
664 /* child */
665
666 close(pmonitor->m_sendfd);
667 pmonitor->m_sendfd = -1;
668
669 /* Demote the private keys to public keys. */
670 demote_sensitive_data();
671
Greg Hartman9768ca42017-06-22 20:49:52 -0700672 reseed_prngs();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800673
674 /* Drop privileges */
675 do_setusercontext(authctxt->pw);
676
677 skip:
678 /* It is safe now to apply the key state */
679 monitor_apply_keystate(pmonitor);
680
681 /*
682 * Tell the packet layer that authentication was successful, since
683 * this information is not part of the key state.
684 */
685 packet_set_authenticated();
686}
687
688static char *
689list_hostkey_types(void)
690{
691 Buffer b;
692 const char *p;
693 char *ret;
694 int i;
695 Key *key;
696
697 buffer_init(&b);
698 for (i = 0; i < options.num_host_key_files; i++) {
699 key = sensitive_data.host_keys[i];
700 if (key == NULL)
Adam Langleyd0592972015-03-30 14:49:51 -0700701 key = sensitive_data.host_pubkeys[i];
Greg Hartman9768ca42017-06-22 20:49:52 -0700702 if (key == NULL)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800703 continue;
Greg Hartmanccacbc92016-02-03 09:59:44 -0800704 /* Check that the key is accepted in HostkeyAlgorithms */
705 if (match_pattern_list(sshkey_ssh_name(key),
706 options.hostkeyalgorithms, 0) != 1) {
707 debug3("%s: %s key not permitted by HostkeyAlgorithms",
708 __func__, sshkey_ssh_name(key));
709 continue;
710 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800711 switch (key->type) {
712 case KEY_RSA:
713 case KEY_DSA:
714 case KEY_ECDSA:
Adam Langleyd0592972015-03-30 14:49:51 -0700715 case KEY_ED25519:
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800716 if (buffer_len(&b) > 0)
717 buffer_append(&b, ",", 1);
718 p = key_ssh_name(key);
719 buffer_append(&b, p, strlen(p));
Greg Hartman9768ca42017-06-22 20:49:52 -0700720
721 /* for RSA we also support SHA2 signatures */
722 if (key->type == KEY_RSA) {
723 p = ",rsa-sha2-512,rsa-sha2-256";
724 buffer_append(&b, p, strlen(p));
725 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800726 break;
727 }
728 /* If the private key has a cert peer, then list that too */
729 key = sensitive_data.host_certificates[i];
730 if (key == NULL)
731 continue;
732 switch (key->type) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800733 case KEY_RSA_CERT:
734 case KEY_DSA_CERT:
735 case KEY_ECDSA_CERT:
Adam Langleyd0592972015-03-30 14:49:51 -0700736 case KEY_ED25519_CERT:
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800737 if (buffer_len(&b) > 0)
738 buffer_append(&b, ",", 1);
739 p = key_ssh_name(key);
740 buffer_append(&b, p, strlen(p));
741 break;
742 }
743 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700744 if ((ret = sshbuf_dup_string(&b)) == NULL)
745 fatal("%s: sshbuf_dup_string failed", __func__);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800746 buffer_free(&b);
747 debug("list_hostkey_types: %s", ret);
748 return ret;
749}
750
751static Key *
Adam Langleyd0592972015-03-30 14:49:51 -0700752get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800753{
754 int i;
755 Key *key;
756
757 for (i = 0; i < options.num_host_key_files; i++) {
758 switch (type) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800759 case KEY_RSA_CERT:
760 case KEY_DSA_CERT:
761 case KEY_ECDSA_CERT:
Adam Langleyd0592972015-03-30 14:49:51 -0700762 case KEY_ED25519_CERT:
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800763 key = sensitive_data.host_certificates[i];
764 break;
765 default:
766 key = sensitive_data.host_keys[i];
Adam Langleyd0592972015-03-30 14:49:51 -0700767 if (key == NULL && !need_private)
768 key = sensitive_data.host_pubkeys[i];
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800769 break;
770 }
Adam Langleyd0592972015-03-30 14:49:51 -0700771 if (key != NULL && key->type == type &&
772 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800773 return need_private ?
774 sensitive_data.host_keys[i] : key;
775 }
776 return NULL;
777}
778
779Key *
Adam Langleyd0592972015-03-30 14:49:51 -0700780get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800781{
Adam Langleyd0592972015-03-30 14:49:51 -0700782 return get_hostkey_by_type(type, nid, 0, ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800783}
784
785Key *
Adam Langleyd0592972015-03-30 14:49:51 -0700786get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800787{
Adam Langleyd0592972015-03-30 14:49:51 -0700788 return get_hostkey_by_type(type, nid, 1, ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800789}
790
791Key *
792get_hostkey_by_index(int ind)
793{
794 if (ind < 0 || ind >= options.num_host_key_files)
795 return (NULL);
796 return (sensitive_data.host_keys[ind]);
797}
798
Adam Langleyd0592972015-03-30 14:49:51 -0700799Key *
800get_hostkey_public_by_index(int ind, struct ssh *ssh)
801{
802 if (ind < 0 || ind >= options.num_host_key_files)
803 return (NULL);
804 return (sensitive_data.host_pubkeys[ind]);
805}
806
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800807int
Adam Langleyd0592972015-03-30 14:49:51 -0700808get_hostkey_index(Key *key, int compare, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800809{
810 int i;
811
812 for (i = 0; i < options.num_host_key_files; i++) {
813 if (key_is_cert(key)) {
Adam Langleyd0592972015-03-30 14:49:51 -0700814 if (key == sensitive_data.host_certificates[i] ||
815 (compare && sensitive_data.host_certificates[i] &&
816 sshkey_equal(key,
817 sensitive_data.host_certificates[i])))
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800818 return (i);
819 } else {
Adam Langleyd0592972015-03-30 14:49:51 -0700820 if (key == sensitive_data.host_keys[i] ||
821 (compare && sensitive_data.host_keys[i] &&
822 sshkey_equal(key, sensitive_data.host_keys[i])))
823 return (i);
824 if (key == sensitive_data.host_pubkeys[i] ||
825 (compare && sensitive_data.host_pubkeys[i] &&
826 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800827 return (i);
828 }
829 }
830 return (-1);
831}
832
Adam Langleyd0592972015-03-30 14:49:51 -0700833/* Inform the client of all hostkeys */
834static void
835notify_hostkeys(struct ssh *ssh)
836{
837 struct sshbuf *buf;
838 struct sshkey *key;
839 int i, nkeys, r;
840 char *fp;
841
Greg Hartmanccacbc92016-02-03 09:59:44 -0800842 /* Some clients cannot cope with the hostkeys message, skip those. */
843 if (datafellows & SSH_BUG_HOSTKEYS)
844 return;
845
Adam Langleyd0592972015-03-30 14:49:51 -0700846 if ((buf = sshbuf_new()) == NULL)
847 fatal("%s: sshbuf_new", __func__);
848 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
849 key = get_hostkey_public_by_index(i, ssh);
850 if (key == NULL || key->type == KEY_UNSPEC ||
Greg Hartman9768ca42017-06-22 20:49:52 -0700851 sshkey_is_cert(key))
Adam Langleyd0592972015-03-30 14:49:51 -0700852 continue;
853 fp = sshkey_fingerprint(key, options.fingerprint_hash,
854 SSH_FP_DEFAULT);
855 debug3("%s: key %d: %s %s", __func__, i,
856 sshkey_ssh_name(key), fp);
857 free(fp);
858 if (nkeys == 0) {
859 packet_start(SSH2_MSG_GLOBAL_REQUEST);
860 packet_put_cstring("hostkeys-00@openssh.com");
861 packet_put_char(0); /* want-reply */
862 }
863 sshbuf_reset(buf);
864 if ((r = sshkey_putb(key, buf)) != 0)
865 fatal("%s: couldn't put hostkey %d: %s",
866 __func__, i, ssh_err(r));
867 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
868 nkeys++;
869 }
870 debug3("%s: sent %d hostkeys", __func__, nkeys);
871 if (nkeys == 0)
872 fatal("%s: no hostkeys", __func__);
873 packet_send();
874 sshbuf_free(buf);
875}
876
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800877/*
878 * returns 1 if connection should be dropped, 0 otherwise.
879 * dropping starts at connection #max_startups_begin with a probability
880 * of (max_startups_rate/100). the probability increases linearly until
881 * all connections are dropped for startups > max_startups
882 */
883static int
884drop_connection(int startups)
885{
886 int p, r;
887
888 if (startups < options.max_startups_begin)
889 return 0;
890 if (startups >= options.max_startups)
891 return 1;
892 if (options.max_startups_rate == 100)
893 return 1;
894
895 p = 100 - options.max_startups_rate;
896 p *= startups - options.max_startups_begin;
897 p /= options.max_startups - options.max_startups_begin;
898 p += options.max_startups_rate;
899 r = arc4random_uniform(100);
900
901 debug("drop_connection: p %d, r %d", p, r);
902 return (r < p) ? 1 : 0;
903}
904
905static void
906usage(void)
907{
908 fprintf(stderr, "%s, %s\n",
Adam Langleyd0592972015-03-30 14:49:51 -0700909 SSH_RELEASE,
910#ifdef WITH_OPENSSL
911 SSLeay_version(SSLEAY_VERSION)
912#else
913 "without OpenSSL"
914#endif
915 );
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800916 fprintf(stderr,
Greg Hartman9768ca42017-06-22 20:49:52 -0700917"usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
Adam Langleyd0592972015-03-30 14:49:51 -0700918" [-E log_file] [-f config_file] [-g login_grace_time]\n"
Greg Hartman9768ca42017-06-22 20:49:52 -0700919" [-h host_key_file] [-o option] [-p port] [-u len]\n"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800920 );
921 exit(1);
922}
923
924static void
Greg Hartman9768ca42017-06-22 20:49:52 -0700925send_rexec_state(int fd, struct sshbuf *conf)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800926{
Greg Hartman9768ca42017-06-22 20:49:52 -0700927 struct sshbuf *m;
928 int r;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800929
Greg Hartman9768ca42017-06-22 20:49:52 -0700930 debug3("%s: entering fd = %d config len %zu", __func__, fd,
931 sshbuf_len(conf));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800932
933 /*
934 * Protocol from reexec master to child:
935 * string configuration
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800936 * string rngseed (only if OpenSSL is not self-seeded)
937 */
Greg Hartman9768ca42017-06-22 20:49:52 -0700938 if ((m = sshbuf_new()) == NULL)
939 fatal("%s: sshbuf_new failed", __func__);
940 if ((r = sshbuf_put_stringb(m, conf)) != 0)
941 fatal("%s: buffer error: %s", __func__, ssh_err(r));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800942
Adam Langleyd0592972015-03-30 14:49:51 -0700943#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
Greg Hartman9768ca42017-06-22 20:49:52 -0700944 rexec_send_rng_seed(m);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800945#endif
946
Greg Hartman9768ca42017-06-22 20:49:52 -0700947 if (ssh_msg_send(fd, 0, m) == -1)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800948 fatal("%s: ssh_msg_send failed", __func__);
949
Greg Hartman9768ca42017-06-22 20:49:52 -0700950 sshbuf_free(m);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800951
952 debug3("%s: done", __func__);
953}
954
955static void
956recv_rexec_state(int fd, Buffer *conf)
957{
958 Buffer m;
959 char *cp;
960 u_int len;
961
962 debug3("%s: entering fd = %d", __func__, fd);
963
964 buffer_init(&m);
965
966 if (ssh_msg_recv(fd, &m) == -1)
967 fatal("%s: ssh_msg_recv failed", __func__);
968 if (buffer_get_char(&m) != 0)
969 fatal("%s: rexec version mismatch", __func__);
970
971 cp = buffer_get_string(&m, &len);
972 if (conf != NULL)
Greg Hartman9768ca42017-06-22 20:49:52 -0700973 buffer_append(conf, cp, len);
Adam Langleyd0592972015-03-30 14:49:51 -0700974 free(cp);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800975
Adam Langleyd0592972015-03-30 14:49:51 -0700976#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800977 rexec_recv_rng_seed(&m);
978#endif
979
980 buffer_free(&m);
981
982 debug3("%s: done", __func__);
983}
984
985/* Accept a connection from inetd */
986static void
987server_accept_inetd(int *sock_in, int *sock_out)
988{
989 int fd;
990
991 startup_pipe = -1;
992 if (rexeced_flag) {
993 close(REEXEC_CONFIG_PASS_FD);
994 *sock_in = *sock_out = dup(STDIN_FILENO);
995 if (!debug_flag) {
996 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
997 close(REEXEC_STARTUP_PIPE_FD);
998 }
999 } else {
1000 *sock_in = dup(STDIN_FILENO);
1001 *sock_out = dup(STDOUT_FILENO);
1002 }
1003 /*
1004 * We intentionally do not close the descriptors 0, 1, and 2
1005 * as our code for setting the descriptors won't work if
1006 * ttyfd happens to be one of those.
1007 */
1008 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1009 dup2(fd, STDIN_FILENO);
1010 dup2(fd, STDOUT_FILENO);
Adam Langleyd0592972015-03-30 14:49:51 -07001011 if (!log_stderr)
1012 dup2(fd, STDERR_FILENO);
1013 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001014 close(fd);
1015 }
1016 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1017}
1018
1019/*
1020 * Listen for TCP connections
1021 */
1022static void
1023server_listen(void)
1024{
1025 int ret, listen_sock, on = 1;
1026 struct addrinfo *ai;
1027 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1028
1029 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1030 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1031 continue;
1032 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1033 fatal("Too many listen sockets. "
1034 "Enlarge MAX_LISTEN_SOCKS");
1035 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1036 ntop, sizeof(ntop), strport, sizeof(strport),
1037 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1038 error("getnameinfo failed: %.100s",
1039 ssh_gai_strerror(ret));
1040 continue;
1041 }
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001042
1043#if defined(ANDROID_GCE) && defined(GCE_PLATFORM_SDK_VERSION) && GCE_PLATFORM_SDK_VERSION >= 28
1044 /*
1045 * Android GCE specific, bug 67899876
1046 * Open socket in external namespace, making it possible to serve SSH
1047 * connections regardless of internal interface states.
1048 */
1049 int outerfd = open("/var/run/netns/outer.net", O_RDONLY);
1050 int androidfd = open("/var/run/netns/android.net", O_RDONLY);
1051 if (outerfd > 0 && androidfd > 0) {
1052 if (setns(outerfd, 0) != 0) {
1053 fprintf(stderr, "Could not set netns: %s\n",
1054 strerror(errno));
1055 exit(1);
1056 }
1057 }
1058#endif
1059
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001060 /* Create socket for listening. */
1061 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1062 ai->ai_protocol);
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001063
1064#if defined(ANDROID_GCE) && defined(GCE_PLATFORM_SDK_VERSION) && GCE_PLATFORM_SDK_VERSION >= 28
1065 if (androidfd > 0) {
1066 if (setns(androidfd, 0) != 0) {
1067 fprintf(stderr, "Could not set netns: %s\n",
1068 strerror(errno));
1069 exit(1);
1070 }
1071 }
1072 if (outerfd > 0) {
1073 close(outerfd);
1074 }
1075 if (androidfd > 0) {
1076 close(androidfd);
1077 }
1078#endif
1079
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001080 if (listen_sock < 0) {
1081 /* kernel may not support ipv6 */
1082 verbose("socket: %.100s", strerror(errno));
1083 continue;
1084 }
1085 if (set_nonblock(listen_sock) == -1) {
1086 close(listen_sock);
1087 continue;
1088 }
Greg Hartman9768ca42017-06-22 20:49:52 -07001089 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1090 verbose("socket: CLOEXEC: %s", strerror(errno));
1091 close(listen_sock);
1092 continue;
1093 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001094 /*
1095 * Set socket options.
1096 * Allow local port reuse in TIME_WAIT.
1097 */
1098 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1099 &on, sizeof(on)) == -1)
1100 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1101
1102 /* Only communicate in IPv6 over AF_INET6 sockets. */
1103 if (ai->ai_family == AF_INET6)
1104 sock_set_v6only(listen_sock);
1105
1106 debug("Bind to port %s on %s.", strport, ntop);
1107
1108 /* Bind the socket to the desired port. */
1109 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1110 error("Bind to port %s on %s failed: %.200s.",
1111 strport, ntop, strerror(errno));
1112 close(listen_sock);
1113 continue;
1114 }
1115 listen_socks[num_listen_socks] = listen_sock;
1116 num_listen_socks++;
1117
1118 /* Start listening on the port. */
1119 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1120 fatal("listen on [%s]:%s: %.100s",
1121 ntop, strport, strerror(errno));
1122 logit("Server listening on %s port %s.", ntop, strport);
1123 }
1124 freeaddrinfo(options.listen_addrs);
1125
1126 if (!num_listen_socks)
1127 fatal("Cannot bind any address.");
1128}
1129
1130/*
1131 * The main TCP accept loop. Note that, for the non-debug case, returns
1132 * from this function are in a forked subprocess.
1133 */
1134static void
1135server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1136{
1137 fd_set *fdset;
1138 int i, j, ret, maxfd;
Greg Hartman9768ca42017-06-22 20:49:52 -07001139 int startups = 0;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001140 int startup_p[2] = { -1 , -1 };
1141 struct sockaddr_storage from;
1142 socklen_t fromlen;
1143 pid_t pid;
Adam Langleyd0592972015-03-30 14:49:51 -07001144 u_char rnd[256];
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001145
1146 /* setup fd set for accept */
1147 fdset = NULL;
1148 maxfd = 0;
1149 for (i = 0; i < num_listen_socks; i++)
1150 if (listen_socks[i] > maxfd)
1151 maxfd = listen_socks[i];
1152 /* pipes connected to unauthenticated childs */
1153 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1154 for (i = 0; i < options.max_startups; i++)
1155 startup_pipes[i] = -1;
1156
1157 /*
1158 * Stay listening for connections until the system crashes or
1159 * the daemon is killed with a signal.
1160 */
1161 for (;;) {
1162 if (received_sighup)
1163 sighup_restart();
Greg Hartman9768ca42017-06-22 20:49:52 -07001164 free(fdset);
Greg Hartmanccacbc92016-02-03 09:59:44 -08001165 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001166 sizeof(fd_mask));
1167
1168 for (i = 0; i < num_listen_socks; i++)
1169 FD_SET(listen_socks[i], fdset);
1170 for (i = 0; i < options.max_startups; i++)
1171 if (startup_pipes[i] != -1)
1172 FD_SET(startup_pipes[i], fdset);
1173
1174 /* Wait in select until there is a connection. */
1175 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1176 if (ret < 0 && errno != EINTR)
1177 error("select: %.100s", strerror(errno));
1178 if (received_sigterm) {
1179 logit("Received signal %d; terminating.",
1180 (int) received_sigterm);
1181 close_listen_socks();
Adam Langleyd0592972015-03-30 14:49:51 -07001182 if (options.pid_file != NULL)
1183 unlink(options.pid_file);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001184 exit(received_sigterm == SIGTERM ? 0 : 255);
1185 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001186 if (ret < 0)
1187 continue;
1188
1189 for (i = 0; i < options.max_startups; i++)
1190 if (startup_pipes[i] != -1 &&
1191 FD_ISSET(startup_pipes[i], fdset)) {
1192 /*
1193 * the read end of the pipe is ready
1194 * if the child has closed the pipe
1195 * after successful authentication
1196 * or if the child has died
1197 */
1198 close(startup_pipes[i]);
1199 startup_pipes[i] = -1;
1200 startups--;
1201 }
1202 for (i = 0; i < num_listen_socks; i++) {
1203 if (!FD_ISSET(listen_socks[i], fdset))
1204 continue;
1205 fromlen = sizeof(from);
1206 *newsock = accept(listen_socks[i],
1207 (struct sockaddr *)&from, &fromlen);
1208 if (*newsock < 0) {
Adam Langleyd0592972015-03-30 14:49:51 -07001209 if (errno != EINTR && errno != EWOULDBLOCK &&
1210 errno != ECONNABORTED && errno != EAGAIN)
1211 error("accept: %.100s",
1212 strerror(errno));
1213 if (errno == EMFILE || errno == ENFILE)
1214 usleep(100 * 1000);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001215 continue;
1216 }
1217 if (unset_nonblock(*newsock) == -1) {
1218 close(*newsock);
1219 continue;
1220 }
1221 if (drop_connection(startups) == 1) {
Greg Hartman9768ca42017-06-22 20:49:52 -07001222 char *laddr = get_local_ipaddr(*newsock);
1223 char *raddr = get_peer_ipaddr(*newsock);
1224
1225 verbose("drop connection #%d from [%s]:%d "
1226 "on [%s]:%d past MaxStartups", startups,
1227 raddr, get_peer_port(*newsock),
1228 laddr, get_local_port(*newsock));
1229 free(laddr);
1230 free(raddr);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001231 close(*newsock);
1232 continue;
1233 }
1234 if (pipe(startup_p) == -1) {
1235 close(*newsock);
1236 continue;
1237 }
1238
1239 if (rexec_flag && socketpair(AF_UNIX,
1240 SOCK_STREAM, 0, config_s) == -1) {
1241 error("reexec socketpair: %s",
1242 strerror(errno));
1243 close(*newsock);
1244 close(startup_p[0]);
1245 close(startup_p[1]);
1246 continue;
1247 }
1248
1249 for (j = 0; j < options.max_startups; j++)
1250 if (startup_pipes[j] == -1) {
1251 startup_pipes[j] = startup_p[0];
1252 if (maxfd < startup_p[0])
1253 maxfd = startup_p[0];
1254 startups++;
1255 break;
1256 }
1257
1258 /*
1259 * Got connection. Fork a child to handle it, unless
1260 * we are in debugging mode.
1261 */
1262 if (debug_flag) {
1263 /*
1264 * In debugging mode. Close the listening
1265 * socket, and start processing the
1266 * connection without forking.
1267 */
1268 debug("Server will not fork when running in debugging mode.");
1269 close_listen_socks();
1270 *sock_in = *newsock;
1271 *sock_out = *newsock;
1272 close(startup_p[0]);
1273 close(startup_p[1]);
1274 startup_pipe = -1;
1275 pid = getpid();
1276 if (rexec_flag) {
1277 send_rexec_state(config_s[0],
1278 &cfg);
1279 close(config_s[0]);
1280 }
1281 break;
1282 }
1283
1284 /*
1285 * Normal production daemon. Fork, and have
1286 * the child process the connection. The
1287 * parent continues listening.
1288 */
1289 platform_pre_fork();
1290 if ((pid = fork()) == 0) {
1291 /*
1292 * Child. Close the listening and
1293 * max_startup sockets. Start using
1294 * the accepted socket. Reinitialize
1295 * logging (since our pid has changed).
1296 * We break out of the loop to handle
1297 * the connection.
1298 */
1299 platform_post_fork_child();
1300 startup_pipe = startup_p[1];
1301 close_startup_pipes();
1302 close_listen_socks();
1303 *sock_in = *newsock;
1304 *sock_out = *newsock;
1305 log_init(__progname,
1306 options.log_level,
1307 options.log_facility,
1308 log_stderr);
1309 if (rexec_flag)
1310 close(config_s[0]);
1311 break;
1312 }
1313
1314 /* Parent. Stay in the loop. */
1315 platform_post_fork_parent(pid);
1316 if (pid < 0)
1317 error("fork: %.100s", strerror(errno));
1318 else
1319 debug("Forked child %ld.", (long)pid);
1320
1321 close(startup_p[1]);
1322
1323 if (rexec_flag) {
1324 send_rexec_state(config_s[0], &cfg);
1325 close(config_s[0]);
1326 close(config_s[1]);
1327 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001328 close(*newsock);
1329
1330 /*
1331 * Ensure that our random state differs
1332 * from that of the child
1333 */
1334 arc4random_stir();
Adam Langleyd0592972015-03-30 14:49:51 -07001335 arc4random_buf(rnd, sizeof(rnd));
1336#ifdef WITH_OPENSSL
1337 RAND_seed(rnd, sizeof(rnd));
Greg Hartman7d4e4742015-11-16 10:13:36 -08001338 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1339 fatal("%s: RAND_bytes failed", __func__);
Adam Langleyd0592972015-03-30 14:49:51 -07001340#endif
1341 explicit_bzero(rnd, sizeof(rnd));
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001342 }
1343
1344 /* child process check (or debug mode) */
1345 if (num_listen_socks < 0)
1346 break;
1347 }
1348}
1349
Greg Hartman9768ca42017-06-22 20:49:52 -07001350/*
1351 * If IP options are supported, make sure there are none (log and
1352 * return an error if any are found). Basically we are worried about
1353 * source routing; it can be used to pretend you are somebody
1354 * (ip-address) you are not. That itself may be "almost acceptable"
1355 * under certain circumstances, but rhosts autentication is useless
1356 * if source routing is accepted. Notice also that if we just dropped
1357 * source routing here, the other side could use IP spoofing to do
1358 * rest of the interaction and could still bypass security. So we
1359 * exit here if we detect any IP options.
1360 */
1361static void
1362check_ip_options(struct ssh *ssh)
1363{
1364#ifdef IP_OPTIONS
1365 int sock_in = ssh_packet_get_connection_in(ssh);
1366 struct sockaddr_storage from;
1367 u_char opts[200];
1368 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1369 char text[sizeof(opts) * 3 + 1];
1370
1371 memset(&from, 0, sizeof(from));
1372 if (getpeername(sock_in, (struct sockaddr *)&from,
1373 &fromlen) < 0)
1374 return;
1375 if (from.ss_family != AF_INET)
1376 return;
1377 /* XXX IPv6 options? */
1378
1379 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1380 &option_size) >= 0 && option_size != 0) {
1381 text[0] = '\0';
1382 for (i = 0; i < option_size; i++)
1383 snprintf(text + i*3, sizeof(text) - i*3,
1384 " %2.2x", opts[i]);
1385 fatal("Connection from %.100s port %d with IP opts: %.800s",
1386 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1387 }
1388 return;
1389#endif /* IP_OPTIONS */
1390}
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001391
1392/*
1393 * Main program for the daemon.
1394 */
1395int
1396main(int ac, char **av)
1397{
Greg Hartman9768ca42017-06-22 20:49:52 -07001398 struct ssh *ssh = NULL;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001399 extern char *optarg;
1400 extern int optind;
Greg Hartman9768ca42017-06-22 20:49:52 -07001401 int r, opt, i, j, on = 1, already_daemon;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001402 int sock_in = -1, sock_out = -1, newsock = -1;
1403 const char *remote_ip;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001404 int remote_port;
Greg Hartmanccacbc92016-02-03 09:59:44 -08001405 char *fp, *line, *laddr, *logfile = NULL;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001406 int config_s[2] = { -1 , -1 };
Adam Langleyd0592972015-03-30 14:49:51 -07001407 u_int n;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001408 u_int64_t ibytes, obytes;
1409 mode_t new_umask;
1410 Key *key;
Adam Langleyd0592972015-03-30 14:49:51 -07001411 Key *pubkey;
1412 int keytype;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001413 Authctxt *authctxt;
Adam Langleyd0592972015-03-30 14:49:51 -07001414 struct connection_info *connection_info = get_connection_info(0, 0);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001415
Greg Hartman9768ca42017-06-22 20:49:52 -07001416 ssh_malloc_init(); /* must be called before any mallocs */
1417
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001418#ifdef HAVE_SECUREWARE
1419 (void)set_auth_parameters(ac, av);
1420#endif
1421 __progname = ssh_get_progname(av[0]);
1422
1423 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1424 saved_argc = ac;
1425 rexec_argc = ac;
1426 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1427 for (i = 0; i < ac; i++)
1428 saved_argv[i] = xstrdup(av[i]);
1429 saved_argv[i] = NULL;
1430
1431#ifndef HAVE_SETPROCTITLE
1432 /* Prepare for later setproctitle emulation */
1433 compat_init_setproctitle(ac, av);
1434 av = saved_argv;
1435#endif
1436
1437 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1438 debug("setgroups(): %.200s", strerror(errno));
1439
1440 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1441 sanitise_stdfd();
1442
1443 /* Initialize configuration options to their default values. */
1444 initialize_server_options(&options);
1445
1446 /* Parse command-line arguments. */
Greg Hartmanccacbc92016-02-03 09:59:44 -08001447 while ((opt = getopt(ac, av,
1448 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001449 switch (opt) {
1450 case '4':
1451 options.address_family = AF_INET;
1452 break;
1453 case '6':
1454 options.address_family = AF_INET6;
1455 break;
1456 case 'f':
1457 config_file_name = optarg;
1458 break;
1459 case 'c':
1460 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1461 fprintf(stderr, "too many host certificates.\n");
1462 exit(1);
1463 }
1464 options.host_cert_files[options.num_host_cert_files++] =
1465 derelativise_path(optarg);
1466 break;
1467 case 'd':
1468 if (debug_flag == 0) {
1469 debug_flag = 1;
1470 options.log_level = SYSLOG_LEVEL_DEBUG1;
1471 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1472 options.log_level++;
1473 break;
1474 case 'D':
1475 no_daemon_flag = 1;
1476 break;
Adam Langleyd0592972015-03-30 14:49:51 -07001477 case 'E':
Greg Hartman9768ca42017-06-22 20:49:52 -07001478 logfile = optarg;
Adam Langleyd0592972015-03-30 14:49:51 -07001479 /* FALLTHROUGH */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001480 case 'e':
1481 log_stderr = 1;
1482 break;
1483 case 'i':
1484 inetd_flag = 1;
1485 break;
1486 case 'r':
1487 rexec_flag = 0;
1488 break;
1489 case 'R':
1490 rexeced_flag = 1;
1491 inetd_flag = 1;
1492 break;
1493 case 'Q':
1494 /* ignored */
1495 break;
1496 case 'q':
1497 options.log_level = SYSLOG_LEVEL_QUIET;
1498 break;
1499 case 'b':
Greg Hartman9768ca42017-06-22 20:49:52 -07001500 /* protocol 1, ignored */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001501 break;
1502 case 'p':
1503 options.ports_from_cmdline = 1;
1504 if (options.num_ports >= MAX_PORTS) {
1505 fprintf(stderr, "too many ports.\n");
1506 exit(1);
1507 }
1508 options.ports[options.num_ports++] = a2port(optarg);
1509 if (options.ports[options.num_ports-1] <= 0) {
1510 fprintf(stderr, "Bad port number.\n");
1511 exit(1);
1512 }
1513 break;
1514 case 'g':
1515 if ((options.login_grace_time = convtime(optarg)) == -1) {
1516 fprintf(stderr, "Invalid login grace time.\n");
1517 exit(1);
1518 }
1519 break;
1520 case 'k':
Greg Hartman9768ca42017-06-22 20:49:52 -07001521 /* protocol 1, ignored */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001522 break;
1523 case 'h':
1524 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1525 fprintf(stderr, "too many host keys.\n");
1526 exit(1);
1527 }
1528 options.host_key_files[options.num_host_key_files++] =
1529 derelativise_path(optarg);
1530 break;
1531 case 't':
1532 test_flag = 1;
1533 break;
1534 case 'T':
1535 test_flag = 2;
1536 break;
1537 case 'C':
Adam Langleyd0592972015-03-30 14:49:51 -07001538 if (parse_server_match_testspec(connection_info,
1539 optarg) == -1)
1540 exit(1);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001541 break;
1542 case 'u':
Adam Langleyd0592972015-03-30 14:49:51 -07001543 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1544 if (utmp_len > HOST_NAME_MAX+1) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001545 fprintf(stderr, "Invalid utmp length.\n");
1546 exit(1);
1547 }
1548 break;
1549 case 'o':
1550 line = xstrdup(optarg);
1551 if (process_server_config_line(&options, line,
Adam Langleyd0592972015-03-30 14:49:51 -07001552 "command-line", 0, NULL, NULL) != 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001553 exit(1);
Adam Langleyd0592972015-03-30 14:49:51 -07001554 free(line);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001555 break;
1556 case '?':
1557 default:
1558 usage();
1559 break;
1560 }
1561 }
1562 if (rexeced_flag || inetd_flag)
1563 rexec_flag = 0;
1564 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1565 fatal("sshd re-exec requires execution with an absolute path");
1566 if (rexeced_flag)
1567 closefrom(REEXEC_MIN_FREE_FD);
1568 else
1569 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1570
Adam Langleyd0592972015-03-30 14:49:51 -07001571#ifdef WITH_OPENSSL
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001572 OpenSSL_add_all_algorithms();
Adam Langleyd0592972015-03-30 14:49:51 -07001573#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001574
Adam Langleyd0592972015-03-30 14:49:51 -07001575 /* If requested, redirect the logs to the specified logfile. */
Greg Hartman9768ca42017-06-22 20:49:52 -07001576 if (logfile != NULL)
Adam Langleyd0592972015-03-30 14:49:51 -07001577 log_redirect_stderr_to(logfile);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001578 /*
1579 * Force logging to stderr until we have loaded the private host
1580 * key (unless started from inetd)
1581 */
1582 log_init(__progname,
1583 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1584 SYSLOG_LEVEL_INFO : options.log_level,
1585 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1586 SYSLOG_FACILITY_AUTH : options.log_facility,
1587 log_stderr || !inetd_flag);
1588
1589 /*
1590 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1591 * root's environment
1592 */
1593 if (getenv("KRB5CCNAME") != NULL)
Adam Langleyd0592972015-03-30 14:49:51 -07001594 (void) unsetenv("KRB5CCNAME");
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001595
1596#ifdef _UNICOS
1597 /* Cray can define user privs drop all privs now!
1598 * Not needed on PRIV_SU systems!
1599 */
1600 drop_cray_privs();
1601#endif
1602
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001603 sensitive_data.have_ssh2_key = 0;
1604
1605 /*
1606 * If we're doing an extended config test, make sure we have all of
1607 * the parameters we need. If we're not doing an extended test,
1608 * do not silently ignore connection test params.
1609 */
Adam Langleyd0592972015-03-30 14:49:51 -07001610 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001611 fatal("user, host and addr are all required when testing "
1612 "Match configs");
Adam Langleyd0592972015-03-30 14:49:51 -07001613 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001614 fatal("Config test connection parameter (-C) provided without "
1615 "test mode (-T)");
1616
1617 /* Fetch our configuration */
1618 buffer_init(&cfg);
1619 if (rexeced_flag)
1620 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
Greg Hartmanccacbc92016-02-03 09:59:44 -08001621 else if (strcasecmp(config_file_name, "none") != 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001622 load_server_config(config_file_name, &cfg);
1623
1624 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
Adam Langleyd0592972015-03-30 14:49:51 -07001625 &cfg, NULL);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001626
1627 seed_rng();
1628
1629 /* Fill in default values for those options not explicitly set. */
1630 fill_default_server_options(&options);
1631
1632 /* challenge-response is implemented via keyboard interactive */
1633 if (options.challenge_response_authentication)
1634 options.kbd_interactive_authentication = 1;
1635
Adam Langleyd0592972015-03-30 14:49:51 -07001636 /* Check that options are sensible */
1637 if (options.authorized_keys_command_user == NULL &&
1638 (options.authorized_keys_command != NULL &&
1639 strcasecmp(options.authorized_keys_command, "none") != 0))
1640 fatal("AuthorizedKeysCommand set without "
1641 "AuthorizedKeysCommandUser");
Greg Hartmanccacbc92016-02-03 09:59:44 -08001642 if (options.authorized_principals_command_user == NULL &&
1643 (options.authorized_principals_command != NULL &&
1644 strcasecmp(options.authorized_principals_command, "none") != 0))
1645 fatal("AuthorizedPrincipalsCommand set without "
1646 "AuthorizedPrincipalsCommandUser");
Adam Langleyd0592972015-03-30 14:49:51 -07001647
1648 /*
1649 * Check whether there is any path through configured auth methods.
1650 * Unfortunately it is not possible to verify this generally before
1651 * daemonisation in the presence of Match block, but this catches
1652 * and warns for trivial misconfigurations that could break login.
1653 */
1654 if (options.num_auth_methods != 0) {
Adam Langleyd0592972015-03-30 14:49:51 -07001655 for (n = 0; n < options.num_auth_methods; n++) {
1656 if (auth2_methods_valid(options.auth_methods[n],
1657 1) == 0)
1658 break;
1659 }
1660 if (n >= options.num_auth_methods)
1661 fatal("AuthenticationMethods cannot be satisfied by "
1662 "enabled authentication methods");
1663 }
1664
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001665 /* set default channel AF */
1666 channel_set_af(options.address_family);
1667
1668 /* Check that there are no remaining arguments. */
1669 if (optind < ac) {
1670 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1671 exit(1);
1672 }
1673
Adam Langleyd0592972015-03-30 14:49:51 -07001674 debug("sshd version %s, %s", SSH_VERSION,
1675#ifdef WITH_OPENSSL
1676 SSLeay_version(SSLEAY_VERSION)
1677#else
1678 "without OpenSSL"
1679#endif
1680 );
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001681
1682 /* Store privilege separation user for later use if required. */
1683 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1684 if (use_privsep || options.kerberos_authentication)
1685 fatal("Privilege separation user %s does not exist",
1686 SSH_PRIVSEP_USER);
1687 } else {
Greg Hartman9768ca42017-06-22 20:49:52 -07001688#if defined(ANDROID)
1689/* Android does not do passwords and passes NULL for them. This breaks strlen */
1690 if (privsep_pw->pw_passwd) {
1691#endif
1692 explicit_bzero(privsep_pw->pw_passwd,
1693 strlen(privsep_pw->pw_passwd));
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001694 privsep_pw = pwcopy(privsep_pw);
Greg Hartman9768ca42017-06-22 20:49:52 -07001695 free(privsep_pw->pw_passwd);
1696#if defined(ANDROID)
1697 }
1698#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001699 privsep_pw->pw_passwd = xstrdup("*");
1700 }
Adam Langleyd0592972015-03-30 14:49:51 -07001701#if !defined(ANDROID)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001702 endpwent();
Greg Hartmanf5c67b42015-02-27 07:55:00 -08001703#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001704
Adam Langleyd0592972015-03-30 14:49:51 -07001705 /* load host keys */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001706 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1707 sizeof(Key *));
Adam Langleyd0592972015-03-30 14:49:51 -07001708 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1709 sizeof(Key *));
1710
1711 if (options.host_key_agent) {
1712 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1713 setenv(SSH_AUTHSOCKET_ENV_NAME,
1714 options.host_key_agent, 1);
1715 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1716 have_agent = 1;
1717 else
1718 error("Could not connect to agent \"%s\": %s",
1719 options.host_key_agent, ssh_err(r));
1720 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001721
1722 for (i = 0; i < options.num_host_key_files; i++) {
Adam Langleyd0592972015-03-30 14:49:51 -07001723 if (options.host_key_files[i] == NULL)
1724 continue;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001725 key = key_load_private(options.host_key_files[i], "", NULL);
Adam Langleyd0592972015-03-30 14:49:51 -07001726 pubkey = key_load_public(options.host_key_files[i], NULL);
Greg Hartman9768ca42017-06-22 20:49:52 -07001727
1728 if ((pubkey != NULL && pubkey->type == KEY_RSA1) ||
1729 (key != NULL && key->type == KEY_RSA1)) {
1730 verbose("Ignoring RSA1 key %s",
1731 options.host_key_files[i]);
1732 key_free(key);
1733 key_free(pubkey);
1734 continue;
1735 }
Adam Langleyd0592972015-03-30 14:49:51 -07001736 if (pubkey == NULL && key != NULL)
1737 pubkey = key_demote(key);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001738 sensitive_data.host_keys[i] = key;
Adam Langleyd0592972015-03-30 14:49:51 -07001739 sensitive_data.host_pubkeys[i] = pubkey;
1740
Greg Hartman9768ca42017-06-22 20:49:52 -07001741 if (key == NULL && pubkey != NULL && have_agent) {
Adam Langleyd0592972015-03-30 14:49:51 -07001742 debug("will rely on agent for hostkey %s",
1743 options.host_key_files[i]);
1744 keytype = pubkey->type;
1745 } else if (key != NULL) {
1746 keytype = key->type;
1747 } else {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001748 error("Could not load host key: %s",
1749 options.host_key_files[i]);
1750 sensitive_data.host_keys[i] = NULL;
Adam Langleyd0592972015-03-30 14:49:51 -07001751 sensitive_data.host_pubkeys[i] = NULL;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001752 continue;
1753 }
Adam Langleyd0592972015-03-30 14:49:51 -07001754
1755 switch (keytype) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001756 case KEY_RSA:
1757 case KEY_DSA:
1758 case KEY_ECDSA:
Adam Langleyd0592972015-03-30 14:49:51 -07001759 case KEY_ED25519:
1760 if (have_agent || key != NULL)
1761 sensitive_data.have_ssh2_key = 1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001762 break;
1763 }
Adam Langleyd0592972015-03-30 14:49:51 -07001764 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1765 SSH_FP_DEFAULT)) == NULL)
1766 fatal("sshkey_fingerprint failed");
1767 debug("%s host key #%d: %s %s",
Greg Hartman9768ca42017-06-22 20:49:52 -07001768 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
Adam Langleyd0592972015-03-30 14:49:51 -07001769 free(fp);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001770 }
Greg Hartman9768ca42017-06-22 20:49:52 -07001771 if (!sensitive_data.have_ssh2_key) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001772 logit("sshd: no hostkeys available -- exiting.");
1773 exit(1);
1774 }
1775
1776 /*
1777 * Load certificates. They are stored in an array at identical
1778 * indices to the public keys that they relate to.
1779 */
1780 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1781 sizeof(Key *));
1782 for (i = 0; i < options.num_host_key_files; i++)
1783 sensitive_data.host_certificates[i] = NULL;
1784
1785 for (i = 0; i < options.num_host_cert_files; i++) {
Adam Langleyd0592972015-03-30 14:49:51 -07001786 if (options.host_cert_files[i] == NULL)
1787 continue;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001788 key = key_load_public(options.host_cert_files[i], NULL);
1789 if (key == NULL) {
1790 error("Could not load host certificate: %s",
1791 options.host_cert_files[i]);
1792 continue;
1793 }
1794 if (!key_is_cert(key)) {
1795 error("Certificate file is not a certificate: %s",
1796 options.host_cert_files[i]);
1797 key_free(key);
1798 continue;
1799 }
1800 /* Find matching private key */
1801 for (j = 0; j < options.num_host_key_files; j++) {
1802 if (key_equal_public(key,
1803 sensitive_data.host_keys[j])) {
1804 sensitive_data.host_certificates[j] = key;
1805 break;
1806 }
1807 }
1808 if (j >= options.num_host_key_files) {
1809 error("No matching private key for certificate: %s",
1810 options.host_cert_files[i]);
1811 key_free(key);
1812 continue;
1813 }
1814 sensitive_data.host_certificates[j] = key;
1815 debug("host certificate: #%d type %d %s", j, key->type,
1816 key_type(key));
1817 }
Adam Langleyd0592972015-03-30 14:49:51 -07001818
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001819 if (use_privsep) {
1820 struct stat st;
1821
1822 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1823 (S_ISDIR(st.st_mode) == 0))
1824 fatal("Missing privilege separation directory: %s",
1825 _PATH_PRIVSEP_CHROOT_DIR);
1826
1827#ifdef HAVE_CYGWIN
1828 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1829 (st.st_uid != getuid () ||
1830 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1831#else
1832 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1833#endif
1834 fatal("%s must be owned by root and not group or "
1835 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1836 }
1837
1838 if (test_flag > 1) {
Adam Langleyd0592972015-03-30 14:49:51 -07001839 if (server_match_spec_complete(connection_info) == 1)
1840 parse_server_match_config(&options, connection_info);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001841 dump_config(&options);
1842 }
1843
1844 /* Configuration looks good, so exit if in test mode. */
1845 if (test_flag)
1846 exit(0);
1847
1848 /*
1849 * Clear out any supplemental groups we may have inherited. This
1850 * prevents inadvertent creation of files with bad modes (in the
1851 * portable version at least, it's certainly possible for PAM
1852 * to create a file, and we can't control the code in every
1853 * module which might be used).
1854 */
1855 if (setgroups(0, NULL) < 0)
1856 debug("setgroups() failed: %.200s", strerror(errno));
1857
1858 if (rexec_flag) {
1859 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1860 for (i = 0; i < rexec_argc; i++) {
1861 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1862 rexec_argv[i] = saved_argv[i];
1863 }
1864 rexec_argv[rexec_argc] = "-R";
1865 rexec_argv[rexec_argc + 1] = NULL;
1866 }
1867
1868 /* Ensure that umask disallows at least group and world write */
1869 new_umask = umask(0077) | 0022;
1870 (void) umask(new_umask);
1871
1872 /* Initialize the log (it is reinitialized below in case we forked). */
1873 if (debug_flag && (!inetd_flag || rexeced_flag))
1874 log_stderr = 1;
1875 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1876
1877 /*
Greg Hartman9768ca42017-06-22 20:49:52 -07001878 * If not in debugging mode, not started from inetd and not already
1879 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1880 * terminal, and fork. The original process exits.
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001881 */
Greg Hartman9768ca42017-06-22 20:49:52 -07001882 already_daemon = daemonized();
1883 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1884
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001885 if (daemon(0, 0) < 0)
1886 fatal("daemon() failed: %.200s", strerror(errno));
1887
Greg Hartman9768ca42017-06-22 20:49:52 -07001888 disconnect_controlling_tty();
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001889 }
1890 /* Reinitialize the log (because of the fork above). */
1891 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1892
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001893 /* Chdir to the root directory so that the current disk can be
1894 unmounted if desired. */
Adam Langleyd0592972015-03-30 14:49:51 -07001895 if (chdir("/") == -1)
1896 error("chdir(\"/\"): %s", strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001897
1898 /* ignore SIGPIPE */
1899 signal(SIGPIPE, SIG_IGN);
1900
1901 /* Get a connection, either from inetd or a listening TCP socket */
1902 if (inetd_flag) {
1903 server_accept_inetd(&sock_in, &sock_out);
1904 } else {
1905 platform_pre_listen();
1906 server_listen();
1907
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001908 signal(SIGHUP, sighup_handler);
1909 signal(SIGCHLD, main_sigchld_handler);
1910 signal(SIGTERM, sigterm_handler);
1911 signal(SIGQUIT, sigterm_handler);
1912
1913 /*
1914 * Write out the pid file after the sigterm handler
1915 * is setup and the listen sockets are bound
1916 */
Adam Langleyd0592972015-03-30 14:49:51 -07001917 if (options.pid_file != NULL && !debug_flag) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001918 FILE *f = fopen(options.pid_file, "w");
1919
1920 if (f == NULL) {
1921 error("Couldn't create pid file \"%s\": %s",
1922 options.pid_file, strerror(errno));
1923 } else {
1924 fprintf(f, "%ld\n", (long) getpid());
1925 fclose(f);
1926 }
1927 }
1928
1929 /* Accept a connection and return in a forked child */
1930 server_accept_loop(&sock_in, &sock_out,
1931 &newsock, config_s);
1932 }
1933
1934 /* This is the child processing a new connection. */
1935 setproctitle("%s", "[accepted]");
1936
1937 /*
1938 * Create a new session and process group since the 4.4BSD
1939 * setlogin() affects the entire process group. We don't
1940 * want the child to be able to affect the parent.
1941 */
1942#if !defined(SSHD_ACQUIRES_CTTY)
1943 /*
1944 * If setsid is called, on some platforms sshd will later acquire a
1945 * controlling terminal which will result in "could not set
1946 * controlling tty" errors.
1947 */
1948 if (!debug_flag && !inetd_flag && setsid() < 0)
1949 error("setsid: %.100s", strerror(errno));
1950#endif
1951
1952 if (rexec_flag) {
1953 int fd;
1954
1955 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1956 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1957 dup2(newsock, STDIN_FILENO);
1958 dup2(STDIN_FILENO, STDOUT_FILENO);
1959 if (startup_pipe == -1)
1960 close(REEXEC_STARTUP_PIPE_FD);
Adam Langleyd0592972015-03-30 14:49:51 -07001961 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001962 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
Adam Langleyd0592972015-03-30 14:49:51 -07001963 close(startup_pipe);
1964 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1965 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001966
1967 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1968 close(config_s[1]);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001969
1970 execv(rexec_argv[0], rexec_argv);
1971
1972 /* Reexec has failed, fall back and continue */
1973 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1974 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1975 log_init(__progname, options.log_level,
1976 options.log_facility, log_stderr);
1977
1978 /* Clean up fds */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001979 close(REEXEC_CONFIG_PASS_FD);
1980 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1981 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1982 dup2(fd, STDIN_FILENO);
1983 dup2(fd, STDOUT_FILENO);
1984 if (fd > STDERR_FILENO)
1985 close(fd);
1986 }
1987 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1988 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1989 }
1990
1991 /* Executed child processes don't need these. */
1992 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1993 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1994
1995 /*
1996 * Disable the key regeneration alarm. We will not regenerate the
1997 * key since we are no longer in a position to give it to anyone. We
1998 * will not restart on SIGHUP since it no longer makes sense.
1999 */
2000 alarm(0);
2001 signal(SIGALRM, SIG_DFL);
2002 signal(SIGHUP, SIG_DFL);
2003 signal(SIGTERM, SIG_DFL);
2004 signal(SIGQUIT, SIG_DFL);
2005 signal(SIGCHLD, SIG_DFL);
2006 signal(SIGINT, SIG_DFL);
2007
2008 /*
2009 * Register our connection. This turns encryption off because we do
2010 * not have a key.
2011 */
2012 packet_set_connection(sock_in, sock_out);
2013 packet_set_server();
Greg Hartman9768ca42017-06-22 20:49:52 -07002014 ssh = active_state; /* XXX */
2015 check_ip_options(ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002016
2017 /* Set SO_KEEPALIVE if requested. */
2018 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2019 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2020 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2021
Greg Hartman9768ca42017-06-22 20:49:52 -07002022 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2023 debug("ssh_remote_port failed");
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002024 cleanup_exit(255);
2025 }
2026
2027 /*
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002028 * The rest of the code depends on the fact that
Greg Hartman9768ca42017-06-22 20:49:52 -07002029 * ssh_remote_ipaddr() caches the remote ip, even if
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002030 * the socket goes away.
2031 */
Greg Hartman9768ca42017-06-22 20:49:52 -07002032 remote_ip = ssh_remote_ipaddr(ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002033
2034#ifdef SSH_AUDIT_EVENTS
2035 audit_connection_from(remote_ip, remote_port);
2036#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002037
2038 /* Log the connection. */
Greg Hartmanccacbc92016-02-03 09:59:44 -08002039 laddr = get_local_ipaddr(sock_in);
Adam Langleyd0592972015-03-30 14:49:51 -07002040 verbose("Connection from %s port %d on %s port %d",
Greg Hartman9768ca42017-06-22 20:49:52 -07002041 remote_ip, remote_port, laddr, ssh_local_port(ssh));
Greg Hartmanccacbc92016-02-03 09:59:44 -08002042 free(laddr);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002043
2044 /*
2045 * We don't want to listen forever unless the other side
2046 * successfully authenticates itself. So we set up an alarm which is
2047 * cleared after successful authentication. A limit of zero
2048 * indicates no limit. Note that we don't set the alarm in debugging
2049 * mode; it is just annoying to have the server exit just when you
2050 * are about to discover the bug.
2051 */
2052 signal(SIGALRM, grace_alarm_handler);
2053 if (!debug_flag)
2054 alarm(options.login_grace_time);
2055
Greg Hartman9768ca42017-06-22 20:49:52 -07002056 sshd_exchange_identification(ssh, sock_in, sock_out);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002057 packet_set_nonblocking();
2058
2059 /* allocate authentication context */
2060 authctxt = xcalloc(1, sizeof(*authctxt));
2061
2062 authctxt->loginmsg = &loginmsg;
2063
2064 /* XXX global for cleanup, access from other modules */
2065 the_authctxt = authctxt;
2066
2067 /* prepare buffer to collect messages to display to user after login */
2068 buffer_init(&loginmsg);
2069 auth_debug_reset();
2070
Adam Langleyd0592972015-03-30 14:49:51 -07002071 if (use_privsep) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002072 if (privsep_preauth(authctxt) == 1)
2073 goto authenticated;
Greg Hartman9768ca42017-06-22 20:49:52 -07002074 } else if (have_agent) {
Adam Langleyd0592972015-03-30 14:49:51 -07002075 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2076 error("Unable to get agent socket: %s", ssh_err(r));
2077 have_agent = 0;
2078 }
2079 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002080
2081 /* perform the key exchange */
2082 /* authenticate user and start session */
Greg Hartman9768ca42017-06-22 20:49:52 -07002083 do_ssh2_kex();
2084 do_authentication2(authctxt);
2085
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002086 /*
2087 * If we use privilege separation, the unprivileged child transfers
2088 * the current keystate and exits
2089 */
2090 if (use_privsep) {
2091 mm_send_keystate(pmonitor);
2092 exit(0);
2093 }
2094
2095 authenticated:
2096 /*
2097 * Cancel the alarm we set to limit the time taken for
2098 * authentication.
2099 */
2100 alarm(0);
2101 signal(SIGALRM, SIG_DFL);
2102 authctxt->authenticated = 1;
2103 if (startup_pipe != -1) {
2104 close(startup_pipe);
2105 startup_pipe = -1;
2106 }
2107
2108#ifdef SSH_AUDIT_EVENTS
2109 audit_event(SSH_AUTH_SUCCESS);
2110#endif
2111
2112#ifdef GSSAPI
2113 if (options.gss_authentication) {
2114 temporarily_use_uid(authctxt->pw);
2115 ssh_gssapi_storecreds();
2116 restore_uid();
2117 }
2118#endif
2119#ifdef USE_PAM
2120 if (options.use_pam) {
2121 do_pam_setcred(1);
2122 do_pam_session();
2123 }
2124#endif
2125
2126 /*
2127 * In privilege separation, we fork another child and prepare
2128 * file descriptor passing.
2129 */
2130 if (use_privsep) {
2131 privsep_postauth(authctxt);
2132 /* the monitor process [priv] will not return */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002133 }
2134
2135 packet_set_timeout(options.client_alive_interval,
2136 options.client_alive_count_max);
2137
Adam Langleyd0592972015-03-30 14:49:51 -07002138 /* Try to send all our hostkeys to the client */
Greg Hartman9768ca42017-06-22 20:49:52 -07002139 notify_hostkeys(active_state);
Adam Langleyd0592972015-03-30 14:49:51 -07002140
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002141 /* Start session. */
2142 do_authenticated(authctxt);
2143
2144 /* The connection has been terminated. */
Adam Langleyd0592972015-03-30 14:49:51 -07002145 packet_get_bytes(&ibytes, &obytes);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002146 verbose("Transferred: sent %llu, received %llu bytes",
2147 (unsigned long long)obytes, (unsigned long long)ibytes);
2148
2149 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2150
2151#ifdef USE_PAM
2152 if (options.use_pam)
2153 finish_pam();
2154#endif /* USE_PAM */
2155
2156#ifdef SSH_AUDIT_EVENTS
2157 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2158#endif
2159
2160 packet_close();
2161
2162 if (use_privsep)
2163 mm_terminate();
2164
2165 exit(0);
2166}
2167
Adam Langleyd0592972015-03-30 14:49:51 -07002168int
2169sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
Greg Hartman9768ca42017-06-22 20:49:52 -07002170 const u_char *data, size_t dlen, const char *alg, u_int flag)
Adam Langleyd0592972015-03-30 14:49:51 -07002171{
2172 int r;
2173 u_int xxx_slen, xxx_dlen = dlen;
2174
2175 if (privkey) {
Greg Hartman9768ca42017-06-22 20:49:52 -07002176 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
2177 alg) < 0))
Adam Langleyd0592972015-03-30 14:49:51 -07002178 fatal("%s: key_sign failed", __func__);
2179 if (slen)
2180 *slen = xxx_slen;
2181 } else if (use_privsep) {
Greg Hartman9768ca42017-06-22 20:49:52 -07002182 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
2183 alg) < 0)
Adam Langleyd0592972015-03-30 14:49:51 -07002184 fatal("%s: pubkey_sign failed", __func__);
2185 if (slen)
2186 *slen = xxx_slen;
2187 } else {
2188 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
Greg Hartman9768ca42017-06-22 20:49:52 -07002189 data, dlen, alg, datafellows)) != 0)
Adam Langleyd0592972015-03-30 14:49:51 -07002190 fatal("%s: ssh_agent_sign failed: %s",
2191 __func__, ssh_err(r));
2192 }
2193 return 0;
2194}
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002195
Greg Hartmanccacbc92016-02-03 09:59:44 -08002196/* SSH2 key exchange */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002197static void
2198do_ssh2_kex(void)
2199{
Adam Langleyd0592972015-03-30 14:49:51 -07002200 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2201 struct kex *kex;
2202 int r;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002203
Greg Hartmanccacbc92016-02-03 09:59:44 -08002204 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2205 options.kex_algorithms);
2206 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2207 options.ciphers);
2208 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2209 options.ciphers);
2210 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2211 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002212
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002213 if (options.compression == COMP_NONE) {
2214 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
Greg Hartman9768ca42017-06-22 20:49:52 -07002215 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002216 }
Adam Langleyd0592972015-03-30 14:49:51 -07002217
2218 if (options.rekey_limit || options.rekey_interval)
Greg Hartman9768ca42017-06-22 20:49:52 -07002219 packet_set_rekey_limits(options.rekey_limit,
2220 options.rekey_interval);
Adam Langleyd0592972015-03-30 14:49:51 -07002221
2222 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2223 list_hostkey_types());
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002224
2225 /* start key exchange */
Adam Langleyd0592972015-03-30 14:49:51 -07002226 if ((r = kex_setup(active_state, myproposal)) != 0)
2227 fatal("kex_setup: %s", ssh_err(r));
2228 kex = active_state->kex;
2229#ifdef WITH_OPENSSL
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002230 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2231 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
Greg Hartman9768ca42017-06-22 20:49:52 -07002232 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2233 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2234 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002235 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2236 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
Adam Langleyd0592972015-03-30 14:49:51 -07002237# ifdef OPENSSL_HAS_ECC
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002238 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
Adam Langleyd0592972015-03-30 14:49:51 -07002239# endif
2240#endif
2241 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002242 kex->server = 1;
2243 kex->client_version_string=client_version_string;
2244 kex->server_version_string=server_version_string;
2245 kex->load_host_public_key=&get_hostkey_public_by_type;
2246 kex->load_host_private_key=&get_hostkey_private_by_type;
2247 kex->host_key_index=&get_hostkey_index;
Adam Langleyd0592972015-03-30 14:49:51 -07002248 kex->sign = sshd_hostkey_sign;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002249
Adam Langleyd0592972015-03-30 14:49:51 -07002250 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002251
2252 session_id2 = kex->session_id;
2253 session_id2_len = kex->session_id_len;
2254
2255#ifdef DEBUG_KEXDH
2256 /* send 1st encrypted/maced/compressed message */
2257 packet_start(SSH2_MSG_IGNORE);
2258 packet_put_cstring("markus");
2259 packet_send();
2260 packet_write_wait();
2261#endif
2262 debug("KEX done");
2263}
2264
2265/* server specific fatal cleanup */
2266void
2267cleanup_exit(int i)
2268{
Adam Langleyd0592972015-03-30 14:49:51 -07002269 if (the_authctxt) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002270 do_cleanup(the_authctxt);
Adam Langleyd0592972015-03-30 14:49:51 -07002271 if (use_privsep && privsep_is_preauth &&
2272 pmonitor != NULL && pmonitor->m_pid > 1) {
2273 debug("Killing privsep child %d", pmonitor->m_pid);
2274 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2275 errno != ESRCH)
2276 error("%s: kill(%d): %s", __func__,
2277 pmonitor->m_pid, strerror(errno));
2278 }
2279 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002280#ifdef SSH_AUDIT_EVENTS
2281 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2282 if (!use_privsep || mm_is_monitor())
2283 audit_event(SSH_CONNECTION_ABANDON);
2284#endif
2285 _exit(i);
2286}