xref: /freebsd/crypto/openssh/sshd-session.c (revision 8e28d84935f2f0ee081d44f9803f3052b960e50b)
1 /* $OpenBSD: sshd-session.c,v 1.12 2025/03/12 22:43:44 djm Exp $ */
2 /*
3  * SSH2 implementation:
4  * Privilege Separation:
5  *
6  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
7  * Copyright (c) 2002 Niels Provos.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "includes.h"
31 
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
40 #endif
41 #include "openbsd-compat/sys-tree.h"
42 #include "openbsd-compat/sys-queue.h"
43 #include <sys/wait.h>
44 
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <netdb.h>
48 #ifdef HAVE_PATHS_H
49 # include <paths.h>
50 #endif
51 #include <pwd.h>
52 #include <grp.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <stdarg.h>
58 #include <unistd.h>
59 #include <limits.h>
60 
61 #ifdef WITH_OPENSSL
62 #include <openssl/bn.h>
63 #include <openssl/evp.h>
64 #include <openssl/rand.h>
65 #include "openbsd-compat/openssl-compat.h"
66 #endif
67 
68 #ifdef HAVE_SECUREWARE
69 #include <sys/security.h>
70 #include <prot.h>
71 #endif
72 
73 #include "xmalloc.h"
74 #include "ssh.h"
75 #include "ssh2.h"
76 #include "sshpty.h"
77 #include "packet.h"
78 #include "log.h"
79 #include "sshbuf.h"
80 #include "misc.h"
81 #include "match.h"
82 #include "servconf.h"
83 #include "uidswap.h"
84 #include "compat.h"
85 #include "cipher.h"
86 #include "digest.h"
87 #include "sshkey.h"
88 #include "kex.h"
89 #include "authfile.h"
90 #include "pathnames.h"
91 #include "atomicio.h"
92 #include "canohost.h"
93 #include "hostfile.h"
94 #include "auth.h"
95 #include "authfd.h"
96 #include "msg.h"
97 #include "dispatch.h"
98 #include "channels.h"
99 #include "session.h"
100 #include "monitor.h"
101 #ifdef GSSAPI
102 #include "ssh-gss.h"
103 #endif
104 #include "monitor_wrap.h"
105 #include "auth-options.h"
106 #include "version.h"
107 #include "ssherr.h"
108 #include "sk-api.h"
109 #include "srclimit.h"
110 #include "dh.h"
111 #include "blacklist_client.h"
112 
113 /* Re-exec fds */
114 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
115 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 2)
116 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 3)
117 
118 /* Privsep fds */
119 #define PRIVSEP_MONITOR_FD		(STDERR_FILENO + 1)
120 #define PRIVSEP_LOG_FD			(STDERR_FILENO + 2)
121 #define PRIVSEP_MIN_FREE_FD		(STDERR_FILENO + 3)
122 
123 extern char *__progname;
124 
125 /* Server configuration options. */
126 ServerOptions options;
127 
128 /* Name of the server configuration file. */
129 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
130 
131 /*
132  * Debug mode flag.  This can be set on the command line.  If debug
133  * mode is enabled, extra debugging output will be sent to the system
134  * log, the daemon will not go to background, and will exit after processing
135  * the first connection.
136  */
137 int debug_flag = 0;
138 
139 /* Flag indicating that the daemon is being started from inetd. */
140 static int inetd_flag = 0;
141 
142 /* debug goes to stderr unless inetd_flag is set */
143 static int log_stderr = 0;
144 
145 /* Saved arguments to main(). */
146 static char **saved_argv;
147 static int saved_argc;
148 
149 /* Daemon's agent connection */
150 int auth_sock = -1;
151 static int have_agent = 0;
152 
153 /*
154  * Any really sensitive data in the application is contained in this
155  * structure. The idea is that this structure could be locked into memory so
156  * that the pages do not get written into swap.  However, there are some
157  * problems. The private key contains BIGNUMs, and we do not (in principle)
158  * have access to the internals of them, and locking just the structure is
159  * not very useful.  Currently, memory locking is not implemented.
160  */
161 struct {
162 	u_int		num_hostkeys;
163 	struct sshkey	**host_keys;		/* all private host keys */
164 	struct sshkey	**host_pubkeys;		/* all public host keys */
165 	struct sshkey	**host_certificates;	/* all public host certificates */
166 } sensitive_data;
167 
168 /* record remote hostname or ip */
169 u_int utmp_len = HOST_NAME_MAX+1;
170 
171 static int startup_pipe = -1;		/* in child */
172 
173 /* variables used for privilege separation */
174 struct monitor *pmonitor = NULL;
175 int privsep_is_preauth = 1;
176 static int privsep_chroot = 1;
177 
178 /* Unprivileged user */
179 struct passwd *privsep_pw = NULL;
180 
181 /* global connection state and authentication contexts */
182 Authctxt *the_authctxt = NULL;
183 struct ssh *the_active_state;
184 
185 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
186 struct sshauthopt *auth_opts = NULL;
187 
188 /* sshd_config buffer */
189 struct sshbuf *cfg;
190 
191 /* Included files from the configuration file */
192 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
193 
194 /* message to be displayed after login */
195 struct sshbuf *loginmsg;
196 
197 /* Prototypes for various functions defined later in this file. */
198 void destroy_sensitive_data(void);
199 void demote_sensitive_data(void);
200 
201 /* XXX reduce to stub once postauth split */
202 int
mm_is_monitor(void)203 mm_is_monitor(void)
204 {
205 	/*
206 	 * m_pid is only set in the privileged part, and
207 	 * points to the unprivileged child.
208 	 */
209 	return (pmonitor && pmonitor->m_pid > 0);
210 }
211 
212 /*
213  * Signal handler for the alarm after the login grace period has expired.
214  * As usual, this may only take signal-safe actions, even though it is
215  * terminal.
216  */
217 static void
grace_alarm_handler(int sig)218 grace_alarm_handler(int sig)
219 {
220 	/*
221 	 * Try to kill any processes that we have spawned, E.g. authorized
222 	 * keys command helpers or privsep children.
223 	 */
224 	if (getpgid(0) == getpid()) {
225 		struct sigaction sa;
226 
227 		/* mask all other signals while in handler */
228 		memset(&sa, 0, sizeof(sa));
229 		sa.sa_handler = SIG_IGN;
230 		sigfillset(&sa.sa_mask);
231 #if defined(SA_RESTART)
232 		sa.sa_flags = SA_RESTART;
233 #endif
234 		(void)sigaction(SIGTERM, &sa, NULL);
235 		kill(0, SIGTERM);
236 	}
237 	_exit(EXIT_LOGIN_GRACE);
238 }
239 
240 /* Destroy the host and server keys.  They will no longer be needed. */
241 void
destroy_sensitive_data(void)242 destroy_sensitive_data(void)
243 {
244 	u_int i;
245 
246 	for (i = 0; i < options.num_host_key_files; i++) {
247 		if (sensitive_data.host_keys[i]) {
248 			sshkey_free(sensitive_data.host_keys[i]);
249 			sensitive_data.host_keys[i] = NULL;
250 		}
251 		if (sensitive_data.host_certificates[i]) {
252 			sshkey_free(sensitive_data.host_certificates[i]);
253 			sensitive_data.host_certificates[i] = NULL;
254 		}
255 	}
256 }
257 
258 /* Demote private to public keys for network child */
259 void
demote_sensitive_data(void)260 demote_sensitive_data(void)
261 {
262 	struct sshkey *tmp;
263 	u_int i;
264 	int r;
265 
266 	for (i = 0; i < options.num_host_key_files; i++) {
267 		if (sensitive_data.host_keys[i]) {
268 			if ((r = sshkey_from_private(
269 			    sensitive_data.host_keys[i], &tmp)) != 0)
270 				fatal_r(r, "could not demote host %s key",
271 				    sshkey_type(sensitive_data.host_keys[i]));
272 			sshkey_free(sensitive_data.host_keys[i]);
273 			sensitive_data.host_keys[i] = tmp;
274 		}
275 		/* Certs do not need demotion */
276 	}
277 }
278 
279 static void
reseed_prngs(void)280 reseed_prngs(void)
281 {
282 	u_int32_t rnd[256];
283 
284 #ifdef WITH_OPENSSL
285 	RAND_poll();
286 #endif
287 	arc4random_stir(); /* noop on recent arc4random() implementations */
288 	arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
289 
290 #ifdef WITH_OPENSSL
291 	RAND_seed(rnd, sizeof(rnd));
292 	/* give libcrypto a chance to notice the PID change */
293 	if ((RAND_bytes((u_char *)rnd, 1)) != 1)
294 		fatal("%s: RAND_bytes failed", __func__);
295 #endif
296 
297 	explicit_bzero(rnd, sizeof(rnd));
298 }
299 
300 struct sshbuf *
pack_hostkeys(void)301 pack_hostkeys(void)
302 {
303 	struct sshbuf *keybuf = NULL, *hostkeys = NULL;
304 	int r;
305 	u_int i;
306 
307 	if ((hostkeys = sshbuf_new()) == NULL)
308 		fatal_f("sshbuf_new failed");
309 
310 	/* pack hostkeys into a string. Empty key slots get empty strings */
311 	for (i = 0; i < options.num_host_key_files; i++) {
312 		/* public key */
313 		if (sensitive_data.host_pubkeys[i] != NULL) {
314 			if ((r = sshkey_puts(sensitive_data.host_pubkeys[i],
315 			    hostkeys)) != 0)
316 				fatal_fr(r, "compose hostkey public");
317 		} else {
318 			if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
319 				fatal_fr(r, "compose hostkey empty public");
320 		}
321 		/* cert */
322 		if (sensitive_data.host_certificates[i] != NULL) {
323 			if ((r = sshkey_puts(
324 			    sensitive_data.host_certificates[i],
325 			    hostkeys)) != 0)
326 				fatal_fr(r, "compose host cert");
327 		} else {
328 			if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
329 				fatal_fr(r, "compose host cert empty");
330 		}
331 	}
332 
333 	sshbuf_free(keybuf);
334 	return hostkeys;
335 }
336 
337 static int
privsep_preauth(struct ssh * ssh)338 privsep_preauth(struct ssh *ssh)
339 {
340 	int status, r;
341 	pid_t pid;
342 
343 	/* Set up unprivileged child process to deal with network data */
344 	pmonitor = monitor_init();
345 	/* Store a pointer to the kex for later rekeying */
346 	pmonitor->m_pkex = &ssh->kex;
347 
348 	if ((pid = fork()) == -1)
349 		fatal("fork of unprivileged child failed");
350 	else if (pid != 0) {
351 		debug2("Network child is on pid %ld", (long)pid);
352 
353 		pmonitor->m_pid = pid;
354 		if (have_agent) {
355 			r = ssh_get_authentication_socket(&auth_sock);
356 			if (r != 0) {
357 				error_r(r, "Could not get agent socket");
358 				have_agent = 0;
359 			}
360 		}
361 		monitor_child_preauth(ssh, pmonitor);
362 
363 		/* Wait for the child's exit status */
364 		while (waitpid(pid, &status, 0) == -1) {
365 			if (errno == EINTR)
366 				continue;
367 			pmonitor->m_pid = -1;
368 			fatal_f("waitpid: %s", strerror(errno));
369 		}
370 		privsep_is_preauth = 0;
371 		pmonitor->m_pid = -1;
372 		if (WIFEXITED(status)) {
373 			if (WEXITSTATUS(status) != 0)
374 				fatal_f("preauth child exited with status %d",
375 				    WEXITSTATUS(status));
376 		} else if (WIFSIGNALED(status))
377 			fatal_f("preauth child terminated by signal %d",
378 			    WTERMSIG(status));
379 		return 1;
380 	} else {
381 		/* child */
382 		close(pmonitor->m_sendfd);
383 		close(pmonitor->m_log_recvfd);
384 
385 		/*
386 		 * Arrange unpriv-preauth child process fds:
387 		 * 0, 1 network socket
388 		 * 2 optional stderr
389 		 * 3 reserved
390 		 * 4 monitor message socket
391 		 * 5 monitor logging socket
392 		 *
393 		 * We know that the monitor sockets will have fds > 4 because
394 		 * of the reserved fds in main()
395 		 */
396 
397 		if (ssh_packet_get_connection_in(ssh) != STDIN_FILENO &&
398 		    dup2(ssh_packet_get_connection_in(ssh), STDIN_FILENO) == -1)
399 			fatal("dup2 stdin failed: %s", strerror(errno));
400 		if (ssh_packet_get_connection_out(ssh) != STDOUT_FILENO &&
401 		    dup2(ssh_packet_get_connection_out(ssh),
402 		    STDOUT_FILENO) == -1)
403 			fatal("dup2 stdout failed: %s", strerror(errno));
404 		/* leave stderr as-is */
405 		log_redirect_stderr_to(NULL); /* dup can clobber log fd */
406 		if (pmonitor->m_recvfd != PRIVSEP_MONITOR_FD &&
407 		    dup2(pmonitor->m_recvfd, PRIVSEP_MONITOR_FD) == -1)
408 			fatal("dup2 monitor fd: %s", strerror(errno));
409 		if (pmonitor->m_log_sendfd != PRIVSEP_LOG_FD &&
410 		    dup2(pmonitor->m_log_sendfd, PRIVSEP_LOG_FD) == -1)
411 			fatal("dup2 log fd: %s", strerror(errno));
412 		closefrom(PRIVSEP_MIN_FREE_FD);
413 
414 		saved_argv[0] = options.sshd_auth_path;
415 		execv(options.sshd_auth_path, saved_argv);
416 
417 		fatal_f("exec of %s failed: %s",
418 		    options.sshd_auth_path, strerror(errno));
419 	}
420 }
421 
422 static void
privsep_postauth(struct ssh * ssh,Authctxt * authctxt)423 privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
424 {
425 	int skip_privdrop = 0;
426 
427 	/*
428 	 * Hack for systems that don't support FD passing: retain privileges
429 	 * in the post-auth privsep process so it can allocate PTYs directly.
430 	 * This is basically equivalent to what we did <= 9.7, which was to
431 	 * disable post-auth privsep entriely.
432 	 * Cygwin doesn't need to drop privs here although it doesn't support
433 	 * fd passing, as AFAIK PTY allocation on this platform doesn't require
434 	 * special privileges to begin with.
435 	 */
436 #if defined(DISABLE_FD_PASSING) && !defined(HAVE_CYGWIN)
437 	skip_privdrop = 1;
438 #endif
439 
440 	/* New socket pair */
441 	monitor_reinit(pmonitor);
442 
443 	pmonitor->m_pid = fork();
444 	if (pmonitor->m_pid == -1)
445 		fatal("fork of unprivileged child failed");
446 	else if (pmonitor->m_pid != 0) {
447 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
448 		sshbuf_reset(loginmsg);
449 		monitor_clear_keystate(ssh, pmonitor);
450 		monitor_child_postauth(ssh, pmonitor);
451 
452 		/* NEVERREACHED */
453 		exit(0);
454 	}
455 
456 	/* child */
457 
458 	close(pmonitor->m_sendfd);
459 	pmonitor->m_sendfd = -1;
460 
461 	/* Demote the private keys to public keys. */
462 	demote_sensitive_data();
463 
464 	reseed_prngs();
465 
466 	/* Drop privileges */
467 	if (!skip_privdrop)
468 		do_setusercontext(authctxt->pw);
469 
470 	/* It is safe now to apply the key state */
471 	monitor_apply_keystate(ssh, pmonitor);
472 
473 	/*
474 	 * Tell the packet layer that authentication was successful, since
475 	 * this information is not part of the key state.
476 	 */
477 	ssh_packet_set_authenticated(ssh);
478 }
479 
480 static struct sshkey *
get_hostkey_by_type(int type,int nid,int need_private,struct ssh * ssh)481 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
482 {
483 	u_int i;
484 	struct sshkey *key;
485 
486 	for (i = 0; i < options.num_host_key_files; i++) {
487 		switch (type) {
488 		case KEY_RSA_CERT:
489 		case KEY_DSA_CERT:
490 		case KEY_ECDSA_CERT:
491 		case KEY_ED25519_CERT:
492 		case KEY_ECDSA_SK_CERT:
493 		case KEY_ED25519_SK_CERT:
494 		case KEY_XMSS_CERT:
495 			key = sensitive_data.host_certificates[i];
496 			break;
497 		default:
498 			key = sensitive_data.host_keys[i];
499 			if (key == NULL && !need_private)
500 				key = sensitive_data.host_pubkeys[i];
501 			break;
502 		}
503 		if (key == NULL || key->type != type)
504 			continue;
505 		switch (type) {
506 		case KEY_ECDSA:
507 		case KEY_ECDSA_SK:
508 		case KEY_ECDSA_CERT:
509 		case KEY_ECDSA_SK_CERT:
510 			if (key->ecdsa_nid != nid)
511 				continue;
512 			/* FALLTHROUGH */
513 		default:
514 			return need_private ?
515 			    sensitive_data.host_keys[i] : key;
516 		}
517 	}
518 	return NULL;
519 }
520 
521 struct sshkey *
get_hostkey_public_by_type(int type,int nid,struct ssh * ssh)522 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
523 {
524 	return get_hostkey_by_type(type, nid, 0, ssh);
525 }
526 
527 struct sshkey *
get_hostkey_private_by_type(int type,int nid,struct ssh * ssh)528 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
529 {
530 	return get_hostkey_by_type(type, nid, 1, ssh);
531 }
532 
533 struct sshkey *
get_hostkey_by_index(int ind)534 get_hostkey_by_index(int ind)
535 {
536 	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
537 		return (NULL);
538 	return (sensitive_data.host_keys[ind]);
539 }
540 
541 struct sshkey *
get_hostkey_public_by_index(int ind,struct ssh * ssh)542 get_hostkey_public_by_index(int ind, struct ssh *ssh)
543 {
544 	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
545 		return (NULL);
546 	return (sensitive_data.host_pubkeys[ind]);
547 }
548 
549 int
get_hostkey_index(struct sshkey * key,int compare,struct ssh * ssh)550 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
551 {
552 	u_int i;
553 
554 	for (i = 0; i < options.num_host_key_files; i++) {
555 		if (sshkey_is_cert(key)) {
556 			if (key == sensitive_data.host_certificates[i] ||
557 			    (compare && sensitive_data.host_certificates[i] &&
558 			    sshkey_equal(key,
559 			    sensitive_data.host_certificates[i])))
560 				return (i);
561 		} else {
562 			if (key == sensitive_data.host_keys[i] ||
563 			    (compare && sensitive_data.host_keys[i] &&
564 			    sshkey_equal(key, sensitive_data.host_keys[i])))
565 				return (i);
566 			if (key == sensitive_data.host_pubkeys[i] ||
567 			    (compare && sensitive_data.host_pubkeys[i] &&
568 			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
569 				return (i);
570 		}
571 	}
572 	return (-1);
573 }
574 
575 /* Inform the client of all hostkeys */
576 static void
notify_hostkeys(struct ssh * ssh)577 notify_hostkeys(struct ssh *ssh)
578 {
579 	struct sshbuf *buf;
580 	struct sshkey *key;
581 	u_int i, nkeys;
582 	int r;
583 	char *fp;
584 
585 	/* Some clients cannot cope with the hostkeys message, skip those. */
586 	if (ssh->compat & SSH_BUG_HOSTKEYS)
587 		return;
588 
589 	if ((buf = sshbuf_new()) == NULL)
590 		fatal_f("sshbuf_new");
591 	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
592 		key = get_hostkey_public_by_index(i, ssh);
593 		if (key == NULL || key->type == KEY_UNSPEC ||
594 		    sshkey_is_cert(key))
595 			continue;
596 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
597 		    SSH_FP_DEFAULT);
598 		debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp);
599 		free(fp);
600 		if (nkeys == 0) {
601 			/*
602 			 * Start building the request when we find the
603 			 * first usable key.
604 			 */
605 			if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
606 			    (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
607 			    (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
608 				sshpkt_fatal(ssh, r, "%s: start request", __func__);
609 		}
610 		/* Append the key to the request */
611 		sshbuf_reset(buf);
612 		if ((r = sshkey_putb(key, buf)) != 0)
613 			fatal_fr(r, "couldn't put hostkey %d", i);
614 		if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
615 			sshpkt_fatal(ssh, r, "%s: append key", __func__);
616 		nkeys++;
617 	}
618 	debug3_f("sent %u hostkeys", nkeys);
619 	if (nkeys == 0)
620 		fatal_f("no hostkeys");
621 	if ((r = sshpkt_send(ssh)) != 0)
622 		sshpkt_fatal(ssh, r, "%s: send", __func__);
623 	sshbuf_free(buf);
624 }
625 
626 static void
usage(void)627 usage(void)
628 {
629 	fprintf(stderr, "%s, %s\n", SSH_RELEASE, SSH_OPENSSL_VERSION);
630 	fprintf(stderr,
631 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
632 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
633 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
634 	);
635 	exit(1);
636 }
637 
638 static void
parse_hostkeys(struct sshbuf * hostkeys)639 parse_hostkeys(struct sshbuf *hostkeys)
640 {
641 	int r;
642 	u_int num_keys = 0;
643 	struct sshkey *k;
644 	struct sshbuf *kbuf;
645 	const u_char *cp;
646 	size_t len;
647 
648 	while (sshbuf_len(hostkeys) != 0) {
649 		if (num_keys > 2048)
650 			fatal_f("too many hostkeys");
651 		sensitive_data.host_keys = xrecallocarray(
652 		    sensitive_data.host_keys, num_keys, num_keys + 1,
653 		    sizeof(*sensitive_data.host_pubkeys));
654 		sensitive_data.host_pubkeys = xrecallocarray(
655 		    sensitive_data.host_pubkeys, num_keys, num_keys + 1,
656 		    sizeof(*sensitive_data.host_pubkeys));
657 		sensitive_data.host_certificates = xrecallocarray(
658 		    sensitive_data.host_certificates, num_keys, num_keys + 1,
659 		    sizeof(*sensitive_data.host_certificates));
660 		/* private key */
661 		k = NULL;
662 		if ((r = sshbuf_froms(hostkeys, &kbuf)) != 0)
663 			fatal_fr(r, "extract privkey");
664 		if (sshbuf_len(kbuf) != 0 &&
665 		    (r = sshkey_private_deserialize(kbuf, &k)) != 0)
666 			fatal_fr(r, "parse pubkey");
667 		sensitive_data.host_keys[num_keys] = k;
668 		sshbuf_free(kbuf);
669 		if (k)
670 			debug2_f("privkey %u: %s", num_keys, sshkey_ssh_name(k));
671 		/* public key */
672 		k = NULL;
673 		if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
674 			fatal_fr(r, "extract pubkey");
675 		if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
676 			fatal_fr(r, "parse pubkey");
677 		sensitive_data.host_pubkeys[num_keys] = k;
678 		if (k)
679 			debug2_f("pubkey %u: %s", num_keys, sshkey_ssh_name(k));
680 		/* certificate */
681 		k = NULL;
682 		if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
683 			fatal_fr(r, "extract pubkey");
684 		if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
685 			fatal_fr(r, "parse pubkey");
686 		sensitive_data.host_certificates[num_keys] = k;
687 		if (k)
688 			debug2_f("cert %u: %s", num_keys, sshkey_ssh_name(k));
689 		num_keys++;
690 	}
691 	sensitive_data.num_hostkeys = num_keys;
692 }
693 
694 static void
recv_rexec_state(int fd,struct sshbuf * conf,uint64_t * timing_secretp)695 recv_rexec_state(int fd, struct sshbuf *conf, uint64_t *timing_secretp)
696 {
697 	struct sshbuf *m, *inc, *hostkeys;
698 	u_char *cp, ver;
699 	size_t len;
700 	int r;
701 	struct include_item *item;
702 
703 	debug3_f("entering fd = %d", fd);
704 
705 	if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
706 		fatal_f("sshbuf_new failed");
707 
708 	/* receive config */
709 	if (ssh_msg_recv(fd, m) == -1)
710 		fatal_f("ssh_msg_recv failed");
711 	if ((r = sshbuf_get_u8(m, &ver)) != 0)
712 		fatal_fr(r, "parse version");
713 	if (ver != 0)
714 		fatal_f("rexec version mismatch");
715 	if ((r = sshbuf_get_string(m, &cp, &len)) != 0 || /* XXX _direct */
716 	    (r = sshbuf_get_u64(m, timing_secretp)) != 0 ||
717 	    (r = sshbuf_get_stringb(m, inc)) != 0)
718 		fatal_fr(r, "parse config");
719 
720 	if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
721 		fatal_fr(r, "sshbuf_put");
722 
723 	while (sshbuf_len(inc) != 0) {
724 		item = xcalloc(1, sizeof(*item));
725 		if ((item->contents = sshbuf_new()) == NULL)
726 			fatal_f("sshbuf_new failed");
727 		if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
728 		    (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
729 		    (r = sshbuf_get_stringb(inc, item->contents)) != 0)
730 			fatal_fr(r, "parse includes");
731 		TAILQ_INSERT_TAIL(&includes, item, entry);
732 	}
733 
734 	/* receive hostkeys */
735 	sshbuf_reset(m);
736 	if (ssh_msg_recv(fd, m) == -1)
737 		fatal_f("ssh_msg_recv failed");
738 	if ((r = sshbuf_get_u8(m, NULL)) != 0 ||
739 	    (r = sshbuf_froms(m, &hostkeys)) != 0)
740 		fatal_fr(r, "parse config");
741 	parse_hostkeys(hostkeys);
742 
743 	free(cp);
744 	sshbuf_free(m);
745 	sshbuf_free(hostkeys);
746 	sshbuf_free(inc);
747 
748 	debug3_f("done");
749 }
750 
751 /*
752  * If IP options are supported, make sure there are none (log and
753  * return an error if any are found).  Basically we are worried about
754  * source routing; it can be used to pretend you are somebody
755  * (ip-address) you are not. That itself may be "almost acceptable"
756  * under certain circumstances, but rhosts authentication is useless
757  * if source routing is accepted. Notice also that if we just dropped
758  * source routing here, the other side could use IP spoofing to do
759  * rest of the interaction and could still bypass security.  So we
760  * exit here if we detect any IP options.
761  */
762 static void
check_ip_options(struct ssh * ssh)763 check_ip_options(struct ssh *ssh)
764 {
765 #ifdef IP_OPTIONS
766 	int sock_in = ssh_packet_get_connection_in(ssh);
767 	struct sockaddr_storage from;
768 	u_char opts[200];
769 	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
770 	char text[sizeof(opts) * 3 + 1];
771 
772 	memset(&from, 0, sizeof(from));
773 	if (getpeername(sock_in, (struct sockaddr *)&from,
774 	    &fromlen) == -1)
775 		return;
776 	if (from.ss_family != AF_INET)
777 		return;
778 	/* XXX IPv6 options? */
779 
780 	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
781 	    &option_size) >= 0 && option_size != 0) {
782 		text[0] = '\0';
783 		for (i = 0; i < option_size; i++)
784 			snprintf(text + i*3, sizeof(text) - i*3,
785 			    " %2.2x", opts[i]);
786 		fatal("Connection from %.100s port %d with IP opts: %.800s",
787 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
788 	}
789 #endif /* IP_OPTIONS */
790 }
791 
792 /* Set the routing domain for this process */
793 static void
set_process_rdomain(struct ssh * ssh,const char * name)794 set_process_rdomain(struct ssh *ssh, const char *name)
795 {
796 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
797 	if (name == NULL)
798 		return; /* default */
799 
800 	if (strcmp(name, "%D") == 0) {
801 		/* "expands" to routing domain of connection */
802 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
803 			return;
804 	}
805 	/* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
806 	return sys_set_process_rdomain(name);
807 #elif defined(__OpenBSD__)
808 	int rtable, ortable = getrtable();
809 	const char *errstr;
810 
811 	if (name == NULL)
812 		return; /* default */
813 
814 	if (strcmp(name, "%D") == 0) {
815 		/* "expands" to routing domain of connection */
816 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
817 			return;
818 	}
819 
820 	rtable = (int)strtonum(name, 0, 255, &errstr);
821 	if (errstr != NULL) /* Shouldn't happen */
822 		fatal("Invalid routing domain \"%s\": %s", name, errstr);
823 	if (rtable != ortable && setrtable(rtable) != 0)
824 		fatal("Unable to set routing domain %d: %s",
825 		    rtable, strerror(errno));
826 	debug_f("set routing domain %d (was %d)", rtable, ortable);
827 #else /* defined(__OpenBSD__) */
828 	fatal("Unable to set routing domain: not supported in this platform");
829 #endif
830 }
831 
832 /*
833  * Main program for the daemon.
834  */
835 int
main(int ac,char ** av)836 main(int ac, char **av)
837 {
838 	struct ssh *ssh = NULL;
839 	extern char *optarg;
840 	extern int optind;
841 	int devnull, r, opt, on = 1, remote_port;
842 	int sock_in = -1, sock_out = -1, rexeced_flag = 0, have_key = 0;
843 	const char *remote_ip, *rdomain;
844 	char *line, *laddr, *logfile = NULL;
845 	u_int i;
846 	u_int64_t ibytes, obytes;
847 	mode_t new_umask;
848 	Authctxt *authctxt;
849 	struct connection_info *connection_info = NULL;
850 	sigset_t sigmask;
851 	uint64_t timing_secret = 0;
852 	struct itimerval itv;
853 
854 	sigemptyset(&sigmask);
855 	sigprocmask(SIG_SETMASK, &sigmask, NULL);
856 
857 #ifdef HAVE_SECUREWARE
858 	(void)set_auth_parameters(ac, av);
859 #endif
860 	__progname = ssh_get_progname(av[0]);
861 
862 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
863 	saved_argc = ac;
864 	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
865 	for (i = 0; (int)i < ac; i++)
866 		saved_argv[i] = xstrdup(av[i]);
867 	saved_argv[i] = NULL;
868 
869 #ifndef HAVE_SETPROCTITLE
870 	/* Prepare for later setproctitle emulation */
871 	compat_init_setproctitle(ac, av);
872 	av = saved_argv;
873 #endif
874 
875 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
876 	sanitise_stdfd();
877 
878 	/* Initialize configuration options to their default values. */
879 	initialize_server_options(&options);
880 
881 	/* Parse command-line arguments. */
882 	while ((opt = getopt(ac, av,
883 	    "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
884 		switch (opt) {
885 		case '4':
886 			options.address_family = AF_INET;
887 			break;
888 		case '6':
889 			options.address_family = AF_INET6;
890 			break;
891 		case 'f':
892 			config_file_name = optarg;
893 			break;
894 		case 'c':
895 			servconf_add_hostcert("[command-line]", 0,
896 			    &options, optarg);
897 			break;
898 		case 'd':
899 			if (debug_flag == 0) {
900 				debug_flag = 1;
901 				options.log_level = SYSLOG_LEVEL_DEBUG1;
902 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
903 				options.log_level++;
904 			break;
905 		case 'D':
906 			/* ignore */
907 			break;
908 		case 'E':
909 			logfile = optarg;
910 			/* FALLTHROUGH */
911 		case 'e':
912 			log_stderr = 1;
913 			break;
914 		case 'i':
915 			inetd_flag = 1;
916 			break;
917 		case 'r':
918 			/* ignore */
919 			break;
920 		case 'R':
921 			rexeced_flag = 1;
922 			break;
923 		case 'Q':
924 			/* ignored */
925 			break;
926 		case 'q':
927 			options.log_level = SYSLOG_LEVEL_QUIET;
928 			break;
929 		case 'b':
930 			/* protocol 1, ignored */
931 			break;
932 		case 'p':
933 			options.ports_from_cmdline = 1;
934 			if (options.num_ports >= MAX_PORTS) {
935 				fprintf(stderr, "too many ports.\n");
936 				exit(1);
937 			}
938 			options.ports[options.num_ports++] = a2port(optarg);
939 			if (options.ports[options.num_ports-1] <= 0) {
940 				fprintf(stderr, "Bad port number.\n");
941 				exit(1);
942 			}
943 			break;
944 		case 'g':
945 			if ((options.login_grace_time = convtime(optarg)) == -1) {
946 				fprintf(stderr, "Invalid login grace time.\n");
947 				exit(1);
948 			}
949 			break;
950 		case 'k':
951 			/* protocol 1, ignored */
952 			break;
953 		case 'h':
954 			servconf_add_hostkey("[command-line]", 0,
955 			    &options, optarg, 1);
956 			break;
957 		case 't':
958 		case 'T':
959 		case 'G':
960 			fatal("test/dump modes not supported");
961 			break;
962 		case 'C':
963 			connection_info = server_get_connection_info(ssh, 0, 0);
964 			if (parse_server_match_testspec(connection_info,
965 			    optarg) == -1)
966 				exit(1);
967 			break;
968 		case 'u':
969 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
970 			if (utmp_len > HOST_NAME_MAX+1) {
971 				fprintf(stderr, "Invalid utmp length.\n");
972 				exit(1);
973 			}
974 			break;
975 		case 'o':
976 			line = xstrdup(optarg);
977 			if (process_server_config_line(&options, line,
978 			    "command-line", 0, NULL, NULL, &includes) != 0)
979 				exit(1);
980 			free(line);
981 			break;
982 		case 'V':
983 			fprintf(stderr, "%s, %s\n",
984 			    SSH_RELEASE, SSH_OPENSSL_VERSION);
985 			exit(0);
986 		default:
987 			usage();
988 			break;
989 		}
990 	}
991 
992 	/* Check that there are no remaining arguments. */
993 	if (optind < ac) {
994 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
995 		exit(1);
996 	}
997 
998 	if (!rexeced_flag)
999 		fatal("sshd-session should not be executed directly");
1000 
1001 	closefrom(REEXEC_MIN_FREE_FD);
1002 
1003 	platform_pre_session_start();
1004 
1005 	/* Reserve fds we'll need later for reexec things */
1006 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
1007 		fatal("open %s: %s", _PATH_DEVNULL, strerror(errno));
1008 	while (devnull < PRIVSEP_MIN_FREE_FD) {
1009 		if ((devnull = dup(devnull)) == -1)
1010 			fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno));
1011 	}
1012 
1013 	seed_rng();
1014 
1015 	/* If requested, redirect the logs to the specified logfile. */
1016 	if (logfile != NULL) {
1017 		char *cp, pid_s[32];
1018 
1019 		snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
1020 		cp = percent_expand(logfile,
1021 		    "p", pid_s,
1022 		    "P", "sshd-session",
1023 		    (char *)NULL);
1024 		log_redirect_stderr_to(cp);
1025 		free(cp);
1026 	}
1027 
1028 	/*
1029 	 * Force logging to stderr until we have loaded the private host
1030 	 * key (unless started from inetd)
1031 	 */
1032 	log_init(__progname,
1033 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1034 	    SYSLOG_LEVEL_INFO : options.log_level,
1035 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1036 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1037 	    log_stderr || !inetd_flag || debug_flag);
1038 
1039 	/* Fetch our configuration */
1040 	if ((cfg = sshbuf_new()) == NULL)
1041 		fatal("sshbuf_new config buf failed");
1042 	setproctitle("%s", "[rexeced]");
1043 	recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg, &timing_secret);
1044 	parse_server_config(&options, "rexec", cfg, &includes, NULL, 1);
1045 	/* Fill in default values for those options not explicitly set. */
1046 	fill_default_server_options(&options);
1047 	options.timing_secret = timing_secret;
1048 
1049 	/* Reinit logging in case config set Level, Facility or Verbose. */
1050 	log_init(__progname, options.log_level, options.log_facility,
1051 	    log_stderr || !inetd_flag || debug_flag);
1052 
1053 	debug("sshd-session version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1054 
1055 	/* Store privilege separation user for later use if required. */
1056 	privsep_chroot = (getuid() == 0 || geteuid() == 0);
1057 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1058 		if (privsep_chroot || options.kerberos_authentication)
1059 			fatal("Privilege separation user %s does not exist",
1060 			    SSH_PRIVSEP_USER);
1061 	} else {
1062 		privsep_pw = pwcopy(privsep_pw);
1063 		freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1064 		privsep_pw->pw_passwd = xstrdup("*");
1065 	}
1066 	endpwent();
1067 
1068 	if (!debug_flag && !inetd_flag) {
1069 		if ((startup_pipe = dup(REEXEC_CONFIG_PASS_FD)) == -1)
1070 			fatal("internal error: no startup pipe");
1071 
1072 		/*
1073 		 * Signal parent that this child is at a point where
1074 		 * they can go away if they have a SIGHUP pending.
1075 		 */
1076 		(void)atomicio(vwrite, startup_pipe, "\0", 1);
1077 	}
1078 	/* close the fd, but keep the slot reserved */
1079 	if (dup2(devnull, REEXEC_CONFIG_PASS_FD) == -1)
1080 		fatal("dup2 devnull->config fd: %s", strerror(errno));
1081 
1082 	/* Check that options are sensible */
1083 	if (options.authorized_keys_command_user == NULL &&
1084 	    (options.authorized_keys_command != NULL &&
1085 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1086 		fatal("AuthorizedKeysCommand set without "
1087 		    "AuthorizedKeysCommandUser");
1088 	if (options.authorized_principals_command_user == NULL &&
1089 	    (options.authorized_principals_command != NULL &&
1090 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1091 		fatal("AuthorizedPrincipalsCommand set without "
1092 		    "AuthorizedPrincipalsCommandUser");
1093 
1094 	/*
1095 	 * Check whether there is any path through configured auth methods.
1096 	 * Unfortunately it is not possible to verify this generally before
1097 	 * daemonisation in the presence of Match block, but this catches
1098 	 * and warns for trivial misconfigurations that could break login.
1099 	 */
1100 	if (options.num_auth_methods != 0) {
1101 		for (i = 0; i < options.num_auth_methods; i++) {
1102 			if (auth2_methods_valid(options.auth_methods[i],
1103 			    1) == 0)
1104 				break;
1105 		}
1106 		if (i >= options.num_auth_methods)
1107 			fatal("AuthenticationMethods cannot be satisfied by "
1108 			    "enabled authentication methods");
1109 	}
1110 
1111 #ifdef WITH_OPENSSL
1112 	if (options.moduli_file != NULL)
1113 		dh_set_moduli_file(options.moduli_file);
1114 #endif
1115 
1116 	if (options.host_key_agent) {
1117 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1118 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1119 			    options.host_key_agent, 1);
1120 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1121 			have_agent = 1;
1122 		else
1123 			error_r(r, "Could not connect to agent \"%s\"",
1124 			    options.host_key_agent);
1125 	}
1126 
1127 	if (options.num_host_key_files != sensitive_data.num_hostkeys) {
1128 		fatal("internal error: hostkeys confused (config %u recvd %u)",
1129 		    options.num_host_key_files, sensitive_data.num_hostkeys);
1130 	}
1131 
1132 	for (i = 0; i < options.num_host_key_files; i++) {
1133 		if (sensitive_data.host_keys[i] != NULL ||
1134 		    (have_agent && sensitive_data.host_pubkeys[i] != NULL)) {
1135 			have_key = 1;
1136 			break;
1137 		}
1138 	}
1139 	if (!have_key)
1140 		fatal("internal error: monitor received no hostkeys");
1141 
1142 	/* Ensure that umask disallows at least group and world write */
1143 	new_umask = umask(0077) | 0022;
1144 	(void) umask(new_umask);
1145 
1146 	/* Initialize the log (it is reinitialized below in case we forked). */
1147 	if (debug_flag)
1148 		log_stderr = 1;
1149 	log_init(__progname, options.log_level,
1150 	    options.log_facility, log_stderr);
1151 	for (i = 0; i < options.num_log_verbose; i++)
1152 		log_verbose_add(options.log_verbose[i]);
1153 
1154 	/* Reinitialize the log (because of the fork above). */
1155 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1156 
1157 	/*
1158 	 * Chdir to the root directory so that the current disk can be
1159 	 * unmounted if desired.
1160 	 */
1161 	if (chdir("/") == -1)
1162 		error("chdir(\"/\"): %s", strerror(errno));
1163 
1164 	/* ignore SIGPIPE */
1165 	ssh_signal(SIGPIPE, SIG_IGN);
1166 
1167 	/* Get a connection, either from inetd or rexec */
1168 	if (inetd_flag) {
1169 		/*
1170 		 * NB. must be different fd numbers for the !socket case,
1171 		 * as packet_connection_is_on_socket() depends on this.
1172 		 */
1173 		sock_in = dup(STDIN_FILENO);
1174 		sock_out = dup(STDOUT_FILENO);
1175 	} else {
1176 		/* rexec case; accept()ed socket in ancestor listener */
1177 		sock_in = sock_out = dup(STDIN_FILENO);
1178 	}
1179 
1180 	/*
1181 	 * We intentionally do not close the descriptors 0, 1, and 2
1182 	 * as our code for setting the descriptors won't work if
1183 	 * ttyfd happens to be one of those.
1184 	 */
1185 	if (stdfd_devnull(1, 1, !log_stderr) == -1)
1186 		error("stdfd_devnull failed");
1187 	debug("network sockets: %d, %d", sock_in, sock_out);
1188 
1189 	/* This is the child processing a new connection. */
1190 	setproctitle("%s", "[accepted]");
1191 
1192 	/* Executed child processes don't need these. */
1193 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1194 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1195 
1196 	/* We will not restart on SIGHUP since it no longer makes sense. */
1197 	ssh_signal(SIGALRM, SIG_DFL);
1198 	ssh_signal(SIGHUP, SIG_DFL);
1199 	ssh_signal(SIGTERM, SIG_DFL);
1200 	ssh_signal(SIGQUIT, SIG_DFL);
1201 	ssh_signal(SIGCHLD, SIG_DFL);
1202 	ssh_signal(SIGINT, SIG_DFL);
1203 
1204 	/*
1205 	 * Register our connection.  This turns encryption off because we do
1206 	 * not have a key.
1207 	 */
1208 	if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
1209 		fatal("Unable to create connection");
1210 	the_active_state = ssh;
1211 	ssh_packet_set_server(ssh);
1212 
1213 	check_ip_options(ssh);
1214 
1215 	/* Prepare the channels layer */
1216 	channel_init_channels(ssh);
1217 	channel_set_af(ssh, options.address_family);
1218 	server_process_channel_timeouts(ssh);
1219 	server_process_permitopen(ssh);
1220 
1221 	/* Set SO_KEEPALIVE if requested. */
1222 	if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
1223 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
1224 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1225 
1226 	if ((remote_port = ssh_remote_port(ssh)) < 0) {
1227 		debug("ssh_remote_port failed");
1228 		cleanup_exit(255);
1229 	}
1230 
1231 #ifdef HAVE_LOGIN_CAP
1232 	/* Also caches remote hostname for sandboxed child. */
1233 	auth_get_canonical_hostname(ssh, options.use_dns);
1234 #endif
1235 
1236 	/*
1237 	 * The rest of the code depends on the fact that
1238 	 * ssh_remote_ipaddr() caches the remote ip, even if
1239 	 * the socket goes away.
1240 	 */
1241 	remote_ip = ssh_remote_ipaddr(ssh);
1242 
1243 #ifdef SSH_AUDIT_EVENTS
1244 	audit_connection_from(remote_ip, remote_port);
1245 #endif
1246 
1247 	rdomain = ssh_packet_rdomain_in(ssh);
1248 
1249 	/* Log the connection. */
1250 	laddr = get_local_ipaddr(sock_in);
1251 	verbose("Connection from %s port %d on %s port %d%s%s%s",
1252 	    remote_ip, remote_port, laddr,  ssh_local_port(ssh),
1253 	    rdomain == NULL ? "" : " rdomain \"",
1254 	    rdomain == NULL ? "" : rdomain,
1255 	    rdomain == NULL ? "" : "\"");
1256 	free(laddr);
1257 
1258 	/*
1259 	 * We don't want to listen forever unless the other side
1260 	 * successfully authenticates itself.  So we set up an alarm which is
1261 	 * cleared after successful authentication.  A limit of zero
1262 	 * indicates no limit. Note that we don't set the alarm in debugging
1263 	 * mode; it is just annoying to have the server exit just when you
1264 	 * are about to discover the bug.
1265 	 */
1266 	ssh_signal(SIGALRM, grace_alarm_handler);
1267 	if (!debug_flag && options.login_grace_time > 0) {
1268 		int ujitter = arc4random_uniform(4 * 1000000);
1269 
1270 		timerclear(&itv.it_interval);
1271 		itv.it_value.tv_sec = options.login_grace_time;
1272 		itv.it_value.tv_sec += ujitter / 1000000;
1273 		itv.it_value.tv_usec = ujitter % 1000000;
1274 
1275 		if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
1276 			fatal("login grace time setitimer failed");
1277 	}
1278 
1279 	if ((r = kex_exchange_identification(ssh, -1,
1280 	    options.version_addendum)) != 0)
1281 		sshpkt_fatal(ssh, r, "banner exchange");
1282 
1283 	ssh_packet_set_nonblocking(ssh);
1284 
1285 	/* allocate authentication context */
1286 	authctxt = xcalloc(1, sizeof(*authctxt));
1287 	ssh->authctxt = authctxt;
1288 
1289 	/* XXX global for cleanup, access from other modules */
1290 	the_authctxt = authctxt;
1291 
1292 	/* Set default key authentication options */
1293 	if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
1294 		fatal("allocation failed");
1295 
1296 	/* prepare buffer to collect messages to display to user after login */
1297 	if ((loginmsg = sshbuf_new()) == NULL)
1298 		fatal("sshbuf_new loginmsg failed");
1299 	auth_debug_reset();
1300 
1301 	BLACKLIST_INIT();
1302 
1303 	if (privsep_preauth(ssh) != 1)
1304 		fatal("privsep_preauth failed");
1305 
1306 	/* Now user is authenticated */
1307 
1308 	/*
1309 	 * Cancel the alarm we set to limit the time taken for
1310 	 * authentication.
1311 	 */
1312 	timerclear(&itv.it_interval);
1313 	timerclear(&itv.it_value);
1314 	if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
1315 		fatal("login grace time clear failed");
1316 	ssh_signal(SIGALRM, SIG_DFL);
1317 	authctxt->authenticated = 1;
1318 	if (startup_pipe != -1) {
1319 		/* signal listener that authentication completed successfully */
1320 		(void)atomicio(vwrite, startup_pipe, "\001", 1);
1321 		close(startup_pipe);
1322 		startup_pipe = -1;
1323 	}
1324 
1325 	if (options.routing_domain != NULL)
1326 		set_process_rdomain(ssh, options.routing_domain);
1327 
1328 #ifdef SSH_AUDIT_EVENTS
1329 	audit_event(ssh, SSH_AUTH_SUCCESS);
1330 #endif
1331 
1332 #ifdef GSSAPI
1333 	if (options.gss_authentication) {
1334 		temporarily_use_uid(authctxt->pw);
1335 		ssh_gssapi_storecreds();
1336 		restore_uid();
1337 	}
1338 #endif
1339 #ifdef USE_PAM
1340 	if (options.use_pam) {
1341 		do_pam_setcred();
1342 		do_pam_session(ssh);
1343 	}
1344 #endif
1345 
1346 	/*
1347 	 * In privilege separation, we fork another child and prepare
1348 	 * file descriptor passing.
1349 	 */
1350 	privsep_postauth(ssh, authctxt);
1351 	/* the monitor process [priv] will not return */
1352 
1353 	ssh_packet_set_timeout(ssh, options.client_alive_interval,
1354 	    options.client_alive_count_max);
1355 
1356 	/* Try to send all our hostkeys to the client */
1357 	notify_hostkeys(ssh);
1358 
1359 	/* Start session. */
1360 	do_authenticated(ssh, authctxt);
1361 
1362 	/* The connection has been terminated. */
1363 	ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1364 	verbose("Transferred: sent %llu, received %llu bytes",
1365 	    (unsigned long long)obytes, (unsigned long long)ibytes);
1366 
1367 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1368 
1369 #ifdef USE_PAM
1370 	if (options.use_pam)
1371 		finish_pam();
1372 #endif /* USE_PAM */
1373 
1374 #ifdef SSH_AUDIT_EVENTS
1375 	mm_audit_event(ssh, SSH_CONNECTION_CLOSE);
1376 #endif
1377 
1378 	ssh_packet_close(ssh);
1379 
1380 	mm_terminate();
1381 
1382 	exit(0);
1383 }
1384 
1385 int
sshd_hostkey_sign(struct ssh * ssh,struct sshkey * privkey,struct sshkey * pubkey,u_char ** signature,size_t * slenp,const u_char * data,size_t dlen,const char * alg)1386 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
1387     struct sshkey *pubkey, u_char **signature, size_t *slenp,
1388     const u_char *data, size_t dlen, const char *alg)
1389 {
1390 	if (privkey) {
1391 		if (mm_sshkey_sign(ssh, privkey, signature, slenp,
1392 		    data, dlen, alg, options.sk_provider, NULL,
1393 		    ssh->compat) < 0)
1394 			fatal_f("privkey sign failed");
1395 	} else {
1396 		if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
1397 		    data, dlen, alg, options.sk_provider, NULL,
1398 		    ssh->compat) < 0)
1399 			fatal_f("pubkey sign failed");
1400 	}
1401 	return 0;
1402 }
1403 
1404 /* server specific fatal cleanup */
1405 void
cleanup_exit(int i)1406 cleanup_exit(int i)
1407 {
1408 	extern int auth_attempted; /* monitor.c */
1409 
1410 	if (the_active_state != NULL && the_authctxt != NULL) {
1411 		do_cleanup(the_active_state, the_authctxt);
1412 		if (privsep_is_preauth &&
1413 		    pmonitor != NULL && pmonitor->m_pid > 1) {
1414 			debug("Killing privsep child %d", pmonitor->m_pid);
1415 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1416 			    errno != ESRCH) {
1417 				error_f("kill(%d): %s", pmonitor->m_pid,
1418 				    strerror(errno));
1419 			}
1420 		}
1421 	}
1422 #ifdef SSH_AUDIT_EVENTS
1423 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
1424 	if (the_active_state != NULL && mm_is_monitor())
1425 		audit_event(the_active_state, SSH_CONNECTION_ABANDON);
1426 #endif
1427 	/* Override default fatal exit value when auth was attempted */
1428 	if (i == 255 && auth_attempted)
1429 		_exit(EXIT_AUTH_ATTEMPTED);
1430 	_exit(i);
1431 }
1432