blob: 20fbb33236506e70f2797d1ba525eb7ae0e4b043 [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 Hartman5bcf61c2017-12-07 16:24:36 -0800126#if defined(ANDROID_GCE)
Greg Hartman786d35e2017-10-25 07:25:43 -0700127#define GNU_SOURCE
128#include <sched.h>
Greg Hartman237e44d2017-12-07 18:17:51 -0800129#include <sys/syscall.h>
130
131int gce_setns(int fd, int clone_flags) {
132#ifdef __i386__
133 return syscall(346, fd, clone_flags);
134#elif __x86_64__
135 return syscall(308, fd, clone_flags);
136#else
137#error "Unsupported Architecture"
138#endif
139}
Greg Hartman786d35e2017-10-25 07:25:43 -0700140#endif
141
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800142/* Re-exec fds */
143#define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
144#define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
145#define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
146#define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
147
148extern char *__progname;
149
150/* Server configuration options. */
151ServerOptions options;
152
153/* Name of the server configuration file. */
154char *config_file_name = _PATH_SERVER_CONFIG_FILE;
155
156/*
157 * Debug mode flag. This can be set on the command line. If debug
158 * mode is enabled, extra debugging output will be sent to the system
159 * log, the daemon will not go to background, and will exit after processing
160 * the first connection.
161 */
162int debug_flag = 0;
163
164/* Flag indicating that the daemon should only test the configuration and keys. */
165int test_flag = 0;
166
167/* Flag indicating that the daemon is being started from inetd. */
168int inetd_flag = 0;
169
170/* Flag indicating that sshd should not detach and become a daemon. */
171int no_daemon_flag = 0;
172
173/* debug goes to stderr unless inetd_flag is set */
174int log_stderr = 0;
175
176/* Saved arguments to main(). */
177char **saved_argv;
178int saved_argc;
179
180/* re-exec */
181int rexeced_flag = 0;
182int rexec_flag = 1;
183int rexec_argc = 0;
184char **rexec_argv;
185
186/*
187 * The sockets that the server is listening; this is used in the SIGHUP
188 * signal handler.
189 */
190#define MAX_LISTEN_SOCKS 16
191int listen_socks[MAX_LISTEN_SOCKS];
192int num_listen_socks = 0;
193
194/*
195 * the client's version string, passed by sshd2 in compat mode. if != NULL,
196 * sshd will skip the version-number exchange
197 */
198char *client_version_string = NULL;
199char *server_version_string = NULL;
200
Adam Langleyd0592972015-03-30 14:49:51 -0700201/* Daemon's agent connection */
202int auth_sock = -1;
203int have_agent = 0;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800204
205/*
206 * Any really sensitive data in the application is contained in this
207 * structure. The idea is that this structure could be locked into memory so
208 * that the pages do not get written into swap. However, there are some
209 * problems. The private key contains BIGNUMs, and we do not (in principle)
210 * have access to the internals of them, and locking just the structure is
211 * not very useful. Currently, memory locking is not implemented.
212 */
213struct {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800214 Key **host_keys; /* all private host keys */
Adam Langleyd0592972015-03-30 14:49:51 -0700215 Key **host_pubkeys; /* all public host keys */
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800216 Key **host_certificates; /* all public host certificates */
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800217 int have_ssh2_key;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800218} sensitive_data;
219
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800220/* This is set to true when a signal is received. */
221static volatile sig_atomic_t received_sighup = 0;
222static volatile sig_atomic_t received_sigterm = 0;
223
224/* session identifier, used by RSA-auth */
225u_char session_id[16];
226
227/* same for ssh2 */
228u_char *session_id2 = NULL;
229u_int session_id2_len = 0;
230
231/* record remote hostname or ip */
Adam Langleyd0592972015-03-30 14:49:51 -0700232u_int utmp_len = HOST_NAME_MAX+1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800233
234/* options.max_startup sized array of fd ints */
235int *startup_pipes = NULL;
236int startup_pipe; /* in child */
237
238/* variables used for privilege separation */
239int use_privsep = -1;
240struct monitor *pmonitor = NULL;
Adam Langleyd0592972015-03-30 14:49:51 -0700241int privsep_is_preauth = 1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800242
243/* global authentication context */
244Authctxt *the_authctxt = NULL;
245
246/* sshd_config buffer */
247Buffer cfg;
248
249/* message to be displayed after login */
250Buffer loginmsg;
251
252/* Unprivileged user */
253struct passwd *privsep_pw = NULL;
254
255/* Prototypes for various functions defined later in this file. */
256void destroy_sensitive_data(void);
257void demote_sensitive_data(void);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800258static void do_ssh2_kex(void);
259
260/*
261 * Close all listening sockets
262 */
263static void
264close_listen_socks(void)
265{
266 int i;
267
268 for (i = 0; i < num_listen_socks; i++)
269 close(listen_socks[i]);
270 num_listen_socks = -1;
271}
272
273static void
274close_startup_pipes(void)
275{
276 int i;
277
278 if (startup_pipes)
279 for (i = 0; i < options.max_startups; i++)
280 if (startup_pipes[i] != -1)
281 close(startup_pipes[i]);
282}
283
284/*
285 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
286 * the effect is to reread the configuration file (and to regenerate
287 * the server key).
288 */
289
290/*ARGSUSED*/
291static void
292sighup_handler(int sig)
293{
294 int save_errno = errno;
295
296 received_sighup = 1;
297 signal(SIGHUP, sighup_handler);
298 errno = save_errno;
299}
300
301/*
302 * Called from the main program after receiving SIGHUP.
303 * Restarts the server.
304 */
305static void
306sighup_restart(void)
307{
308 logit("Received SIGHUP; restarting.");
Greg Hartman9768ca42017-06-22 20:49:52 -0700309 if (options.pid_file != NULL)
310 unlink(options.pid_file);
Adam Langleyd0592972015-03-30 14:49:51 -0700311 platform_pre_restart();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800312 close_listen_socks();
313 close_startup_pipes();
314 alarm(0); /* alarm timer persists across exec */
315 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
316 execv(saved_argv[0], saved_argv);
317 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
318 strerror(errno));
319 exit(1);
320}
321
322/*
323 * Generic signal handler for terminating signals in the master daemon.
324 */
325/*ARGSUSED*/
326static void
327sigterm_handler(int sig)
328{
329 received_sigterm = sig;
330}
331
332/*
333 * SIGCHLD handler. This is called whenever a child dies. This will then
334 * reap any zombies left by exited children.
335 */
336/*ARGSUSED*/
337static void
338main_sigchld_handler(int sig)
339{
340 int save_errno = errno;
341 pid_t pid;
342 int status;
343
344 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
345 (pid < 0 && errno == EINTR))
346 ;
347
348 signal(SIGCHLD, main_sigchld_handler);
349 errno = save_errno;
350}
351
352/*
353 * Signal handler for the alarm after the login grace period has expired.
354 */
355/*ARGSUSED*/
356static void
357grace_alarm_handler(int sig)
358{
359 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
360 kill(pmonitor->m_pid, SIGALRM);
361
Adam Langleyd0592972015-03-30 14:49:51 -0700362 /*
363 * Try to kill any processes that we have spawned, E.g. authorized
364 * keys command helpers.
365 */
366 if (getpgid(0) == getpid()) {
367 signal(SIGTERM, SIG_IGN);
368 kill(0, SIGTERM);
369 }
370
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800371 /* Log error and exit. */
Greg Hartman9768ca42017-06-22 20:49:52 -0700372 sigdie("Timeout before authentication for %s port %d",
373 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800374}
375
376static void
Greg Hartman9768ca42017-06-22 20:49:52 -0700377sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800378{
379 u_int i;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800380 int remote_major, remote_minor;
Greg Hartman9768ca42017-06-22 20:49:52 -0700381 char *s;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800382 char buf[256]; /* Must not be larger than remote_version. */
383 char remote_version[256]; /* Must be at least as big as buf. */
384
Greg Hartman9768ca42017-06-22 20:49:52 -0700385 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
386 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
Adam Langleyd0592972015-03-30 14:49:51 -0700387 *options.version_addendum == '\0' ? "" : " ",
Greg Hartman9768ca42017-06-22 20:49:52 -0700388 options.version_addendum);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800389
390 /* Send our protocol version identification. */
Greg Hartman9768ca42017-06-22 20:49:52 -0700391 if (atomicio(vwrite, sock_out, server_version_string,
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800392 strlen(server_version_string))
393 != strlen(server_version_string)) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700394 logit("Could not write ident string to %s port %d",
395 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800396 cleanup_exit(255);
397 }
398
399 /* Read other sides version identification. */
400 memset(buf, 0, sizeof(buf));
401 for (i = 0; i < sizeof(buf) - 1; i++) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700402 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
403 logit("Did not receive identification string "
404 "from %s port %d",
405 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800406 cleanup_exit(255);
407 }
408 if (buf[i] == '\r') {
409 buf[i] = 0;
410 /* Kludge for F-Secure Macintosh < 1.0.2 */
411 if (i == 12 &&
412 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
413 break;
414 continue;
415 }
416 if (buf[i] == '\n') {
417 buf[i] = 0;
418 break;
419 }
420 }
421 buf[sizeof(buf) - 1] = 0;
422 client_version_string = xstrdup(buf);
423
424 /*
425 * Check that the versions match. In future this might accept
426 * several versions and set appropriate flags to handle them.
427 */
428 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
429 &remote_major, &remote_minor, remote_version) != 3) {
430 s = "Protocol mismatch.\n";
431 (void) atomicio(vwrite, sock_out, s, strlen(s));
Adam Langleyd0592972015-03-30 14:49:51 -0700432 logit("Bad protocol version identification '%.100s' "
433 "from %s port %d", client_version_string,
Greg Hartman9768ca42017-06-22 20:49:52 -0700434 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800435 close(sock_in);
436 close(sock_out);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800437 cleanup_exit(255);
438 }
439 debug("Client protocol version %d.%d; client software version %.100s",
440 remote_major, remote_minor, remote_version);
441
Greg Hartman9768ca42017-06-22 20:49:52 -0700442 ssh->compat = compat_datafellows(remote_version);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800443
Greg Hartman9768ca42017-06-22 20:49:52 -0700444 if ((ssh->compat & SSH_BUG_PROBE) != 0) {
445 logit("probed from %s port %d with %s. Don't panic.",
446 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
447 client_version_string);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800448 cleanup_exit(255);
449 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700450 if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
451 logit("scanned from %s port %d with %s. Don't panic.",
452 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
453 client_version_string);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800454 cleanup_exit(255);
455 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700456 if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
Adam Langleyd0592972015-03-30 14:49:51 -0700457 logit("Client version \"%.100s\" uses unsafe RSA signature "
458 "scheme; disabling use of RSA keys", remote_version);
459 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700460 if ((ssh->compat & SSH_BUG_DERIVEKEY) != 0) {
Adam Langleyd0592972015-03-30 14:49:51 -0700461 fatal("Client version \"%.100s\" uses unsafe key agreement; "
462 "refusing connection", remote_version);
463 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800464
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800465 chop(server_version_string);
466 debug("Local version string %.200s", server_version_string);
467
Greg Hartman9768ca42017-06-22 20:49:52 -0700468 if (remote_major == 2 ||
469 (remote_major == 1 && remote_minor == 99)) {
470 enable_compat20();
471 } else {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800472 s = "Protocol major versions differ.\n";
473 (void) atomicio(vwrite, sock_out, s, strlen(s));
474 close(sock_in);
475 close(sock_out);
Greg Hartman9768ca42017-06-22 20:49:52 -0700476 logit("Protocol major versions differ for %s port %d: "
477 "%.200s vs. %.200s",
478 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800479 server_version_string, client_version_string);
480 cleanup_exit(255);
481 }
482}
483
484/* Destroy the host and server keys. They will no longer be needed. */
485void
486destroy_sensitive_data(void)
487{
488 int i;
489
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800490 for (i = 0; i < options.num_host_key_files; i++) {
491 if (sensitive_data.host_keys[i]) {
492 key_free(sensitive_data.host_keys[i]);
493 sensitive_data.host_keys[i] = NULL;
494 }
495 if (sensitive_data.host_certificates[i]) {
496 key_free(sensitive_data.host_certificates[i]);
497 sensitive_data.host_certificates[i] = NULL;
498 }
499 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800500}
501
502/* Demote private to public keys for network child */
503void
504demote_sensitive_data(void)
505{
506 Key *tmp;
507 int i;
508
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800509 for (i = 0; i < options.num_host_key_files; i++) {
510 if (sensitive_data.host_keys[i]) {
511 tmp = key_demote(sensitive_data.host_keys[i]);
512 key_free(sensitive_data.host_keys[i]);
513 sensitive_data.host_keys[i] = tmp;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800514 }
515 /* Certs do not need demotion */
516 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700517}
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800518
Greg Hartman9768ca42017-06-22 20:49:52 -0700519static void
520reseed_prngs(void)
521{
522 u_int32_t rnd[256];
523
524#ifdef WITH_OPENSSL
525 RAND_poll();
526#endif
527 arc4random_stir(); /* noop on recent arc4random() implementations */
528 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
529
530#ifdef WITH_OPENSSL
531 RAND_seed(rnd, sizeof(rnd));
532 /* give libcrypto a chance to notice the PID change */
533 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
534 fatal("%s: RAND_bytes failed", __func__);
535#endif
536
537 explicit_bzero(rnd, sizeof(rnd));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800538}
539
540static void
541privsep_preauth_child(void)
542{
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800543 gid_t gidset[1];
544
545 /* Enable challenge-response authentication for privilege separation */
546 privsep_challenge_enable();
547
Adam Langleyd0592972015-03-30 14:49:51 -0700548#ifdef GSSAPI
549 /* Cache supported mechanism OIDs for later use */
550 if (options.gss_authentication)
551 ssh_gssapi_prepare_supported_oids();
552#endif
553
Greg Hartman9768ca42017-06-22 20:49:52 -0700554 reseed_prngs();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800555
556 /* Demote the private keys to public keys. */
557 demote_sensitive_data();
558
Greg Hartman9768ca42017-06-22 20:49:52 -0700559 /* Demote the child */
560 if (getuid() == 0 || geteuid() == 0) {
561 /* Change our root directory */
562 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
563 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
564 strerror(errno));
565 if (chdir("/") == -1)
566 fatal("chdir(\"/\"): %s", strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800567
Greg Hartman9768ca42017-06-22 20:49:52 -0700568 /* Drop our privileges */
569 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
570 (u_int)privsep_pw->pw_gid);
571 gidset[0] = privsep_pw->pw_gid;
572 if (setgroups(1, gidset) < 0)
573 fatal("setgroups: %.100s", strerror(errno));
574 permanently_set_uid(privsep_pw);
575 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800576}
577
578static int
579privsep_preauth(Authctxt *authctxt)
580{
Adam Langleyd0592972015-03-30 14:49:51 -0700581 int status, r;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800582 pid_t pid;
583 struct ssh_sandbox *box = NULL;
584
585 /* Set up unprivileged child process to deal with network data */
586 pmonitor = monitor_init();
587 /* Store a pointer to the kex for later rekeying */
Adam Langleyd0592972015-03-30 14:49:51 -0700588 pmonitor->m_pkex = &active_state->kex;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800589
Adam Langleyd0592972015-03-30 14:49:51 -0700590 if (use_privsep == PRIVSEP_ON)
591 box = ssh_sandbox_init(pmonitor);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800592 pid = fork();
593 if (pid == -1) {
594 fatal("fork of unprivileged child failed");
595 } else if (pid != 0) {
596 debug2("Network child is on pid %ld", (long)pid);
597
Adam Langleyd0592972015-03-30 14:49:51 -0700598 pmonitor->m_pid = pid;
599 if (have_agent) {
600 r = ssh_get_authentication_socket(&auth_sock);
601 if (r != 0) {
602 error("Could not get agent socket: %s",
603 ssh_err(r));
604 have_agent = 0;
605 }
606 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800607 if (box != NULL)
608 ssh_sandbox_parent_preauth(box, pid);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800609 monitor_child_preauth(authctxt, pmonitor);
610
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800611 /* Wait for the child's exit status */
612 while (waitpid(pid, &status, 0) < 0) {
Adam Langleyd0592972015-03-30 14:49:51 -0700613 if (errno == EINTR)
614 continue;
615 pmonitor->m_pid = -1;
616 fatal("%s: waitpid: %s", __func__, strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800617 }
Adam Langleyd0592972015-03-30 14:49:51 -0700618 privsep_is_preauth = 0;
619 pmonitor->m_pid = -1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800620 if (WIFEXITED(status)) {
621 if (WEXITSTATUS(status) != 0)
622 fatal("%s: preauth child exited with status %d",
623 __func__, WEXITSTATUS(status));
624 } else if (WIFSIGNALED(status))
625 fatal("%s: preauth child terminated by signal %d",
626 __func__, WTERMSIG(status));
627 if (box != NULL)
628 ssh_sandbox_parent_finish(box);
629 return 1;
630 } else {
631 /* child */
632 close(pmonitor->m_sendfd);
633 close(pmonitor->m_log_recvfd);
634
635 /* Arrange for logging to be sent to the monitor */
636 set_log_handler(mm_log_handler, pmonitor);
637
Greg Hartman9768ca42017-06-22 20:49:52 -0700638 privsep_preauth_child();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800639 setproctitle("%s", "[net]");
640 if (box != NULL)
641 ssh_sandbox_child(box);
642
643 return 0;
644 }
645}
646
647static void
648privsep_postauth(Authctxt *authctxt)
649{
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800650#ifdef DISABLE_FD_PASSING
651 if (1) {
652#else
Greg Hartman9768ca42017-06-22 20:49:52 -0700653 if (authctxt->pw->pw_uid == 0) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800654#endif
655 /* File descriptor passing is broken or root login */
656 use_privsep = 0;
657 goto skip;
658 }
659
660 /* New socket pair */
661 monitor_reinit(pmonitor);
662
663 pmonitor->m_pid = fork();
664 if (pmonitor->m_pid == -1)
665 fatal("fork of unprivileged child failed");
666 else if (pmonitor->m_pid != 0) {
667 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
668 buffer_clear(&loginmsg);
669 monitor_child_postauth(pmonitor);
670
671 /* NEVERREACHED */
672 exit(0);
673 }
674
675 /* child */
676
677 close(pmonitor->m_sendfd);
678 pmonitor->m_sendfd = -1;
679
680 /* Demote the private keys to public keys. */
681 demote_sensitive_data();
682
Greg Hartman9768ca42017-06-22 20:49:52 -0700683 reseed_prngs();
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800684
685 /* Drop privileges */
686 do_setusercontext(authctxt->pw);
687
688 skip:
689 /* It is safe now to apply the key state */
690 monitor_apply_keystate(pmonitor);
691
692 /*
693 * Tell the packet layer that authentication was successful, since
694 * this information is not part of the key state.
695 */
696 packet_set_authenticated();
697}
698
699static char *
700list_hostkey_types(void)
701{
702 Buffer b;
703 const char *p;
704 char *ret;
705 int i;
706 Key *key;
707
708 buffer_init(&b);
709 for (i = 0; i < options.num_host_key_files; i++) {
710 key = sensitive_data.host_keys[i];
711 if (key == NULL)
Adam Langleyd0592972015-03-30 14:49:51 -0700712 key = sensitive_data.host_pubkeys[i];
Greg Hartman9768ca42017-06-22 20:49:52 -0700713 if (key == NULL)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800714 continue;
Greg Hartmanccacbc92016-02-03 09:59:44 -0800715 /* Check that the key is accepted in HostkeyAlgorithms */
716 if (match_pattern_list(sshkey_ssh_name(key),
717 options.hostkeyalgorithms, 0) != 1) {
718 debug3("%s: %s key not permitted by HostkeyAlgorithms",
719 __func__, sshkey_ssh_name(key));
720 continue;
721 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800722 switch (key->type) {
723 case KEY_RSA:
724 case KEY_DSA:
725 case KEY_ECDSA:
Adam Langleyd0592972015-03-30 14:49:51 -0700726 case KEY_ED25519:
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800727 if (buffer_len(&b) > 0)
728 buffer_append(&b, ",", 1);
729 p = key_ssh_name(key);
730 buffer_append(&b, p, strlen(p));
Greg Hartman9768ca42017-06-22 20:49:52 -0700731
732 /* for RSA we also support SHA2 signatures */
733 if (key->type == KEY_RSA) {
734 p = ",rsa-sha2-512,rsa-sha2-256";
735 buffer_append(&b, p, strlen(p));
736 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800737 break;
738 }
739 /* If the private key has a cert peer, then list that too */
740 key = sensitive_data.host_certificates[i];
741 if (key == NULL)
742 continue;
743 switch (key->type) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800744 case KEY_RSA_CERT:
745 case KEY_DSA_CERT:
746 case KEY_ECDSA_CERT:
Adam Langleyd0592972015-03-30 14:49:51 -0700747 case KEY_ED25519_CERT:
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800748 if (buffer_len(&b) > 0)
749 buffer_append(&b, ",", 1);
750 p = key_ssh_name(key);
751 buffer_append(&b, p, strlen(p));
752 break;
753 }
754 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700755 if ((ret = sshbuf_dup_string(&b)) == NULL)
756 fatal("%s: sshbuf_dup_string failed", __func__);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800757 buffer_free(&b);
758 debug("list_hostkey_types: %s", ret);
759 return ret;
760}
761
762static Key *
Adam Langleyd0592972015-03-30 14:49:51 -0700763get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800764{
765 int i;
766 Key *key;
767
768 for (i = 0; i < options.num_host_key_files; i++) {
769 switch (type) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800770 case KEY_RSA_CERT:
771 case KEY_DSA_CERT:
772 case KEY_ECDSA_CERT:
Adam Langleyd0592972015-03-30 14:49:51 -0700773 case KEY_ED25519_CERT:
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800774 key = sensitive_data.host_certificates[i];
775 break;
776 default:
777 key = sensitive_data.host_keys[i];
Adam Langleyd0592972015-03-30 14:49:51 -0700778 if (key == NULL && !need_private)
779 key = sensitive_data.host_pubkeys[i];
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800780 break;
781 }
Adam Langleyd0592972015-03-30 14:49:51 -0700782 if (key != NULL && key->type == type &&
783 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800784 return need_private ?
785 sensitive_data.host_keys[i] : key;
786 }
787 return NULL;
788}
789
790Key *
Adam Langleyd0592972015-03-30 14:49:51 -0700791get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800792{
Adam Langleyd0592972015-03-30 14:49:51 -0700793 return get_hostkey_by_type(type, nid, 0, ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800794}
795
796Key *
Adam Langleyd0592972015-03-30 14:49:51 -0700797get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800798{
Adam Langleyd0592972015-03-30 14:49:51 -0700799 return get_hostkey_by_type(type, nid, 1, ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800800}
801
802Key *
803get_hostkey_by_index(int ind)
804{
805 if (ind < 0 || ind >= options.num_host_key_files)
806 return (NULL);
807 return (sensitive_data.host_keys[ind]);
808}
809
Adam Langleyd0592972015-03-30 14:49:51 -0700810Key *
811get_hostkey_public_by_index(int ind, struct ssh *ssh)
812{
813 if (ind < 0 || ind >= options.num_host_key_files)
814 return (NULL);
815 return (sensitive_data.host_pubkeys[ind]);
816}
817
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800818int
Adam Langleyd0592972015-03-30 14:49:51 -0700819get_hostkey_index(Key *key, int compare, struct ssh *ssh)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800820{
821 int i;
822
823 for (i = 0; i < options.num_host_key_files; i++) {
824 if (key_is_cert(key)) {
Adam Langleyd0592972015-03-30 14:49:51 -0700825 if (key == sensitive_data.host_certificates[i] ||
826 (compare && sensitive_data.host_certificates[i] &&
827 sshkey_equal(key,
828 sensitive_data.host_certificates[i])))
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800829 return (i);
830 } else {
Adam Langleyd0592972015-03-30 14:49:51 -0700831 if (key == sensitive_data.host_keys[i] ||
832 (compare && sensitive_data.host_keys[i] &&
833 sshkey_equal(key, sensitive_data.host_keys[i])))
834 return (i);
835 if (key == sensitive_data.host_pubkeys[i] ||
836 (compare && sensitive_data.host_pubkeys[i] &&
837 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800838 return (i);
839 }
840 }
841 return (-1);
842}
843
Adam Langleyd0592972015-03-30 14:49:51 -0700844/* Inform the client of all hostkeys */
845static void
846notify_hostkeys(struct ssh *ssh)
847{
848 struct sshbuf *buf;
849 struct sshkey *key;
850 int i, nkeys, r;
851 char *fp;
852
Greg Hartmanccacbc92016-02-03 09:59:44 -0800853 /* Some clients cannot cope with the hostkeys message, skip those. */
854 if (datafellows & SSH_BUG_HOSTKEYS)
855 return;
856
Adam Langleyd0592972015-03-30 14:49:51 -0700857 if ((buf = sshbuf_new()) == NULL)
858 fatal("%s: sshbuf_new", __func__);
859 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
860 key = get_hostkey_public_by_index(i, ssh);
861 if (key == NULL || key->type == KEY_UNSPEC ||
Greg Hartman9768ca42017-06-22 20:49:52 -0700862 sshkey_is_cert(key))
Adam Langleyd0592972015-03-30 14:49:51 -0700863 continue;
864 fp = sshkey_fingerprint(key, options.fingerprint_hash,
865 SSH_FP_DEFAULT);
866 debug3("%s: key %d: %s %s", __func__, i,
867 sshkey_ssh_name(key), fp);
868 free(fp);
869 if (nkeys == 0) {
870 packet_start(SSH2_MSG_GLOBAL_REQUEST);
871 packet_put_cstring("hostkeys-00@openssh.com");
872 packet_put_char(0); /* want-reply */
873 }
874 sshbuf_reset(buf);
875 if ((r = sshkey_putb(key, buf)) != 0)
876 fatal("%s: couldn't put hostkey %d: %s",
877 __func__, i, ssh_err(r));
878 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
879 nkeys++;
880 }
881 debug3("%s: sent %d hostkeys", __func__, nkeys);
882 if (nkeys == 0)
883 fatal("%s: no hostkeys", __func__);
884 packet_send();
885 sshbuf_free(buf);
886}
887
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800888/*
889 * returns 1 if connection should be dropped, 0 otherwise.
890 * dropping starts at connection #max_startups_begin with a probability
891 * of (max_startups_rate/100). the probability increases linearly until
892 * all connections are dropped for startups > max_startups
893 */
894static int
895drop_connection(int startups)
896{
897 int p, r;
898
899 if (startups < options.max_startups_begin)
900 return 0;
901 if (startups >= options.max_startups)
902 return 1;
903 if (options.max_startups_rate == 100)
904 return 1;
905
906 p = 100 - options.max_startups_rate;
907 p *= startups - options.max_startups_begin;
908 p /= options.max_startups - options.max_startups_begin;
909 p += options.max_startups_rate;
910 r = arc4random_uniform(100);
911
912 debug("drop_connection: p %d, r %d", p, r);
913 return (r < p) ? 1 : 0;
914}
915
916static void
917usage(void)
918{
919 fprintf(stderr, "%s, %s\n",
Adam Langleyd0592972015-03-30 14:49:51 -0700920 SSH_RELEASE,
921#ifdef WITH_OPENSSL
922 SSLeay_version(SSLEAY_VERSION)
923#else
924 "without OpenSSL"
925#endif
926 );
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800927 fprintf(stderr,
Greg Hartman9768ca42017-06-22 20:49:52 -0700928"usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
Adam Langleyd0592972015-03-30 14:49:51 -0700929" [-E log_file] [-f config_file] [-g login_grace_time]\n"
Greg Hartman9768ca42017-06-22 20:49:52 -0700930" [-h host_key_file] [-o option] [-p port] [-u len]\n"
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800931 );
932 exit(1);
933}
934
935static void
Greg Hartman9768ca42017-06-22 20:49:52 -0700936send_rexec_state(int fd, struct sshbuf *conf)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800937{
Greg Hartman9768ca42017-06-22 20:49:52 -0700938 struct sshbuf *m;
939 int r;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800940
Greg Hartman9768ca42017-06-22 20:49:52 -0700941 debug3("%s: entering fd = %d config len %zu", __func__, fd,
942 sshbuf_len(conf));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800943
944 /*
945 * Protocol from reexec master to child:
946 * string configuration
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800947 * string rngseed (only if OpenSSL is not self-seeded)
948 */
Greg Hartman9768ca42017-06-22 20:49:52 -0700949 if ((m = sshbuf_new()) == NULL)
950 fatal("%s: sshbuf_new failed", __func__);
951 if ((r = sshbuf_put_stringb(m, conf)) != 0)
952 fatal("%s: buffer error: %s", __func__, ssh_err(r));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800953
Adam Langleyd0592972015-03-30 14:49:51 -0700954#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
Greg Hartman9768ca42017-06-22 20:49:52 -0700955 rexec_send_rng_seed(m);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800956#endif
957
Greg Hartman9768ca42017-06-22 20:49:52 -0700958 if (ssh_msg_send(fd, 0, m) == -1)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800959 fatal("%s: ssh_msg_send failed", __func__);
960
Greg Hartman9768ca42017-06-22 20:49:52 -0700961 sshbuf_free(m);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800962
963 debug3("%s: done", __func__);
964}
965
966static void
967recv_rexec_state(int fd, Buffer *conf)
968{
969 Buffer m;
970 char *cp;
971 u_int len;
972
973 debug3("%s: entering fd = %d", __func__, fd);
974
975 buffer_init(&m);
976
977 if (ssh_msg_recv(fd, &m) == -1)
978 fatal("%s: ssh_msg_recv failed", __func__);
979 if (buffer_get_char(&m) != 0)
980 fatal("%s: rexec version mismatch", __func__);
981
982 cp = buffer_get_string(&m, &len);
983 if (conf != NULL)
Greg Hartman9768ca42017-06-22 20:49:52 -0700984 buffer_append(conf, cp, len);
Adam Langleyd0592972015-03-30 14:49:51 -0700985 free(cp);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800986
Adam Langleyd0592972015-03-30 14:49:51 -0700987#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800988 rexec_recv_rng_seed(&m);
989#endif
990
991 buffer_free(&m);
992
993 debug3("%s: done", __func__);
994}
995
996/* Accept a connection from inetd */
997static void
998server_accept_inetd(int *sock_in, int *sock_out)
999{
1000 int fd;
1001
1002 startup_pipe = -1;
1003 if (rexeced_flag) {
1004 close(REEXEC_CONFIG_PASS_FD);
1005 *sock_in = *sock_out = dup(STDIN_FILENO);
1006 if (!debug_flag) {
1007 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1008 close(REEXEC_STARTUP_PIPE_FD);
1009 }
1010 } else {
1011 *sock_in = dup(STDIN_FILENO);
1012 *sock_out = dup(STDOUT_FILENO);
1013 }
1014 /*
1015 * We intentionally do not close the descriptors 0, 1, and 2
1016 * as our code for setting the descriptors won't work if
1017 * ttyfd happens to be one of those.
1018 */
1019 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1020 dup2(fd, STDIN_FILENO);
1021 dup2(fd, STDOUT_FILENO);
Adam Langleyd0592972015-03-30 14:49:51 -07001022 if (!log_stderr)
1023 dup2(fd, STDERR_FILENO);
1024 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001025 close(fd);
1026 }
1027 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1028}
1029
1030/*
1031 * Listen for TCP connections
1032 */
1033static void
1034server_listen(void)
1035{
1036 int ret, listen_sock, on = 1;
1037 struct addrinfo *ai;
1038 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1039
1040 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1041 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1042 continue;
1043 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1044 fatal("Too many listen sockets. "
1045 "Enlarge MAX_LISTEN_SOCKS");
1046 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1047 ntop, sizeof(ntop), strport, sizeof(strport),
1048 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1049 error("getnameinfo failed: %.100s",
1050 ssh_gai_strerror(ret));
1051 continue;
1052 }
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001053
Greg Hartman5bcf61c2017-12-07 16:24:36 -08001054#if defined(ANDROID_GCE)
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001055 /*
1056 * Android GCE specific, bug 67899876
1057 * Open socket in external namespace, making it possible to serve SSH
1058 * connections regardless of internal interface states.
1059 */
1060 int outerfd = open("/var/run/netns/outer.net", O_RDONLY);
1061 int androidfd = open("/var/run/netns/android.net", O_RDONLY);
1062 if (outerfd > 0 && androidfd > 0) {
Greg Hartman237e44d2017-12-07 18:17:51 -08001063 if (gce_setns(outerfd, 0) != 0) {
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001064 fprintf(stderr, "Could not set netns: %s\n",
1065 strerror(errno));
1066 exit(1);
1067 }
1068 }
1069#endif
1070
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001071 /* Create socket for listening. */
1072 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1073 ai->ai_protocol);
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001074
Greg Hartman5bcf61c2017-12-07 16:24:36 -08001075#if defined(ANDROID_GCE)
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001076 if (androidfd > 0) {
Greg Hartman237e44d2017-12-07 18:17:51 -08001077 if (gce_setns(androidfd, 0) != 0) {
Tomasz Wiszkowski721b0752017-10-18 11:51:30 -07001078 fprintf(stderr, "Could not set netns: %s\n",
1079 strerror(errno));
1080 exit(1);
1081 }
1082 }
1083 if (outerfd > 0) {
1084 close(outerfd);
1085 }
1086 if (androidfd > 0) {
1087 close(androidfd);
1088 }
1089#endif
1090
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001091 if (listen_sock < 0) {
1092 /* kernel may not support ipv6 */
1093 verbose("socket: %.100s", strerror(errno));
1094 continue;
1095 }
1096 if (set_nonblock(listen_sock) == -1) {
1097 close(listen_sock);
1098 continue;
1099 }
Greg Hartman9768ca42017-06-22 20:49:52 -07001100 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1101 verbose("socket: CLOEXEC: %s", strerror(errno));
1102 close(listen_sock);
1103 continue;
1104 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001105 /*
1106 * Set socket options.
1107 * Allow local port reuse in TIME_WAIT.
1108 */
1109 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1110 &on, sizeof(on)) == -1)
1111 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1112
1113 /* Only communicate in IPv6 over AF_INET6 sockets. */
1114 if (ai->ai_family == AF_INET6)
1115 sock_set_v6only(listen_sock);
1116
1117 debug("Bind to port %s on %s.", strport, ntop);
1118
1119 /* Bind the socket to the desired port. */
1120 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1121 error("Bind to port %s on %s failed: %.200s.",
1122 strport, ntop, strerror(errno));
1123 close(listen_sock);
1124 continue;
1125 }
1126 listen_socks[num_listen_socks] = listen_sock;
1127 num_listen_socks++;
1128
1129 /* Start listening on the port. */
1130 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1131 fatal("listen on [%s]:%s: %.100s",
1132 ntop, strport, strerror(errno));
1133 logit("Server listening on %s port %s.", ntop, strport);
1134 }
1135 freeaddrinfo(options.listen_addrs);
1136
1137 if (!num_listen_socks)
1138 fatal("Cannot bind any address.");
1139}
1140
1141/*
1142 * The main TCP accept loop. Note that, for the non-debug case, returns
1143 * from this function are in a forked subprocess.
1144 */
1145static void
1146server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1147{
1148 fd_set *fdset;
1149 int i, j, ret, maxfd;
Greg Hartman9768ca42017-06-22 20:49:52 -07001150 int startups = 0;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001151 int startup_p[2] = { -1 , -1 };
1152 struct sockaddr_storage from;
1153 socklen_t fromlen;
1154 pid_t pid;
Adam Langleyd0592972015-03-30 14:49:51 -07001155 u_char rnd[256];
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001156
1157 /* setup fd set for accept */
1158 fdset = NULL;
1159 maxfd = 0;
1160 for (i = 0; i < num_listen_socks; i++)
1161 if (listen_socks[i] > maxfd)
1162 maxfd = listen_socks[i];
1163 /* pipes connected to unauthenticated childs */
1164 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1165 for (i = 0; i < options.max_startups; i++)
1166 startup_pipes[i] = -1;
1167
1168 /*
1169 * Stay listening for connections until the system crashes or
1170 * the daemon is killed with a signal.
1171 */
1172 for (;;) {
1173 if (received_sighup)
1174 sighup_restart();
Greg Hartman9768ca42017-06-22 20:49:52 -07001175 free(fdset);
Greg Hartmanccacbc92016-02-03 09:59:44 -08001176 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001177 sizeof(fd_mask));
1178
1179 for (i = 0; i < num_listen_socks; i++)
1180 FD_SET(listen_socks[i], fdset);
1181 for (i = 0; i < options.max_startups; i++)
1182 if (startup_pipes[i] != -1)
1183 FD_SET(startup_pipes[i], fdset);
1184
1185 /* Wait in select until there is a connection. */
1186 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1187 if (ret < 0 && errno != EINTR)
1188 error("select: %.100s", strerror(errno));
1189 if (received_sigterm) {
1190 logit("Received signal %d; terminating.",
1191 (int) received_sigterm);
1192 close_listen_socks();
Adam Langleyd0592972015-03-30 14:49:51 -07001193 if (options.pid_file != NULL)
1194 unlink(options.pid_file);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001195 exit(received_sigterm == SIGTERM ? 0 : 255);
1196 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001197 if (ret < 0)
1198 continue;
1199
1200 for (i = 0; i < options.max_startups; i++)
1201 if (startup_pipes[i] != -1 &&
1202 FD_ISSET(startup_pipes[i], fdset)) {
1203 /*
1204 * the read end of the pipe is ready
1205 * if the child has closed the pipe
1206 * after successful authentication
1207 * or if the child has died
1208 */
1209 close(startup_pipes[i]);
1210 startup_pipes[i] = -1;
1211 startups--;
1212 }
1213 for (i = 0; i < num_listen_socks; i++) {
1214 if (!FD_ISSET(listen_socks[i], fdset))
1215 continue;
1216 fromlen = sizeof(from);
1217 *newsock = accept(listen_socks[i],
1218 (struct sockaddr *)&from, &fromlen);
1219 if (*newsock < 0) {
Adam Langleyd0592972015-03-30 14:49:51 -07001220 if (errno != EINTR && errno != EWOULDBLOCK &&
1221 errno != ECONNABORTED && errno != EAGAIN)
1222 error("accept: %.100s",
1223 strerror(errno));
1224 if (errno == EMFILE || errno == ENFILE)
1225 usleep(100 * 1000);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001226 continue;
1227 }
1228 if (unset_nonblock(*newsock) == -1) {
1229 close(*newsock);
1230 continue;
1231 }
1232 if (drop_connection(startups) == 1) {
Greg Hartman9768ca42017-06-22 20:49:52 -07001233 char *laddr = get_local_ipaddr(*newsock);
1234 char *raddr = get_peer_ipaddr(*newsock);
1235
1236 verbose("drop connection #%d from [%s]:%d "
1237 "on [%s]:%d past MaxStartups", startups,
1238 raddr, get_peer_port(*newsock),
1239 laddr, get_local_port(*newsock));
1240 free(laddr);
1241 free(raddr);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001242 close(*newsock);
1243 continue;
1244 }
1245 if (pipe(startup_p) == -1) {
1246 close(*newsock);
1247 continue;
1248 }
1249
1250 if (rexec_flag && socketpair(AF_UNIX,
1251 SOCK_STREAM, 0, config_s) == -1) {
1252 error("reexec socketpair: %s",
1253 strerror(errno));
1254 close(*newsock);
1255 close(startup_p[0]);
1256 close(startup_p[1]);
1257 continue;
1258 }
1259
1260 for (j = 0; j < options.max_startups; j++)
1261 if (startup_pipes[j] == -1) {
1262 startup_pipes[j] = startup_p[0];
1263 if (maxfd < startup_p[0])
1264 maxfd = startup_p[0];
1265 startups++;
1266 break;
1267 }
1268
1269 /*
1270 * Got connection. Fork a child to handle it, unless
1271 * we are in debugging mode.
1272 */
1273 if (debug_flag) {
1274 /*
1275 * In debugging mode. Close the listening
1276 * socket, and start processing the
1277 * connection without forking.
1278 */
1279 debug("Server will not fork when running in debugging mode.");
1280 close_listen_socks();
1281 *sock_in = *newsock;
1282 *sock_out = *newsock;
1283 close(startup_p[0]);
1284 close(startup_p[1]);
1285 startup_pipe = -1;
1286 pid = getpid();
1287 if (rexec_flag) {
1288 send_rexec_state(config_s[0],
1289 &cfg);
1290 close(config_s[0]);
1291 }
1292 break;
1293 }
1294
1295 /*
1296 * Normal production daemon. Fork, and have
1297 * the child process the connection. The
1298 * parent continues listening.
1299 */
1300 platform_pre_fork();
1301 if ((pid = fork()) == 0) {
1302 /*
1303 * Child. Close the listening and
1304 * max_startup sockets. Start using
1305 * the accepted socket. Reinitialize
1306 * logging (since our pid has changed).
1307 * We break out of the loop to handle
1308 * the connection.
1309 */
1310 platform_post_fork_child();
1311 startup_pipe = startup_p[1];
1312 close_startup_pipes();
1313 close_listen_socks();
1314 *sock_in = *newsock;
1315 *sock_out = *newsock;
1316 log_init(__progname,
1317 options.log_level,
1318 options.log_facility,
1319 log_stderr);
1320 if (rexec_flag)
1321 close(config_s[0]);
1322 break;
1323 }
1324
1325 /* Parent. Stay in the loop. */
1326 platform_post_fork_parent(pid);
1327 if (pid < 0)
1328 error("fork: %.100s", strerror(errno));
1329 else
1330 debug("Forked child %ld.", (long)pid);
1331
1332 close(startup_p[1]);
1333
1334 if (rexec_flag) {
1335 send_rexec_state(config_s[0], &cfg);
1336 close(config_s[0]);
1337 close(config_s[1]);
1338 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001339 close(*newsock);
1340
1341 /*
1342 * Ensure that our random state differs
1343 * from that of the child
1344 */
1345 arc4random_stir();
Adam Langleyd0592972015-03-30 14:49:51 -07001346 arc4random_buf(rnd, sizeof(rnd));
1347#ifdef WITH_OPENSSL
1348 RAND_seed(rnd, sizeof(rnd));
Greg Hartman7d4e4742015-11-16 10:13:36 -08001349 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1350 fatal("%s: RAND_bytes failed", __func__);
Adam Langleyd0592972015-03-30 14:49:51 -07001351#endif
1352 explicit_bzero(rnd, sizeof(rnd));
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001353 }
1354
1355 /* child process check (or debug mode) */
1356 if (num_listen_socks < 0)
1357 break;
1358 }
1359}
1360
Greg Hartman9768ca42017-06-22 20:49:52 -07001361/*
1362 * If IP options are supported, make sure there are none (log and
1363 * return an error if any are found). Basically we are worried about
1364 * source routing; it can be used to pretend you are somebody
1365 * (ip-address) you are not. That itself may be "almost acceptable"
1366 * under certain circumstances, but rhosts autentication is useless
1367 * if source routing is accepted. Notice also that if we just dropped
1368 * source routing here, the other side could use IP spoofing to do
1369 * rest of the interaction and could still bypass security. So we
1370 * exit here if we detect any IP options.
1371 */
1372static void
1373check_ip_options(struct ssh *ssh)
1374{
1375#ifdef IP_OPTIONS
1376 int sock_in = ssh_packet_get_connection_in(ssh);
1377 struct sockaddr_storage from;
1378 u_char opts[200];
1379 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1380 char text[sizeof(opts) * 3 + 1];
1381
1382 memset(&from, 0, sizeof(from));
1383 if (getpeername(sock_in, (struct sockaddr *)&from,
1384 &fromlen) < 0)
1385 return;
1386 if (from.ss_family != AF_INET)
1387 return;
1388 /* XXX IPv6 options? */
1389
1390 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1391 &option_size) >= 0 && option_size != 0) {
1392 text[0] = '\0';
1393 for (i = 0; i < option_size; i++)
1394 snprintf(text + i*3, sizeof(text) - i*3,
1395 " %2.2x", opts[i]);
1396 fatal("Connection from %.100s port %d with IP opts: %.800s",
1397 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1398 }
1399 return;
1400#endif /* IP_OPTIONS */
1401}
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001402
1403/*
1404 * Main program for the daemon.
1405 */
1406int
1407main(int ac, char **av)
1408{
Greg Hartman9768ca42017-06-22 20:49:52 -07001409 struct ssh *ssh = NULL;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001410 extern char *optarg;
1411 extern int optind;
Greg Hartman9768ca42017-06-22 20:49:52 -07001412 int r, opt, i, j, on = 1, already_daemon;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001413 int sock_in = -1, sock_out = -1, newsock = -1;
1414 const char *remote_ip;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001415 int remote_port;
Greg Hartmanccacbc92016-02-03 09:59:44 -08001416 char *fp, *line, *laddr, *logfile = NULL;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001417 int config_s[2] = { -1 , -1 };
Adam Langleyd0592972015-03-30 14:49:51 -07001418 u_int n;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001419 u_int64_t ibytes, obytes;
1420 mode_t new_umask;
1421 Key *key;
Adam Langleyd0592972015-03-30 14:49:51 -07001422 Key *pubkey;
1423 int keytype;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001424 Authctxt *authctxt;
Adam Langleyd0592972015-03-30 14:49:51 -07001425 struct connection_info *connection_info = get_connection_info(0, 0);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001426
Greg Hartman9768ca42017-06-22 20:49:52 -07001427 ssh_malloc_init(); /* must be called before any mallocs */
1428
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001429#ifdef HAVE_SECUREWARE
1430 (void)set_auth_parameters(ac, av);
1431#endif
1432 __progname = ssh_get_progname(av[0]);
1433
1434 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1435 saved_argc = ac;
1436 rexec_argc = ac;
1437 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1438 for (i = 0; i < ac; i++)
1439 saved_argv[i] = xstrdup(av[i]);
1440 saved_argv[i] = NULL;
1441
1442#ifndef HAVE_SETPROCTITLE
1443 /* Prepare for later setproctitle emulation */
1444 compat_init_setproctitle(ac, av);
1445 av = saved_argv;
1446#endif
1447
1448 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1449 debug("setgroups(): %.200s", strerror(errno));
1450
1451 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1452 sanitise_stdfd();
1453
1454 /* Initialize configuration options to their default values. */
1455 initialize_server_options(&options);
1456
1457 /* Parse command-line arguments. */
Greg Hartmanccacbc92016-02-03 09:59:44 -08001458 while ((opt = getopt(ac, av,
1459 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001460 switch (opt) {
1461 case '4':
1462 options.address_family = AF_INET;
1463 break;
1464 case '6':
1465 options.address_family = AF_INET6;
1466 break;
1467 case 'f':
1468 config_file_name = optarg;
1469 break;
1470 case 'c':
1471 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1472 fprintf(stderr, "too many host certificates.\n");
1473 exit(1);
1474 }
1475 options.host_cert_files[options.num_host_cert_files++] =
1476 derelativise_path(optarg);
1477 break;
1478 case 'd':
1479 if (debug_flag == 0) {
1480 debug_flag = 1;
1481 options.log_level = SYSLOG_LEVEL_DEBUG1;
1482 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1483 options.log_level++;
1484 break;
1485 case 'D':
1486 no_daemon_flag = 1;
1487 break;
Adam Langleyd0592972015-03-30 14:49:51 -07001488 case 'E':
Greg Hartman9768ca42017-06-22 20:49:52 -07001489 logfile = optarg;
Adam Langleyd0592972015-03-30 14:49:51 -07001490 /* FALLTHROUGH */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001491 case 'e':
1492 log_stderr = 1;
1493 break;
1494 case 'i':
1495 inetd_flag = 1;
1496 break;
1497 case 'r':
1498 rexec_flag = 0;
1499 break;
1500 case 'R':
1501 rexeced_flag = 1;
1502 inetd_flag = 1;
1503 break;
1504 case 'Q':
1505 /* ignored */
1506 break;
1507 case 'q':
1508 options.log_level = SYSLOG_LEVEL_QUIET;
1509 break;
1510 case 'b':
Greg Hartman9768ca42017-06-22 20:49:52 -07001511 /* protocol 1, ignored */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001512 break;
1513 case 'p':
1514 options.ports_from_cmdline = 1;
1515 if (options.num_ports >= MAX_PORTS) {
1516 fprintf(stderr, "too many ports.\n");
1517 exit(1);
1518 }
1519 options.ports[options.num_ports++] = a2port(optarg);
1520 if (options.ports[options.num_ports-1] <= 0) {
1521 fprintf(stderr, "Bad port number.\n");
1522 exit(1);
1523 }
1524 break;
1525 case 'g':
1526 if ((options.login_grace_time = convtime(optarg)) == -1) {
1527 fprintf(stderr, "Invalid login grace time.\n");
1528 exit(1);
1529 }
1530 break;
1531 case 'k':
Greg Hartman9768ca42017-06-22 20:49:52 -07001532 /* protocol 1, ignored */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001533 break;
1534 case 'h':
1535 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1536 fprintf(stderr, "too many host keys.\n");
1537 exit(1);
1538 }
1539 options.host_key_files[options.num_host_key_files++] =
1540 derelativise_path(optarg);
1541 break;
1542 case 't':
1543 test_flag = 1;
1544 break;
1545 case 'T':
1546 test_flag = 2;
1547 break;
1548 case 'C':
Adam Langleyd0592972015-03-30 14:49:51 -07001549 if (parse_server_match_testspec(connection_info,
1550 optarg) == -1)
1551 exit(1);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001552 break;
1553 case 'u':
Adam Langleyd0592972015-03-30 14:49:51 -07001554 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1555 if (utmp_len > HOST_NAME_MAX+1) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001556 fprintf(stderr, "Invalid utmp length.\n");
1557 exit(1);
1558 }
1559 break;
1560 case 'o':
1561 line = xstrdup(optarg);
1562 if (process_server_config_line(&options, line,
Adam Langleyd0592972015-03-30 14:49:51 -07001563 "command-line", 0, NULL, NULL) != 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001564 exit(1);
Adam Langleyd0592972015-03-30 14:49:51 -07001565 free(line);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001566 break;
1567 case '?':
1568 default:
1569 usage();
1570 break;
1571 }
1572 }
1573 if (rexeced_flag || inetd_flag)
1574 rexec_flag = 0;
1575 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1576 fatal("sshd re-exec requires execution with an absolute path");
1577 if (rexeced_flag)
1578 closefrom(REEXEC_MIN_FREE_FD);
1579 else
1580 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1581
Adam Langleyd0592972015-03-30 14:49:51 -07001582#ifdef WITH_OPENSSL
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001583 OpenSSL_add_all_algorithms();
Adam Langleyd0592972015-03-30 14:49:51 -07001584#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001585
Adam Langleyd0592972015-03-30 14:49:51 -07001586 /* If requested, redirect the logs to the specified logfile. */
Greg Hartman9768ca42017-06-22 20:49:52 -07001587 if (logfile != NULL)
Adam Langleyd0592972015-03-30 14:49:51 -07001588 log_redirect_stderr_to(logfile);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001589 /*
1590 * Force logging to stderr until we have loaded the private host
1591 * key (unless started from inetd)
1592 */
1593 log_init(__progname,
1594 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1595 SYSLOG_LEVEL_INFO : options.log_level,
1596 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1597 SYSLOG_FACILITY_AUTH : options.log_facility,
1598 log_stderr || !inetd_flag);
1599
1600 /*
1601 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1602 * root's environment
1603 */
1604 if (getenv("KRB5CCNAME") != NULL)
Adam Langleyd0592972015-03-30 14:49:51 -07001605 (void) unsetenv("KRB5CCNAME");
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001606
1607#ifdef _UNICOS
1608 /* Cray can define user privs drop all privs now!
1609 * Not needed on PRIV_SU systems!
1610 */
1611 drop_cray_privs();
1612#endif
1613
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001614 sensitive_data.have_ssh2_key = 0;
1615
1616 /*
1617 * If we're doing an extended config test, make sure we have all of
1618 * the parameters we need. If we're not doing an extended test,
1619 * do not silently ignore connection test params.
1620 */
Adam Langleyd0592972015-03-30 14:49:51 -07001621 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001622 fatal("user, host and addr are all required when testing "
1623 "Match configs");
Adam Langleyd0592972015-03-30 14:49:51 -07001624 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001625 fatal("Config test connection parameter (-C) provided without "
1626 "test mode (-T)");
1627
1628 /* Fetch our configuration */
1629 buffer_init(&cfg);
1630 if (rexeced_flag)
1631 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
Greg Hartmanccacbc92016-02-03 09:59:44 -08001632 else if (strcasecmp(config_file_name, "none") != 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001633 load_server_config(config_file_name, &cfg);
1634
1635 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
Adam Langleyd0592972015-03-30 14:49:51 -07001636 &cfg, NULL);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001637
1638 seed_rng();
1639
1640 /* Fill in default values for those options not explicitly set. */
1641 fill_default_server_options(&options);
1642
1643 /* challenge-response is implemented via keyboard interactive */
1644 if (options.challenge_response_authentication)
1645 options.kbd_interactive_authentication = 1;
1646
Adam Langleyd0592972015-03-30 14:49:51 -07001647 /* Check that options are sensible */
1648 if (options.authorized_keys_command_user == NULL &&
1649 (options.authorized_keys_command != NULL &&
1650 strcasecmp(options.authorized_keys_command, "none") != 0))
1651 fatal("AuthorizedKeysCommand set without "
1652 "AuthorizedKeysCommandUser");
Greg Hartmanccacbc92016-02-03 09:59:44 -08001653 if (options.authorized_principals_command_user == NULL &&
1654 (options.authorized_principals_command != NULL &&
1655 strcasecmp(options.authorized_principals_command, "none") != 0))
1656 fatal("AuthorizedPrincipalsCommand set without "
1657 "AuthorizedPrincipalsCommandUser");
Adam Langleyd0592972015-03-30 14:49:51 -07001658
1659 /*
1660 * Check whether there is any path through configured auth methods.
1661 * Unfortunately it is not possible to verify this generally before
1662 * daemonisation in the presence of Match block, but this catches
1663 * and warns for trivial misconfigurations that could break login.
1664 */
1665 if (options.num_auth_methods != 0) {
Adam Langleyd0592972015-03-30 14:49:51 -07001666 for (n = 0; n < options.num_auth_methods; n++) {
1667 if (auth2_methods_valid(options.auth_methods[n],
1668 1) == 0)
1669 break;
1670 }
1671 if (n >= options.num_auth_methods)
1672 fatal("AuthenticationMethods cannot be satisfied by "
1673 "enabled authentication methods");
1674 }
1675
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001676 /* set default channel AF */
1677 channel_set_af(options.address_family);
1678
1679 /* Check that there are no remaining arguments. */
1680 if (optind < ac) {
1681 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1682 exit(1);
1683 }
1684
Adam Langleyd0592972015-03-30 14:49:51 -07001685 debug("sshd version %s, %s", SSH_VERSION,
1686#ifdef WITH_OPENSSL
1687 SSLeay_version(SSLEAY_VERSION)
1688#else
1689 "without OpenSSL"
1690#endif
1691 );
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001692
1693 /* Store privilege separation user for later use if required. */
1694 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1695 if (use_privsep || options.kerberos_authentication)
1696 fatal("Privilege separation user %s does not exist",
1697 SSH_PRIVSEP_USER);
1698 } else {
Greg Hartman9768ca42017-06-22 20:49:52 -07001699#if defined(ANDROID)
1700/* Android does not do passwords and passes NULL for them. This breaks strlen */
1701 if (privsep_pw->pw_passwd) {
1702#endif
1703 explicit_bzero(privsep_pw->pw_passwd,
1704 strlen(privsep_pw->pw_passwd));
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001705 privsep_pw = pwcopy(privsep_pw);
Greg Hartman9768ca42017-06-22 20:49:52 -07001706 free(privsep_pw->pw_passwd);
1707#if defined(ANDROID)
1708 }
1709#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001710 privsep_pw->pw_passwd = xstrdup("*");
1711 }
Adam Langleyd0592972015-03-30 14:49:51 -07001712#if !defined(ANDROID)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001713 endpwent();
Greg Hartmanf5c67b42015-02-27 07:55:00 -08001714#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001715
Adam Langleyd0592972015-03-30 14:49:51 -07001716 /* load host keys */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001717 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1718 sizeof(Key *));
Adam Langleyd0592972015-03-30 14:49:51 -07001719 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1720 sizeof(Key *));
1721
1722 if (options.host_key_agent) {
1723 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1724 setenv(SSH_AUTHSOCKET_ENV_NAME,
1725 options.host_key_agent, 1);
1726 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1727 have_agent = 1;
1728 else
1729 error("Could not connect to agent \"%s\": %s",
1730 options.host_key_agent, ssh_err(r));
1731 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001732
1733 for (i = 0; i < options.num_host_key_files; i++) {
Adam Langleyd0592972015-03-30 14:49:51 -07001734 if (options.host_key_files[i] == NULL)
1735 continue;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001736 key = key_load_private(options.host_key_files[i], "", NULL);
Adam Langleyd0592972015-03-30 14:49:51 -07001737 pubkey = key_load_public(options.host_key_files[i], NULL);
Greg Hartman9768ca42017-06-22 20:49:52 -07001738
1739 if ((pubkey != NULL && pubkey->type == KEY_RSA1) ||
1740 (key != NULL && key->type == KEY_RSA1)) {
1741 verbose("Ignoring RSA1 key %s",
1742 options.host_key_files[i]);
1743 key_free(key);
1744 key_free(pubkey);
1745 continue;
1746 }
Adam Langleyd0592972015-03-30 14:49:51 -07001747 if (pubkey == NULL && key != NULL)
1748 pubkey = key_demote(key);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001749 sensitive_data.host_keys[i] = key;
Adam Langleyd0592972015-03-30 14:49:51 -07001750 sensitive_data.host_pubkeys[i] = pubkey;
1751
Greg Hartman9768ca42017-06-22 20:49:52 -07001752 if (key == NULL && pubkey != NULL && have_agent) {
Adam Langleyd0592972015-03-30 14:49:51 -07001753 debug("will rely on agent for hostkey %s",
1754 options.host_key_files[i]);
1755 keytype = pubkey->type;
1756 } else if (key != NULL) {
1757 keytype = key->type;
1758 } else {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001759 error("Could not load host key: %s",
1760 options.host_key_files[i]);
1761 sensitive_data.host_keys[i] = NULL;
Adam Langleyd0592972015-03-30 14:49:51 -07001762 sensitive_data.host_pubkeys[i] = NULL;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001763 continue;
1764 }
Adam Langleyd0592972015-03-30 14:49:51 -07001765
1766 switch (keytype) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001767 case KEY_RSA:
1768 case KEY_DSA:
1769 case KEY_ECDSA:
Adam Langleyd0592972015-03-30 14:49:51 -07001770 case KEY_ED25519:
1771 if (have_agent || key != NULL)
1772 sensitive_data.have_ssh2_key = 1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001773 break;
1774 }
Adam Langleyd0592972015-03-30 14:49:51 -07001775 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1776 SSH_FP_DEFAULT)) == NULL)
1777 fatal("sshkey_fingerprint failed");
1778 debug("%s host key #%d: %s %s",
Greg Hartman9768ca42017-06-22 20:49:52 -07001779 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
Adam Langleyd0592972015-03-30 14:49:51 -07001780 free(fp);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001781 }
Greg Hartman9768ca42017-06-22 20:49:52 -07001782 if (!sensitive_data.have_ssh2_key) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001783 logit("sshd: no hostkeys available -- exiting.");
1784 exit(1);
1785 }
1786
1787 /*
1788 * Load certificates. They are stored in an array at identical
1789 * indices to the public keys that they relate to.
1790 */
1791 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1792 sizeof(Key *));
1793 for (i = 0; i < options.num_host_key_files; i++)
1794 sensitive_data.host_certificates[i] = NULL;
1795
1796 for (i = 0; i < options.num_host_cert_files; i++) {
Adam Langleyd0592972015-03-30 14:49:51 -07001797 if (options.host_cert_files[i] == NULL)
1798 continue;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001799 key = key_load_public(options.host_cert_files[i], NULL);
1800 if (key == NULL) {
1801 error("Could not load host certificate: %s",
1802 options.host_cert_files[i]);
1803 continue;
1804 }
1805 if (!key_is_cert(key)) {
1806 error("Certificate file is not a certificate: %s",
1807 options.host_cert_files[i]);
1808 key_free(key);
1809 continue;
1810 }
1811 /* Find matching private key */
1812 for (j = 0; j < options.num_host_key_files; j++) {
1813 if (key_equal_public(key,
1814 sensitive_data.host_keys[j])) {
1815 sensitive_data.host_certificates[j] = key;
1816 break;
1817 }
1818 }
1819 if (j >= options.num_host_key_files) {
1820 error("No matching private key for certificate: %s",
1821 options.host_cert_files[i]);
1822 key_free(key);
1823 continue;
1824 }
1825 sensitive_data.host_certificates[j] = key;
1826 debug("host certificate: #%d type %d %s", j, key->type,
1827 key_type(key));
1828 }
Adam Langleyd0592972015-03-30 14:49:51 -07001829
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001830 if (use_privsep) {
1831 struct stat st;
1832
1833 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1834 (S_ISDIR(st.st_mode) == 0))
1835 fatal("Missing privilege separation directory: %s",
1836 _PATH_PRIVSEP_CHROOT_DIR);
1837
1838#ifdef HAVE_CYGWIN
1839 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1840 (st.st_uid != getuid () ||
1841 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1842#else
1843 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1844#endif
1845 fatal("%s must be owned by root and not group or "
1846 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1847 }
1848
1849 if (test_flag > 1) {
Adam Langleyd0592972015-03-30 14:49:51 -07001850 if (server_match_spec_complete(connection_info) == 1)
1851 parse_server_match_config(&options, connection_info);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001852 dump_config(&options);
1853 }
1854
1855 /* Configuration looks good, so exit if in test mode. */
1856 if (test_flag)
1857 exit(0);
1858
1859 /*
1860 * Clear out any supplemental groups we may have inherited. This
1861 * prevents inadvertent creation of files with bad modes (in the
1862 * portable version at least, it's certainly possible for PAM
1863 * to create a file, and we can't control the code in every
1864 * module which might be used).
1865 */
1866 if (setgroups(0, NULL) < 0)
1867 debug("setgroups() failed: %.200s", strerror(errno));
1868
1869 if (rexec_flag) {
1870 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1871 for (i = 0; i < rexec_argc; i++) {
1872 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1873 rexec_argv[i] = saved_argv[i];
1874 }
1875 rexec_argv[rexec_argc] = "-R";
1876 rexec_argv[rexec_argc + 1] = NULL;
1877 }
1878
1879 /* Ensure that umask disallows at least group and world write */
1880 new_umask = umask(0077) | 0022;
1881 (void) umask(new_umask);
1882
1883 /* Initialize the log (it is reinitialized below in case we forked). */
1884 if (debug_flag && (!inetd_flag || rexeced_flag))
1885 log_stderr = 1;
1886 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1887
1888 /*
Greg Hartman9768ca42017-06-22 20:49:52 -07001889 * If not in debugging mode, not started from inetd and not already
1890 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1891 * terminal, and fork. The original process exits.
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001892 */
Greg Hartman9768ca42017-06-22 20:49:52 -07001893 already_daemon = daemonized();
1894 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1895
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001896 if (daemon(0, 0) < 0)
1897 fatal("daemon() failed: %.200s", strerror(errno));
1898
Greg Hartman9768ca42017-06-22 20:49:52 -07001899 disconnect_controlling_tty();
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001900 }
1901 /* Reinitialize the log (because of the fork above). */
1902 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1903
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001904 /* Chdir to the root directory so that the current disk can be
1905 unmounted if desired. */
Adam Langleyd0592972015-03-30 14:49:51 -07001906 if (chdir("/") == -1)
1907 error("chdir(\"/\"): %s", strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001908
1909 /* ignore SIGPIPE */
1910 signal(SIGPIPE, SIG_IGN);
1911
1912 /* Get a connection, either from inetd or a listening TCP socket */
1913 if (inetd_flag) {
1914 server_accept_inetd(&sock_in, &sock_out);
1915 } else {
1916 platform_pre_listen();
1917 server_listen();
1918
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001919 signal(SIGHUP, sighup_handler);
1920 signal(SIGCHLD, main_sigchld_handler);
1921 signal(SIGTERM, sigterm_handler);
1922 signal(SIGQUIT, sigterm_handler);
1923
1924 /*
1925 * Write out the pid file after the sigterm handler
1926 * is setup and the listen sockets are bound
1927 */
Adam Langleyd0592972015-03-30 14:49:51 -07001928 if (options.pid_file != NULL && !debug_flag) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001929 FILE *f = fopen(options.pid_file, "w");
1930
1931 if (f == NULL) {
1932 error("Couldn't create pid file \"%s\": %s",
1933 options.pid_file, strerror(errno));
1934 } else {
1935 fprintf(f, "%ld\n", (long) getpid());
1936 fclose(f);
1937 }
1938 }
1939
1940 /* Accept a connection and return in a forked child */
1941 server_accept_loop(&sock_in, &sock_out,
1942 &newsock, config_s);
1943 }
1944
1945 /* This is the child processing a new connection. */
1946 setproctitle("%s", "[accepted]");
1947
1948 /*
1949 * Create a new session and process group since the 4.4BSD
1950 * setlogin() affects the entire process group. We don't
1951 * want the child to be able to affect the parent.
1952 */
1953#if !defined(SSHD_ACQUIRES_CTTY)
1954 /*
1955 * If setsid is called, on some platforms sshd will later acquire a
1956 * controlling terminal which will result in "could not set
1957 * controlling tty" errors.
1958 */
1959 if (!debug_flag && !inetd_flag && setsid() < 0)
1960 error("setsid: %.100s", strerror(errno));
1961#endif
1962
1963 if (rexec_flag) {
1964 int fd;
1965
1966 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1967 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1968 dup2(newsock, STDIN_FILENO);
1969 dup2(STDIN_FILENO, STDOUT_FILENO);
1970 if (startup_pipe == -1)
1971 close(REEXEC_STARTUP_PIPE_FD);
Adam Langleyd0592972015-03-30 14:49:51 -07001972 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001973 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
Adam Langleyd0592972015-03-30 14:49:51 -07001974 close(startup_pipe);
1975 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1976 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001977
1978 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1979 close(config_s[1]);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001980
1981 execv(rexec_argv[0], rexec_argv);
1982
1983 /* Reexec has failed, fall back and continue */
1984 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1985 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1986 log_init(__progname, options.log_level,
1987 options.log_facility, log_stderr);
1988
1989 /* Clean up fds */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001990 close(REEXEC_CONFIG_PASS_FD);
1991 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1992 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1993 dup2(fd, STDIN_FILENO);
1994 dup2(fd, STDOUT_FILENO);
1995 if (fd > STDERR_FILENO)
1996 close(fd);
1997 }
1998 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1999 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2000 }
2001
2002 /* Executed child processes don't need these. */
2003 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2004 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2005
2006 /*
2007 * Disable the key regeneration alarm. We will not regenerate the
2008 * key since we are no longer in a position to give it to anyone. We
2009 * will not restart on SIGHUP since it no longer makes sense.
2010 */
2011 alarm(0);
2012 signal(SIGALRM, SIG_DFL);
2013 signal(SIGHUP, SIG_DFL);
2014 signal(SIGTERM, SIG_DFL);
2015 signal(SIGQUIT, SIG_DFL);
2016 signal(SIGCHLD, SIG_DFL);
2017 signal(SIGINT, SIG_DFL);
2018
2019 /*
2020 * Register our connection. This turns encryption off because we do
2021 * not have a key.
2022 */
2023 packet_set_connection(sock_in, sock_out);
2024 packet_set_server();
Greg Hartman9768ca42017-06-22 20:49:52 -07002025 ssh = active_state; /* XXX */
2026 check_ip_options(ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002027
2028 /* Set SO_KEEPALIVE if requested. */
2029 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2030 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2031 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2032
Greg Hartman9768ca42017-06-22 20:49:52 -07002033 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2034 debug("ssh_remote_port failed");
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002035 cleanup_exit(255);
2036 }
2037
2038 /*
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002039 * The rest of the code depends on the fact that
Greg Hartman9768ca42017-06-22 20:49:52 -07002040 * ssh_remote_ipaddr() caches the remote ip, even if
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002041 * the socket goes away.
2042 */
Greg Hartman9768ca42017-06-22 20:49:52 -07002043 remote_ip = ssh_remote_ipaddr(ssh);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002044
2045#ifdef SSH_AUDIT_EVENTS
2046 audit_connection_from(remote_ip, remote_port);
2047#endif
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002048
2049 /* Log the connection. */
Greg Hartmanccacbc92016-02-03 09:59:44 -08002050 laddr = get_local_ipaddr(sock_in);
Adam Langleyd0592972015-03-30 14:49:51 -07002051 verbose("Connection from %s port %d on %s port %d",
Greg Hartman9768ca42017-06-22 20:49:52 -07002052 remote_ip, remote_port, laddr, ssh_local_port(ssh));
Greg Hartmanccacbc92016-02-03 09:59:44 -08002053 free(laddr);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002054
2055 /*
2056 * We don't want to listen forever unless the other side
2057 * successfully authenticates itself. So we set up an alarm which is
2058 * cleared after successful authentication. A limit of zero
2059 * indicates no limit. Note that we don't set the alarm in debugging
2060 * mode; it is just annoying to have the server exit just when you
2061 * are about to discover the bug.
2062 */
2063 signal(SIGALRM, grace_alarm_handler);
2064 if (!debug_flag)
2065 alarm(options.login_grace_time);
2066
Greg Hartman9768ca42017-06-22 20:49:52 -07002067 sshd_exchange_identification(ssh, sock_in, sock_out);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002068 packet_set_nonblocking();
2069
2070 /* allocate authentication context */
2071 authctxt = xcalloc(1, sizeof(*authctxt));
2072
2073 authctxt->loginmsg = &loginmsg;
2074
2075 /* XXX global for cleanup, access from other modules */
2076 the_authctxt = authctxt;
2077
2078 /* prepare buffer to collect messages to display to user after login */
2079 buffer_init(&loginmsg);
2080 auth_debug_reset();
2081
Adam Langleyd0592972015-03-30 14:49:51 -07002082 if (use_privsep) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002083 if (privsep_preauth(authctxt) == 1)
2084 goto authenticated;
Greg Hartman9768ca42017-06-22 20:49:52 -07002085 } else if (have_agent) {
Adam Langleyd0592972015-03-30 14:49:51 -07002086 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2087 error("Unable to get agent socket: %s", ssh_err(r));
2088 have_agent = 0;
2089 }
2090 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002091
2092 /* perform the key exchange */
2093 /* authenticate user and start session */
Greg Hartman9768ca42017-06-22 20:49:52 -07002094 do_ssh2_kex();
2095 do_authentication2(authctxt);
2096
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002097 /*
2098 * If we use privilege separation, the unprivileged child transfers
2099 * the current keystate and exits
2100 */
2101 if (use_privsep) {
2102 mm_send_keystate(pmonitor);
2103 exit(0);
2104 }
2105
2106 authenticated:
2107 /*
2108 * Cancel the alarm we set to limit the time taken for
2109 * authentication.
2110 */
2111 alarm(0);
2112 signal(SIGALRM, SIG_DFL);
2113 authctxt->authenticated = 1;
2114 if (startup_pipe != -1) {
2115 close(startup_pipe);
2116 startup_pipe = -1;
2117 }
2118
2119#ifdef SSH_AUDIT_EVENTS
2120 audit_event(SSH_AUTH_SUCCESS);
2121#endif
2122
2123#ifdef GSSAPI
2124 if (options.gss_authentication) {
2125 temporarily_use_uid(authctxt->pw);
2126 ssh_gssapi_storecreds();
2127 restore_uid();
2128 }
2129#endif
2130#ifdef USE_PAM
2131 if (options.use_pam) {
2132 do_pam_setcred(1);
2133 do_pam_session();
2134 }
2135#endif
2136
2137 /*
2138 * In privilege separation, we fork another child and prepare
2139 * file descriptor passing.
2140 */
2141 if (use_privsep) {
2142 privsep_postauth(authctxt);
2143 /* the monitor process [priv] will not return */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002144 }
2145
2146 packet_set_timeout(options.client_alive_interval,
2147 options.client_alive_count_max);
2148
Adam Langleyd0592972015-03-30 14:49:51 -07002149 /* Try to send all our hostkeys to the client */
Greg Hartman9768ca42017-06-22 20:49:52 -07002150 notify_hostkeys(active_state);
Adam Langleyd0592972015-03-30 14:49:51 -07002151
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002152 /* Start session. */
2153 do_authenticated(authctxt);
2154
2155 /* The connection has been terminated. */
Adam Langleyd0592972015-03-30 14:49:51 -07002156 packet_get_bytes(&ibytes, &obytes);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002157 verbose("Transferred: sent %llu, received %llu bytes",
2158 (unsigned long long)obytes, (unsigned long long)ibytes);
2159
2160 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2161
2162#ifdef USE_PAM
2163 if (options.use_pam)
2164 finish_pam();
2165#endif /* USE_PAM */
2166
2167#ifdef SSH_AUDIT_EVENTS
2168 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2169#endif
2170
2171 packet_close();
2172
2173 if (use_privsep)
2174 mm_terminate();
2175
2176 exit(0);
2177}
2178
Adam Langleyd0592972015-03-30 14:49:51 -07002179int
2180sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
Greg Hartman9768ca42017-06-22 20:49:52 -07002181 const u_char *data, size_t dlen, const char *alg, u_int flag)
Adam Langleyd0592972015-03-30 14:49:51 -07002182{
2183 int r;
2184 u_int xxx_slen, xxx_dlen = dlen;
2185
2186 if (privkey) {
Greg Hartman9768ca42017-06-22 20:49:52 -07002187 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
2188 alg) < 0))
Adam Langleyd0592972015-03-30 14:49:51 -07002189 fatal("%s: key_sign failed", __func__);
2190 if (slen)
2191 *slen = xxx_slen;
2192 } else if (use_privsep) {
Greg Hartman9768ca42017-06-22 20:49:52 -07002193 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
2194 alg) < 0)
Adam Langleyd0592972015-03-30 14:49:51 -07002195 fatal("%s: pubkey_sign failed", __func__);
2196 if (slen)
2197 *slen = xxx_slen;
2198 } else {
2199 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
Greg Hartman9768ca42017-06-22 20:49:52 -07002200 data, dlen, alg, datafellows)) != 0)
Adam Langleyd0592972015-03-30 14:49:51 -07002201 fatal("%s: ssh_agent_sign failed: %s",
2202 __func__, ssh_err(r));
2203 }
2204 return 0;
2205}
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002206
Greg Hartmanccacbc92016-02-03 09:59:44 -08002207/* SSH2 key exchange */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002208static void
2209do_ssh2_kex(void)
2210{
Adam Langleyd0592972015-03-30 14:49:51 -07002211 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2212 struct kex *kex;
2213 int r;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002214
Greg Hartmanccacbc92016-02-03 09:59:44 -08002215 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2216 options.kex_algorithms);
2217 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2218 options.ciphers);
2219 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2220 options.ciphers);
2221 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2222 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002223
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002224 if (options.compression == COMP_NONE) {
2225 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
Greg Hartman9768ca42017-06-22 20:49:52 -07002226 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002227 }
Adam Langleyd0592972015-03-30 14:49:51 -07002228
2229 if (options.rekey_limit || options.rekey_interval)
Greg Hartman9768ca42017-06-22 20:49:52 -07002230 packet_set_rekey_limits(options.rekey_limit,
2231 options.rekey_interval);
Adam Langleyd0592972015-03-30 14:49:51 -07002232
2233 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2234 list_hostkey_types());
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002235
2236 /* start key exchange */
Adam Langleyd0592972015-03-30 14:49:51 -07002237 if ((r = kex_setup(active_state, myproposal)) != 0)
2238 fatal("kex_setup: %s", ssh_err(r));
2239 kex = active_state->kex;
2240#ifdef WITH_OPENSSL
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002241 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2242 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
Greg Hartman9768ca42017-06-22 20:49:52 -07002243 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2244 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2245 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002246 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2247 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
Adam Langleyd0592972015-03-30 14:49:51 -07002248# ifdef OPENSSL_HAS_ECC
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002249 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
Adam Langleyd0592972015-03-30 14:49:51 -07002250# endif
2251#endif
2252 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002253 kex->server = 1;
2254 kex->client_version_string=client_version_string;
2255 kex->server_version_string=server_version_string;
2256 kex->load_host_public_key=&get_hostkey_public_by_type;
2257 kex->load_host_private_key=&get_hostkey_private_by_type;
2258 kex->host_key_index=&get_hostkey_index;
Adam Langleyd0592972015-03-30 14:49:51 -07002259 kex->sign = sshd_hostkey_sign;
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002260
Adam Langleyd0592972015-03-30 14:49:51 -07002261 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002262
2263 session_id2 = kex->session_id;
2264 session_id2_len = kex->session_id_len;
2265
2266#ifdef DEBUG_KEXDH
2267 /* send 1st encrypted/maced/compressed message */
2268 packet_start(SSH2_MSG_IGNORE);
2269 packet_put_cstring("markus");
2270 packet_send();
2271 packet_write_wait();
2272#endif
2273 debug("KEX done");
2274}
2275
2276/* server specific fatal cleanup */
2277void
2278cleanup_exit(int i)
2279{
Adam Langleyd0592972015-03-30 14:49:51 -07002280 if (the_authctxt) {
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002281 do_cleanup(the_authctxt);
Adam Langleyd0592972015-03-30 14:49:51 -07002282 if (use_privsep && privsep_is_preauth &&
2283 pmonitor != NULL && pmonitor->m_pid > 1) {
2284 debug("Killing privsep child %d", pmonitor->m_pid);
2285 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2286 errno != ESRCH)
2287 error("%s: kill(%d): %s", __func__,
2288 pmonitor->m_pid, strerror(errno));
2289 }
2290 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002291#ifdef SSH_AUDIT_EVENTS
2292 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2293 if (!use_privsep || mm_is_monitor())
2294 audit_event(SSH_CONNECTION_ABANDON);
2295#endif
2296 _exit(i);
2297}