xref: /freebsd/crypto/openssh/session.c (revision 3332f1b444d4a73238e9f59cca27bfc95fe936bd)
1 /* $OpenBSD: session.c,v 1.329 2021/08/11 05:20:17 djm Exp $ */
2 /*
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  *
6  * As far as I am concerned, the code I have written for this software
7  * can be used freely for any purpose.  Any derived versions of this
8  * software must be clearly marked as such, and if the derived work is
9  * incompatible with the protocol description in the RFC file, it must be
10  * called by a name other than "ssh" or "Secure Shell".
11  *
12  * SSH2 support by Markus Friedl.
13  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #include "includes.h"
37 __RCSID("$FreeBSD$");
38 
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #include <sys/socket.h>
45 #include <sys/un.h>
46 #include <sys/wait.h>
47 
48 #include <arpa/inet.h>
49 
50 #include <ctype.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <grp.h>
54 #include <netdb.h>
55 #ifdef HAVE_PATHS_H
56 #include <paths.h>
57 #endif
58 #include <pwd.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <stdarg.h>
64 #include <unistd.h>
65 #include <limits.h>
66 
67 #include "openbsd-compat/sys-queue.h"
68 #include "xmalloc.h"
69 #include "ssh.h"
70 #include "ssh2.h"
71 #include "sshpty.h"
72 #include "packet.h"
73 #include "sshbuf.h"
74 #include "ssherr.h"
75 #include "match.h"
76 #include "uidswap.h"
77 #include "compat.h"
78 #include "channels.h"
79 #include "sshkey.h"
80 #include "cipher.h"
81 #ifdef GSSAPI
82 #include "ssh-gss.h"
83 #endif
84 #include "hostfile.h"
85 #include "auth.h"
86 #include "auth-options.h"
87 #include "authfd.h"
88 #include "pathnames.h"
89 #include "log.h"
90 #include "misc.h"
91 #include "servconf.h"
92 #include "sshlogin.h"
93 #include "serverloop.h"
94 #include "canohost.h"
95 #include "session.h"
96 #include "kex.h"
97 #include "monitor_wrap.h"
98 #include "sftp.h"
99 #include "atomicio.h"
100 
101 #if defined(KRB5) && defined(USE_AFS)
102 #include <kafs.h>
103 #endif
104 
105 #ifdef WITH_SELINUX
106 #include <selinux/selinux.h>
107 #endif
108 
109 #define IS_INTERNAL_SFTP(c) \
110 	(!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
111 	 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
112 	  c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
113 	  c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
114 
115 /* func */
116 
117 Session *session_new(void);
118 void	session_set_fds(struct ssh *, Session *, int, int, int, int, int);
119 void	session_pty_cleanup(Session *);
120 void	session_proctitle(Session *);
121 int	session_setup_x11fwd(struct ssh *, Session *);
122 int	do_exec_pty(struct ssh *, Session *, const char *);
123 int	do_exec_no_pty(struct ssh *, Session *, const char *);
124 int	do_exec(struct ssh *, Session *, const char *);
125 void	do_login(struct ssh *, Session *, const char *);
126 void	do_child(struct ssh *, Session *, const char *);
127 void	do_motd(void);
128 int	check_quietlogin(Session *, const char *);
129 
130 static void do_authenticated2(struct ssh *, Authctxt *);
131 
132 static int session_pty_req(struct ssh *, Session *);
133 
134 /* import */
135 extern ServerOptions options;
136 extern char *__progname;
137 extern int debug_flag;
138 extern u_int utmp_len;
139 extern int startup_pipe;
140 extern void destroy_sensitive_data(void);
141 extern struct sshbuf *loginmsg;
142 extern struct sshauthopt *auth_opts;
143 extern char *tun_fwd_ifnames; /* serverloop.c */
144 
145 /* original command from peer. */
146 const char *original_command = NULL;
147 
148 /* data */
149 static int sessions_first_unused = -1;
150 static int sessions_nalloc = 0;
151 static Session *sessions = NULL;
152 
153 #define SUBSYSTEM_NONE			0
154 #define SUBSYSTEM_EXT			1
155 #define SUBSYSTEM_INT_SFTP		2
156 #define SUBSYSTEM_INT_SFTP_ERROR	3
157 
158 #ifdef HAVE_LOGIN_CAP
159 login_cap_t *lc;
160 #endif
161 
162 static int is_child = 0;
163 static int in_chroot = 0;
164 
165 /* File containing userauth info, if ExposeAuthInfo set */
166 static char *auth_info_file = NULL;
167 
168 /* Name and directory of socket for authentication agent forwarding. */
169 static char *auth_sock_name = NULL;
170 static char *auth_sock_dir = NULL;
171 
172 /* removes the agent forwarding socket */
173 
174 static void
175 auth_sock_cleanup_proc(struct passwd *pw)
176 {
177 	if (auth_sock_name != NULL) {
178 		temporarily_use_uid(pw);
179 		unlink(auth_sock_name);
180 		rmdir(auth_sock_dir);
181 		auth_sock_name = NULL;
182 		restore_uid();
183 	}
184 }
185 
186 static int
187 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
188 {
189 	Channel *nc;
190 	int sock = -1;
191 
192 	if (auth_sock_name != NULL) {
193 		error("authentication forwarding requested twice.");
194 		return 0;
195 	}
196 
197 	/* Temporarily drop privileged uid for mkdir/bind. */
198 	temporarily_use_uid(pw);
199 
200 	/* Allocate a buffer for the socket name, and format the name. */
201 	auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
202 
203 	/* Create private directory for socket */
204 	if (mkdtemp(auth_sock_dir) == NULL) {
205 		ssh_packet_send_debug(ssh, "Agent forwarding disabled: "
206 		    "mkdtemp() failed: %.100s", strerror(errno));
207 		restore_uid();
208 		free(auth_sock_dir);
209 		auth_sock_dir = NULL;
210 		goto authsock_err;
211 	}
212 
213 	xasprintf(&auth_sock_name, "%s/agent.%ld",
214 	    auth_sock_dir, (long) getpid());
215 
216 	/* Start a Unix listener on auth_sock_name. */
217 	sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
218 
219 	/* Restore the privileged uid. */
220 	restore_uid();
221 
222 	/* Check for socket/bind/listen failure. */
223 	if (sock < 0)
224 		goto authsock_err;
225 
226 	/* Allocate a channel for the authentication agent socket. */
227 	nc = channel_new(ssh, "auth socket",
228 	    SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
229 	    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
230 	    0, "auth socket", 1);
231 	nc->path = xstrdup(auth_sock_name);
232 	return 1;
233 
234  authsock_err:
235 	free(auth_sock_name);
236 	if (auth_sock_dir != NULL) {
237 		temporarily_use_uid(pw);
238 		rmdir(auth_sock_dir);
239 		restore_uid();
240 		free(auth_sock_dir);
241 	}
242 	if (sock != -1)
243 		close(sock);
244 	auth_sock_name = NULL;
245 	auth_sock_dir = NULL;
246 	return 0;
247 }
248 
249 static void
250 display_loginmsg(void)
251 {
252 	int r;
253 
254 	if (sshbuf_len(loginmsg) == 0)
255 		return;
256 	if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
257 		fatal_fr(r, "sshbuf_put_u8");
258 	printf("%s", (char *)sshbuf_ptr(loginmsg));
259 	sshbuf_reset(loginmsg);
260 }
261 
262 static void
263 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
264 {
265 	int fd = -1, success = 0;
266 
267 	if (!options.expose_userauth_info || info == NULL)
268 		return;
269 
270 	temporarily_use_uid(pw);
271 	auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
272 	if ((fd = mkstemp(auth_info_file)) == -1) {
273 		error_f("mkstemp: %s", strerror(errno));
274 		goto out;
275 	}
276 	if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
277 	    sshbuf_len(info)) != sshbuf_len(info)) {
278 		error_f("write: %s", strerror(errno));
279 		goto out;
280 	}
281 	if (close(fd) != 0) {
282 		error_f("close: %s", strerror(errno));
283 		goto out;
284 	}
285 	success = 1;
286  out:
287 	if (!success) {
288 		if (fd != -1)
289 			close(fd);
290 		free(auth_info_file);
291 		auth_info_file = NULL;
292 	}
293 	restore_uid();
294 }
295 
296 static void
297 set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
298 {
299 	char *tmp, *cp, *host;
300 	int port;
301 	size_t i;
302 
303 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
304 		channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
305 		for (i = 0; i < auth_opts->npermitopen; i++) {
306 			tmp = cp = xstrdup(auth_opts->permitopen[i]);
307 			/* This shouldn't fail as it has already been checked */
308 			if ((host = hpdelim(&cp)) == NULL)
309 				fatal_f("internal error: hpdelim");
310 			host = cleanhostname(host);
311 			if (cp == NULL || (port = permitopen_port(cp)) < 0)
312 				fatal_f("internal error: permitopen port");
313 			channel_add_permission(ssh,
314 			    FORWARD_USER, FORWARD_LOCAL, host, port);
315 			free(tmp);
316 		}
317 	}
318 	if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
319 		channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
320 		for (i = 0; i < auth_opts->npermitlisten; i++) {
321 			tmp = cp = xstrdup(auth_opts->permitlisten[i]);
322 			/* This shouldn't fail as it has already been checked */
323 			if ((host = hpdelim(&cp)) == NULL)
324 				fatal_f("internal error: hpdelim");
325 			host = cleanhostname(host);
326 			if (cp == NULL || (port = permitopen_port(cp)) < 0)
327 				fatal_f("internal error: permitlisten port");
328 			channel_add_permission(ssh,
329 			    FORWARD_USER, FORWARD_REMOTE, host, port);
330 			free(tmp);
331 		}
332 	}
333 }
334 
335 void
336 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
337 {
338 	setproctitle("%s", authctxt->pw->pw_name);
339 
340 	auth_log_authopts("active", auth_opts, 0);
341 
342 	/* setup the channel layer */
343 	/* XXX - streamlocal? */
344 	set_fwdpermit_from_authopts(ssh, auth_opts);
345 
346 	if (!auth_opts->permit_port_forwarding_flag ||
347 	    options.disable_forwarding) {
348 		channel_disable_admin(ssh, FORWARD_LOCAL);
349 		channel_disable_admin(ssh, FORWARD_REMOTE);
350 	} else {
351 		if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
352 			channel_disable_admin(ssh, FORWARD_LOCAL);
353 		else
354 			channel_permit_all(ssh, FORWARD_LOCAL);
355 		if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
356 			channel_disable_admin(ssh, FORWARD_REMOTE);
357 		else
358 			channel_permit_all(ssh, FORWARD_REMOTE);
359 	}
360 	auth_debug_send(ssh);
361 
362 	prepare_auth_info_file(authctxt->pw, authctxt->session_info);
363 
364 	do_authenticated2(ssh, authctxt);
365 
366 	do_cleanup(ssh, authctxt);
367 }
368 
369 /* Check untrusted xauth strings for metacharacters */
370 static int
371 xauth_valid_string(const char *s)
372 {
373 	size_t i;
374 
375 	for (i = 0; s[i] != '\0'; i++) {
376 		if (!isalnum((u_char)s[i]) &&
377 		    s[i] != '.' && s[i] != ':' && s[i] != '/' &&
378 		    s[i] != '-' && s[i] != '_')
379 			return 0;
380 	}
381 	return 1;
382 }
383 
384 #define USE_PIPES 1
385 /*
386  * This is called to fork and execute a command when we have no tty.  This
387  * will call do_child from the child, and server_loop from the parent after
388  * setting up file descriptors and such.
389  */
390 int
391 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
392 {
393 	pid_t pid;
394 #ifdef USE_PIPES
395 	int pin[2], pout[2], perr[2];
396 
397 	if (s == NULL)
398 		fatal("do_exec_no_pty: no session");
399 
400 	/* Allocate pipes for communicating with the program. */
401 	if (pipe(pin) == -1) {
402 		error_f("pipe in: %.100s", strerror(errno));
403 		return -1;
404 	}
405 	if (pipe(pout) == -1) {
406 		error_f("pipe out: %.100s", strerror(errno));
407 		close(pin[0]);
408 		close(pin[1]);
409 		return -1;
410 	}
411 	if (pipe(perr) == -1) {
412 		error_f("pipe err: %.100s", strerror(errno));
413 		close(pin[0]);
414 		close(pin[1]);
415 		close(pout[0]);
416 		close(pout[1]);
417 		return -1;
418 	}
419 #else
420 	int inout[2], err[2];
421 
422 	if (s == NULL)
423 		fatal("do_exec_no_pty: no session");
424 
425 	/* Uses socket pairs to communicate with the program. */
426 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) {
427 		error_f("socketpair #1: %.100s", strerror(errno));
428 		return -1;
429 	}
430 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) == -1) {
431 		error_f("socketpair #2: %.100s", strerror(errno));
432 		close(inout[0]);
433 		close(inout[1]);
434 		return -1;
435 	}
436 #endif
437 
438 	session_proctitle(s);
439 
440 	/* Fork the child. */
441 	switch ((pid = fork())) {
442 	case -1:
443 		error_f("fork: %.100s", strerror(errno));
444 #ifdef USE_PIPES
445 		close(pin[0]);
446 		close(pin[1]);
447 		close(pout[0]);
448 		close(pout[1]);
449 		close(perr[0]);
450 		close(perr[1]);
451 #else
452 		close(inout[0]);
453 		close(inout[1]);
454 		close(err[0]);
455 		close(err[1]);
456 #endif
457 		return -1;
458 	case 0:
459 		is_child = 1;
460 
461 		/*
462 		 * Create a new session and process group since the 4.4BSD
463 		 * setlogin() affects the entire process group.
464 		 */
465 		if (setsid() == -1)
466 			error("setsid failed: %.100s", strerror(errno));
467 
468 #ifdef USE_PIPES
469 		/*
470 		 * Redirect stdin.  We close the parent side of the socket
471 		 * pair, and make the child side the standard input.
472 		 */
473 		close(pin[1]);
474 		if (dup2(pin[0], 0) == -1)
475 			perror("dup2 stdin");
476 		close(pin[0]);
477 
478 		/* Redirect stdout. */
479 		close(pout[0]);
480 		if (dup2(pout[1], 1) == -1)
481 			perror("dup2 stdout");
482 		close(pout[1]);
483 
484 		/* Redirect stderr. */
485 		close(perr[0]);
486 		if (dup2(perr[1], 2) == -1)
487 			perror("dup2 stderr");
488 		close(perr[1]);
489 #else
490 		/*
491 		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
492 		 * use the same socket, as some programs (particularly rdist)
493 		 * seem to depend on it.
494 		 */
495 		close(inout[1]);
496 		close(err[1]);
497 		if (dup2(inout[0], 0) == -1)	/* stdin */
498 			perror("dup2 stdin");
499 		if (dup2(inout[0], 1) == -1)	/* stdout (same as stdin) */
500 			perror("dup2 stdout");
501 		close(inout[0]);
502 		if (dup2(err[0], 2) == -1)	/* stderr */
503 			perror("dup2 stderr");
504 		close(err[0]);
505 #endif
506 
507 		/* Do processing for the child (exec command etc). */
508 		do_child(ssh, s, command);
509 		/* NOTREACHED */
510 	default:
511 		break;
512 	}
513 
514 #ifdef HAVE_CYGWIN
515 	cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
516 #endif
517 
518 	s->pid = pid;
519 	/* Set interactive/non-interactive mode. */
520 	ssh_packet_set_interactive(ssh, s->display != NULL,
521 	    options.ip_qos_interactive, options.ip_qos_bulk);
522 
523 	/*
524 	 * Clear loginmsg, since it's the child's responsibility to display
525 	 * it to the user, otherwise multiple sessions may accumulate
526 	 * multiple copies of the login messages.
527 	 */
528 	sshbuf_reset(loginmsg);
529 
530 #ifdef USE_PIPES
531 	/* We are the parent.  Close the child sides of the pipes. */
532 	close(pin[0]);
533 	close(pout[1]);
534 	close(perr[1]);
535 
536 	session_set_fds(ssh, s, pin[1], pout[0], perr[0],
537 	    s->is_subsystem, 0);
538 #else
539 	/* We are the parent.  Close the child sides of the socket pairs. */
540 	close(inout[0]);
541 	close(err[0]);
542 
543 	/*
544 	 * Enter the interactive session.  Note: server_loop must be able to
545 	 * handle the case that fdin and fdout are the same.
546 	 */
547 	session_set_fds(ssh, s, inout[1], inout[1], err[1],
548 	    s->is_subsystem, 0);
549 #endif
550 	return 0;
551 }
552 
553 /*
554  * This is called to fork and execute a command when we have a tty.  This
555  * will call do_child from the child, and server_loop from the parent after
556  * setting up file descriptors, controlling tty, updating wtmp, utmp,
557  * lastlog, and other such operations.
558  */
559 int
560 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
561 {
562 	int fdout, ptyfd, ttyfd, ptymaster;
563 	pid_t pid;
564 
565 	if (s == NULL)
566 		fatal("do_exec_pty: no session");
567 	ptyfd = s->ptyfd;
568 	ttyfd = s->ttyfd;
569 
570 	/*
571 	 * Create another descriptor of the pty master side for use as the
572 	 * standard input.  We could use the original descriptor, but this
573 	 * simplifies code in server_loop.  The descriptor is bidirectional.
574 	 * Do this before forking (and cleanup in the child) so as to
575 	 * detect and gracefully fail out-of-fd conditions.
576 	 */
577 	if ((fdout = dup(ptyfd)) == -1) {
578 		error_f("dup #1: %s", strerror(errno));
579 		close(ttyfd);
580 		close(ptyfd);
581 		return -1;
582 	}
583 	/* we keep a reference to the pty master */
584 	if ((ptymaster = dup(ptyfd)) == -1) {
585 		error_f("dup #2: %s", strerror(errno));
586 		close(ttyfd);
587 		close(ptyfd);
588 		close(fdout);
589 		return -1;
590 	}
591 
592 	/* Fork the child. */
593 	switch ((pid = fork())) {
594 	case -1:
595 		error_f("fork: %.100s", strerror(errno));
596 		close(fdout);
597 		close(ptymaster);
598 		close(ttyfd);
599 		close(ptyfd);
600 		return -1;
601 	case 0:
602 		is_child = 1;
603 
604 		close(fdout);
605 		close(ptymaster);
606 
607 		/* Close the master side of the pseudo tty. */
608 		close(ptyfd);
609 
610 		/* Make the pseudo tty our controlling tty. */
611 		pty_make_controlling_tty(&ttyfd, s->tty);
612 
613 		/* Redirect stdin/stdout/stderr from the pseudo tty. */
614 		if (dup2(ttyfd, 0) == -1)
615 			error("dup2 stdin: %s", strerror(errno));
616 		if (dup2(ttyfd, 1) == -1)
617 			error("dup2 stdout: %s", strerror(errno));
618 		if (dup2(ttyfd, 2) == -1)
619 			error("dup2 stderr: %s", strerror(errno));
620 
621 		/* Close the extra descriptor for the pseudo tty. */
622 		close(ttyfd);
623 
624 		/* record login, etc. similar to login(1) */
625 #ifndef HAVE_OSF_SIA
626 		do_login(ssh, s, command);
627 #endif
628 		/*
629 		 * Do common processing for the child, such as execing
630 		 * the command.
631 		 */
632 		do_child(ssh, s, command);
633 		/* NOTREACHED */
634 	default:
635 		break;
636 	}
637 
638 #ifdef HAVE_CYGWIN
639 	cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
640 #endif
641 
642 	s->pid = pid;
643 
644 	/* Parent.  Close the slave side of the pseudo tty. */
645 	close(ttyfd);
646 
647 	/* Enter interactive session. */
648 	s->ptymaster = ptymaster;
649 	ssh_packet_set_interactive(ssh, 1,
650 	    options.ip_qos_interactive, options.ip_qos_bulk);
651 	session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
652 	return 0;
653 }
654 
655 /*
656  * This is called to fork and execute a command.  If another command is
657  * to be forced, execute that instead.
658  */
659 int
660 do_exec(struct ssh *ssh, Session *s, const char *command)
661 {
662 	int ret;
663 	const char *forced = NULL, *tty = NULL;
664 	char session_type[1024];
665 
666 	if (options.adm_forced_command) {
667 		original_command = command;
668 		command = options.adm_forced_command;
669 		forced = "(config)";
670 	} else if (auth_opts->force_command != NULL) {
671 		original_command = command;
672 		command = auth_opts->force_command;
673 		forced = "(key-option)";
674 	}
675 	s->forced = 0;
676 	if (forced != NULL) {
677 		s->forced = 1;
678 		if (IS_INTERNAL_SFTP(command)) {
679 			s->is_subsystem = s->is_subsystem ?
680 			    SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
681 		} else if (s->is_subsystem)
682 			s->is_subsystem = SUBSYSTEM_EXT;
683 		snprintf(session_type, sizeof(session_type),
684 		    "forced-command %s '%.900s'", forced, command);
685 	} else if (s->is_subsystem) {
686 		snprintf(session_type, sizeof(session_type),
687 		    "subsystem '%.900s'", s->subsys);
688 	} else if (command == NULL) {
689 		snprintf(session_type, sizeof(session_type), "shell");
690 	} else {
691 		/* NB. we don't log unforced commands to preserve privacy */
692 		snprintf(session_type, sizeof(session_type), "command");
693 	}
694 
695 	if (s->ttyfd != -1) {
696 		tty = s->tty;
697 		if (strncmp(tty, "/dev/", 5) == 0)
698 			tty += 5;
699 	}
700 
701 	verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
702 	    session_type,
703 	    tty == NULL ? "" : " on ",
704 	    tty == NULL ? "" : tty,
705 	    s->pw->pw_name,
706 	    ssh_remote_ipaddr(ssh),
707 	    ssh_remote_port(ssh),
708 	    s->self);
709 
710 #ifdef SSH_AUDIT_EVENTS
711 	if (command != NULL)
712 		PRIVSEP(audit_run_command(command));
713 	else if (s->ttyfd == -1) {
714 		char *shell = s->pw->pw_shell;
715 
716 		if (shell[0] == '\0')	/* empty shell means /bin/sh */
717 			shell =_PATH_BSHELL;
718 		PRIVSEP(audit_run_command(shell));
719 	}
720 #endif
721 	if (s->ttyfd != -1)
722 		ret = do_exec_pty(ssh, s, command);
723 	else
724 		ret = do_exec_no_pty(ssh, s, command);
725 
726 	original_command = NULL;
727 
728 	/*
729 	 * Clear loginmsg: it's the child's responsibility to display
730 	 * it to the user, otherwise multiple sessions may accumulate
731 	 * multiple copies of the login messages.
732 	 */
733 	sshbuf_reset(loginmsg);
734 
735 	return ret;
736 }
737 
738 /* administrative, login(1)-like work */
739 void
740 do_login(struct ssh *ssh, Session *s, const char *command)
741 {
742 	socklen_t fromlen;
743 	struct sockaddr_storage from;
744 	struct passwd * pw = s->pw;
745 	pid_t pid = getpid();
746 
747 	/*
748 	 * Get IP address of client. If the connection is not a socket, let
749 	 * the address be 0.0.0.0.
750 	 */
751 	memset(&from, 0, sizeof(from));
752 	fromlen = sizeof(from);
753 	if (ssh_packet_connection_is_on_socket(ssh)) {
754 		if (getpeername(ssh_packet_get_connection_in(ssh),
755 		    (struct sockaddr *)&from, &fromlen) == -1) {
756 			debug("getpeername: %.100s", strerror(errno));
757 			cleanup_exit(255);
758 		}
759 	}
760 
761 	/* Record that there was a login on that tty from the remote host. */
762 	if (!use_privsep)
763 		record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
764 		    session_get_remote_name_or_ip(ssh, utmp_len,
765 		    options.use_dns),
766 		    (struct sockaddr *)&from, fromlen);
767 
768 #ifdef USE_PAM
769 	/*
770 	 * If password change is needed, do it now.
771 	 * This needs to occur before the ~/.hushlogin check.
772 	 */
773 	if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
774 		display_loginmsg();
775 		do_pam_chauthtok();
776 		s->authctxt->force_pwchange = 0;
777 		/* XXX - signal [net] parent to enable forwardings */
778 	}
779 #endif
780 
781 	if (check_quietlogin(s, command))
782 		return;
783 
784 	display_loginmsg();
785 
786 	do_motd();
787 }
788 
789 /*
790  * Display the message of the day.
791  */
792 void
793 do_motd(void)
794 {
795 	FILE *f;
796 	char buf[256];
797 
798 	if (options.print_motd) {
799 #ifdef HAVE_LOGIN_CAP
800 		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
801 		    "/etc/motd"), "r");
802 #else
803 		f = fopen("/etc/motd", "r");
804 #endif
805 		if (f) {
806 			while (fgets(buf, sizeof(buf), f))
807 				fputs(buf, stdout);
808 			fclose(f);
809 		}
810 	}
811 }
812 
813 
814 /*
815  * Check for quiet login, either .hushlogin or command given.
816  */
817 int
818 check_quietlogin(Session *s, const char *command)
819 {
820 	char buf[256];
821 	struct passwd *pw = s->pw;
822 	struct stat st;
823 
824 	/* Return 1 if .hushlogin exists or a command given. */
825 	if (command != NULL)
826 		return 1;
827 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
828 #ifdef HAVE_LOGIN_CAP
829 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
830 		return 1;
831 #else
832 	if (stat(buf, &st) >= 0)
833 		return 1;
834 #endif
835 	return 0;
836 }
837 
838 /*
839  * Reads environment variables from the given file and adds/overrides them
840  * into the environment.  If the file does not exist, this does nothing.
841  * Otherwise, it must consist of empty lines, comments (line starts with '#')
842  * and assignments of the form name=value.  No other forms are allowed.
843  * If allowlist is not NULL, then it is interpreted as a pattern list and
844  * only variable names that match it will be accepted.
845  */
846 static void
847 read_environment_file(char ***env, u_int *envsize,
848 	const char *filename, const char *allowlist)
849 {
850 	FILE *f;
851 	char *line = NULL, *cp, *value;
852 	size_t linesize = 0;
853 	u_int lineno = 0;
854 
855 	f = fopen(filename, "r");
856 	if (!f)
857 		return;
858 
859 	while (getline(&line, &linesize, f) != -1) {
860 		if (++lineno > 1000)
861 			fatal("Too many lines in environment file %s", filename);
862 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
863 			;
864 		if (!*cp || *cp == '#' || *cp == '\n')
865 			continue;
866 
867 		cp[strcspn(cp, "\n")] = '\0';
868 
869 		value = strchr(cp, '=');
870 		if (value == NULL) {
871 			fprintf(stderr, "Bad line %u in %.100s\n", lineno,
872 			    filename);
873 			continue;
874 		}
875 		/*
876 		 * Replace the equals sign by nul, and advance value to
877 		 * the value string.
878 		 */
879 		*value = '\0';
880 		value++;
881 		if (allowlist != NULL &&
882 		    match_pattern_list(cp, allowlist, 0) != 1)
883 			continue;
884 		child_set_env(env, envsize, cp, value);
885 	}
886 	free(line);
887 	fclose(f);
888 }
889 
890 #ifdef HAVE_ETC_DEFAULT_LOGIN
891 /*
892  * Return named variable from specified environment, or NULL if not present.
893  */
894 static char *
895 child_get_env(char **env, const char *name)
896 {
897 	int i;
898 	size_t len;
899 
900 	len = strlen(name);
901 	for (i=0; env[i] != NULL; i++)
902 		if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
903 			return(env[i] + len + 1);
904 	return NULL;
905 }
906 
907 /*
908  * Read /etc/default/login.
909  * We pick up the PATH (or SUPATH for root) and UMASK.
910  */
911 static void
912 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
913 {
914 	char **tmpenv = NULL, *var;
915 	u_int i, tmpenvsize = 0;
916 	u_long mask;
917 
918 	/*
919 	 * We don't want to copy the whole file to the child's environment,
920 	 * so we use a temporary environment and copy the variables we're
921 	 * interested in.
922 	 */
923 	read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
924 	    options.permit_user_env_allowlist);
925 
926 	if (tmpenv == NULL)
927 		return;
928 
929 	if (uid == 0)
930 		var = child_get_env(tmpenv, "SUPATH");
931 	else
932 		var = child_get_env(tmpenv, "PATH");
933 	if (var != NULL)
934 		child_set_env(env, envsize, "PATH", var);
935 
936 	if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
937 		if (sscanf(var, "%5lo", &mask) == 1)
938 			umask((mode_t)mask);
939 
940 	for (i = 0; tmpenv[i] != NULL; i++)
941 		free(tmpenv[i]);
942 	free(tmpenv);
943 }
944 #endif /* HAVE_ETC_DEFAULT_LOGIN */
945 
946 #if defined(USE_PAM) || defined(HAVE_CYGWIN)
947 static void
948 copy_environment_denylist(char **source, char ***env, u_int *envsize,
949     const char *denylist)
950 {
951 	char *var_name, *var_val;
952 	int i;
953 
954 	if (source == NULL)
955 		return;
956 
957 	for(i = 0; source[i] != NULL; i++) {
958 		var_name = xstrdup(source[i]);
959 		if ((var_val = strstr(var_name, "=")) == NULL) {
960 			free(var_name);
961 			continue;
962 		}
963 		*var_val++ = '\0';
964 
965 		if (denylist == NULL ||
966 		    match_pattern_list(var_name, denylist, 0) != 1) {
967 			debug3("Copy environment: %s=%s", var_name, var_val);
968 			child_set_env(env, envsize, var_name, var_val);
969 		}
970 
971 		free(var_name);
972 	}
973 }
974 #endif /* defined(USE_PAM) || defined(HAVE_CYGWIN) */
975 
976 #ifdef HAVE_CYGWIN
977 static void
978 copy_environment(char **source, char ***env, u_int *envsize)
979 {
980 	copy_environment_denylist(source, env, envsize, NULL);
981 }
982 #endif
983 
984 static char **
985 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
986 {
987 	char buf[256];
988 	size_t n;
989 	u_int i, envsize;
990 	char *ocp, *cp, *value, **env, *laddr;
991 	struct passwd *pw = s->pw;
992 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
993 	char *path = NULL;
994 #else
995 	extern char **environ;
996 	char **senv, **var, *val;
997 #endif
998 
999 	/* Initialize the environment. */
1000 	envsize = 100;
1001 	env = xcalloc(envsize, sizeof(char *));
1002 	env[0] = NULL;
1003 
1004 #ifdef HAVE_CYGWIN
1005 	/*
1006 	 * The Windows environment contains some setting which are
1007 	 * important for a running system. They must not be dropped.
1008 	 */
1009 	{
1010 		char **p;
1011 
1012 		p = fetch_windows_environment();
1013 		copy_environment(p, &env, &envsize);
1014 		free_windows_environment(p);
1015 	}
1016 #endif
1017 
1018 	if (getenv("TZ"))
1019 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1020 
1021 #ifdef GSSAPI
1022 	/* Allow any GSSAPI methods that we've used to alter
1023 	 * the child's environment as they see fit
1024 	 */
1025 	ssh_gssapi_do_child(&env, &envsize);
1026 #endif
1027 
1028 	/* Set basic environment. */
1029 	for (i = 0; i < s->num_env; i++)
1030 		child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1031 
1032 	child_set_env(&env, &envsize, "USER", pw->pw_name);
1033 	child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1034 #ifdef _AIX
1035 	child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1036 #endif
1037 	child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1038 	snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1039 	child_set_env(&env, &envsize, "MAIL", buf);
1040 #ifdef HAVE_LOGIN_CAP
1041 	child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1042 	child_set_env(&env, &envsize, "TERM", "su");
1043 	/*
1044 	 * Temporarily swap out our real environment with an empty one,
1045 	 * let setusercontext() apply any environment variables defined
1046 	 * for the user's login class, copy those variables to the child,
1047 	 * free the temporary environment, and restore the original.
1048 	 */
1049 	senv = environ;
1050 	environ = xmalloc(sizeof(*environ));
1051 	*environ = NULL;
1052 	(void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1053 	for (var = environ; *var != NULL; ++var) {
1054 		if ((val = strchr(*var, '=')) != NULL) {
1055 			*val++ = '\0';
1056 			child_set_env(&env, &envsize, *var, val);
1057 		}
1058 		free(*var);
1059 	}
1060 	free(environ);
1061 	environ = senv;
1062 #else /* HAVE_LOGIN_CAP */
1063 # ifndef HAVE_CYGWIN
1064 	/*
1065 	 * There's no standard path on Windows. The path contains
1066 	 * important components pointing to the system directories,
1067 	 * needed for loading shared libraries. So the path better
1068 	 * remains intact here.
1069 	 */
1070 #  ifdef HAVE_ETC_DEFAULT_LOGIN
1071 	read_etc_default_login(&env, &envsize, pw->pw_uid);
1072 	path = child_get_env(env, "PATH");
1073 #  endif /* HAVE_ETC_DEFAULT_LOGIN */
1074 	if (path == NULL || *path == '\0') {
1075 		child_set_env(&env, &envsize, "PATH",
1076 		    s->pw->pw_uid == 0 ?  SUPERUSER_PATH : _PATH_STDPATH);
1077 	}
1078 # endif /* HAVE_CYGWIN */
1079 #endif /* HAVE_LOGIN_CAP */
1080 
1081 	if (!options.use_pam) {
1082 		snprintf(buf, sizeof buf, "%.200s/%.50s",
1083 		    _PATH_MAILDIR, pw->pw_name);
1084 		child_set_env(&env, &envsize, "MAIL", buf);
1085 	}
1086 
1087 	/* Normal systems set SHELL by default. */
1088 	child_set_env(&env, &envsize, "SHELL", shell);
1089 
1090 	if (s->term)
1091 		child_set_env(&env, &envsize, "TERM", s->term);
1092 	if (s->display)
1093 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1094 
1095 	/*
1096 	 * Since we clear KRB5CCNAME at startup, if it's set now then it
1097 	 * must have been set by a native authentication method (eg AIX or
1098 	 * SIA), so copy it to the child.
1099 	 */
1100 	{
1101 		char *cp;
1102 
1103 		if ((cp = getenv("KRB5CCNAME")) != NULL)
1104 			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1105 	}
1106 
1107 #ifdef _AIX
1108 	{
1109 		char *cp;
1110 
1111 		if ((cp = getenv("AUTHSTATE")) != NULL)
1112 			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1113 		read_environment_file(&env, &envsize, "/etc/environment",
1114 		    options.permit_user_env_allowlist);
1115 	}
1116 #endif
1117 #ifdef KRB5
1118 	if (s->authctxt->krb5_ccname)
1119 		child_set_env(&env, &envsize, "KRB5CCNAME",
1120 		    s->authctxt->krb5_ccname);
1121 #endif
1122 	if (auth_sock_name != NULL)
1123 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1124 		    auth_sock_name);
1125 
1126 
1127 	/* Set custom environment options from pubkey authentication. */
1128 	if (options.permit_user_env) {
1129 		for (n = 0 ; n < auth_opts->nenv; n++) {
1130 			ocp = xstrdup(auth_opts->env[n]);
1131 			cp = strchr(ocp, '=');
1132 			if (cp != NULL) {
1133 				*cp = '\0';
1134 				/* Apply PermitUserEnvironment allowlist */
1135 				if (options.permit_user_env_allowlist == NULL ||
1136 				    match_pattern_list(ocp,
1137 				    options.permit_user_env_allowlist, 0) == 1)
1138 					child_set_env(&env, &envsize,
1139 					    ocp, cp + 1);
1140 			}
1141 			free(ocp);
1142 		}
1143 	}
1144 
1145 	/* read $HOME/.ssh/environment. */
1146 	if (options.permit_user_env) {
1147 		snprintf(buf, sizeof buf, "%.200s/%s/environment",
1148 		    pw->pw_dir, _PATH_SSH_USER_DIR);
1149 		read_environment_file(&env, &envsize, buf,
1150 		    options.permit_user_env_allowlist);
1151 	}
1152 
1153 #ifdef USE_PAM
1154 	/*
1155 	 * Pull in any environment variables that may have
1156 	 * been set by PAM.
1157 	 */
1158 	if (options.use_pam) {
1159 		char **p;
1160 
1161 		/*
1162 		 * Don't allow PAM-internal env vars to leak
1163 		 * back into the session environment.
1164 		 */
1165 #define PAM_ENV_DENYLIST  "SSH_AUTH_INFO*,SSH_CONNECTION*"
1166 		p = fetch_pam_child_environment();
1167 		copy_environment_denylist(p, &env, &envsize,
1168 		    PAM_ENV_DENYLIST);
1169 		free_pam_environment(p);
1170 
1171 		p = fetch_pam_environment();
1172 		copy_environment_denylist(p, &env, &envsize,
1173 		    PAM_ENV_DENYLIST);
1174 		free_pam_environment(p);
1175 	}
1176 #endif /* USE_PAM */
1177 
1178 	/* Environment specified by admin */
1179 	for (i = 0; i < options.num_setenv; i++) {
1180 		cp = xstrdup(options.setenv[i]);
1181 		if ((value = strchr(cp, '=')) == NULL) {
1182 			/* shouldn't happen; vars are checked in servconf.c */
1183 			fatal("Invalid config SetEnv: %s", options.setenv[i]);
1184 		}
1185 		*value++ = '\0';
1186 		child_set_env(&env, &envsize, cp, value);
1187 	}
1188 
1189 	/* SSH_CLIENT deprecated */
1190 	snprintf(buf, sizeof buf, "%.50s %d %d",
1191 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1192 	    ssh_local_port(ssh));
1193 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1194 
1195 	laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh));
1196 	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1197 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1198 	    laddr, ssh_local_port(ssh));
1199 	free(laddr);
1200 	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1201 
1202 	if (tun_fwd_ifnames != NULL)
1203 		child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1204 	if (auth_info_file != NULL)
1205 		child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1206 	if (s->ttyfd != -1)
1207 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1208 	if (original_command)
1209 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1210 		    original_command);
1211 
1212 	if (debug_flag) {
1213 		/* dump the environment */
1214 		fprintf(stderr, "Environment:\n");
1215 		for (i = 0; env[i]; i++)
1216 			fprintf(stderr, "  %.200s\n", env[i]);
1217 	}
1218 	return env;
1219 }
1220 
1221 /*
1222  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1223  * first in this order).
1224  */
1225 static void
1226 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1227 {
1228 	FILE *f = NULL;
1229 	char *cmd = NULL, *user_rc = NULL;
1230 	int do_xauth;
1231 	struct stat st;
1232 
1233 	do_xauth =
1234 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1235 	xasprintf(&user_rc, "%s/%s", s->pw->pw_dir, _PATH_SSH_USER_RC);
1236 
1237 	/* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1238 	if (!s->is_subsystem && options.adm_forced_command == NULL &&
1239 	    auth_opts->permit_user_rc && options.permit_user_rc &&
1240 	    stat(user_rc, &st) >= 0) {
1241 		if (xasprintf(&cmd, "%s -c '%s %s'", shell, _PATH_BSHELL,
1242 		    user_rc) == -1)
1243 			fatal_f("xasprintf: %s", strerror(errno));
1244 		if (debug_flag)
1245 			fprintf(stderr, "Running %s\n", cmd);
1246 		f = popen(cmd, "w");
1247 		if (f) {
1248 			if (do_xauth)
1249 				fprintf(f, "%s %s\n", s->auth_proto,
1250 				    s->auth_data);
1251 			pclose(f);
1252 		} else
1253 			fprintf(stderr, "Could not run %s\n",
1254 			    user_rc);
1255 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1256 		if (debug_flag)
1257 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1258 			    _PATH_SSH_SYSTEM_RC);
1259 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1260 		if (f) {
1261 			if (do_xauth)
1262 				fprintf(f, "%s %s\n", s->auth_proto,
1263 				    s->auth_data);
1264 			pclose(f);
1265 		} else
1266 			fprintf(stderr, "Could not run %s\n",
1267 			    _PATH_SSH_SYSTEM_RC);
1268 	} else if (do_xauth && options.xauth_location != NULL) {
1269 		/* Add authority data to .Xauthority if appropriate. */
1270 		if (debug_flag) {
1271 			fprintf(stderr,
1272 			    "Running %.500s remove %.100s\n",
1273 			    options.xauth_location, s->auth_display);
1274 			fprintf(stderr,
1275 			    "%.500s add %.100s %.100s %.100s\n",
1276 			    options.xauth_location, s->auth_display,
1277 			    s->auth_proto, s->auth_data);
1278 		}
1279 		if (xasprintf(&cmd, "%s -q -", options.xauth_location) == -1)
1280 			fatal_f("xasprintf: %s", strerror(errno));
1281 		f = popen(cmd, "w");
1282 		if (f) {
1283 			fprintf(f, "remove %s\n",
1284 			    s->auth_display);
1285 			fprintf(f, "add %s %s %s\n",
1286 			    s->auth_display, s->auth_proto,
1287 			    s->auth_data);
1288 			pclose(f);
1289 		} else {
1290 			fprintf(stderr, "Could not run %s\n",
1291 			    cmd);
1292 		}
1293 	}
1294 	free(cmd);
1295 	free(user_rc);
1296 }
1297 
1298 static void
1299 do_nologin(struct passwd *pw)
1300 {
1301 	FILE *f = NULL;
1302 	const char *nl;
1303 	char buf[1024], *def_nl = _PATH_NOLOGIN;
1304 	struct stat sb;
1305 
1306 #ifdef HAVE_LOGIN_CAP
1307 	if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1308 		return;
1309 	nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1310 #else
1311 	if (pw->pw_uid == 0)
1312 		return;
1313 	nl = def_nl;
1314 #endif
1315 	if (stat(nl, &sb) == -1)
1316 		return;
1317 
1318 	/* /etc/nologin exists.  Print its contents if we can and exit. */
1319 	logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1320 	if ((f = fopen(nl, "r")) != NULL) {
1321 		while (fgets(buf, sizeof(buf), f))
1322 			fputs(buf, stderr);
1323 		fclose(f);
1324 	}
1325 	exit(254);
1326 }
1327 
1328 /*
1329  * Chroot into a directory after checking it for safety: all path components
1330  * must be root-owned directories with strict permissions.
1331  */
1332 static void
1333 safely_chroot(const char *path, uid_t uid)
1334 {
1335 	const char *cp;
1336 	char component[PATH_MAX];
1337 	struct stat st;
1338 
1339 	if (!path_absolute(path))
1340 		fatal("chroot path does not begin at root");
1341 	if (strlen(path) >= sizeof(component))
1342 		fatal("chroot path too long");
1343 
1344 	/*
1345 	 * Descend the path, checking that each component is a
1346 	 * root-owned directory with strict permissions.
1347 	 */
1348 	for (cp = path; cp != NULL;) {
1349 		if ((cp = strchr(cp, '/')) == NULL)
1350 			strlcpy(component, path, sizeof(component));
1351 		else {
1352 			cp++;
1353 			memcpy(component, path, cp - path);
1354 			component[cp - path] = '\0';
1355 		}
1356 
1357 		debug3_f("checking '%s'", component);
1358 
1359 		if (stat(component, &st) != 0)
1360 			fatal_f("stat(\"%s\"): %s",
1361 			    component, strerror(errno));
1362 		if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1363 			fatal("bad ownership or modes for chroot "
1364 			    "directory %s\"%s\"",
1365 			    cp == NULL ? "" : "component ", component);
1366 		if (!S_ISDIR(st.st_mode))
1367 			fatal("chroot path %s\"%s\" is not a directory",
1368 			    cp == NULL ? "" : "component ", component);
1369 
1370 	}
1371 
1372 	if (chdir(path) == -1)
1373 		fatal("Unable to chdir to chroot path \"%s\": "
1374 		    "%s", path, strerror(errno));
1375 	if (chroot(path) == -1)
1376 		fatal("chroot(\"%s\"): %s", path, strerror(errno));
1377 	if (chdir("/") == -1)
1378 		fatal_f("chdir(/) after chroot: %s", strerror(errno));
1379 	verbose("Changed root directory to \"%s\"", path);
1380 }
1381 
1382 /* Set login name, uid, gid, and groups. */
1383 void
1384 do_setusercontext(struct passwd *pw)
1385 {
1386 	char uidstr[32], *chroot_path, *tmp;
1387 
1388 	platform_setusercontext(pw);
1389 
1390 	if (platform_privileged_uidswap()) {
1391 #ifdef HAVE_LOGIN_CAP
1392 		if (setusercontext(lc, pw, pw->pw_uid,
1393 		    (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1394 			perror("unable to set user context");
1395 			exit(1);
1396 		}
1397 #else
1398 		if (setlogin(pw->pw_name) < 0)
1399 			error("setlogin failed: %s", strerror(errno));
1400 		if (setgid(pw->pw_gid) < 0) {
1401 			perror("setgid");
1402 			exit(1);
1403 		}
1404 		/* Initialize the group list. */
1405 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1406 			perror("initgroups");
1407 			exit(1);
1408 		}
1409 		endgrent();
1410 #endif
1411 
1412 		platform_setusercontext_post_groups(pw);
1413 
1414 		if (!in_chroot && options.chroot_directory != NULL &&
1415 		    strcasecmp(options.chroot_directory, "none") != 0) {
1416 			tmp = tilde_expand_filename(options.chroot_directory,
1417 			    pw->pw_uid);
1418 			snprintf(uidstr, sizeof(uidstr), "%llu",
1419 			    (unsigned long long)pw->pw_uid);
1420 			chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1421 			    "u", pw->pw_name, "U", uidstr, (char *)NULL);
1422 			safely_chroot(chroot_path, pw->pw_uid);
1423 			free(tmp);
1424 			free(chroot_path);
1425 			/* Make sure we don't attempt to chroot again */
1426 			free(options.chroot_directory);
1427 			options.chroot_directory = NULL;
1428 			in_chroot = 1;
1429 		}
1430 
1431 #ifdef HAVE_LOGIN_CAP
1432 		if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1433 			perror("unable to set user context (setuser)");
1434 			exit(1);
1435 		}
1436 		/*
1437 		 * FreeBSD's setusercontext() will not apply the user's
1438 		 * own umask setting unless running with the user's UID.
1439 		 */
1440 		(void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1441 #else
1442 # ifdef USE_LIBIAF
1443 		/*
1444 		 * In a chroot environment, the set_id() will always fail;
1445 		 * typically because of the lack of necessary authentication
1446 		 * services and runtime such as ./usr/lib/libiaf.so,
1447 		 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1448 		 * internal sftp chroot case.  We'll lose auditing and ACLs but
1449 		 * permanently_set_uid will take care of the rest.
1450 		 */
1451 		if (!in_chroot && set_id(pw->pw_name) != 0)
1452 			fatal("set_id(%s) Failed", pw->pw_name);
1453 # endif /* USE_LIBIAF */
1454 		/* Permanently switch to the desired uid. */
1455 		permanently_set_uid(pw);
1456 #endif
1457 	} else if (options.chroot_directory != NULL &&
1458 	    strcasecmp(options.chroot_directory, "none") != 0) {
1459 		fatal("server lacks privileges to chroot to ChrootDirectory");
1460 	}
1461 
1462 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1463 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1464 }
1465 
1466 static void
1467 do_pwchange(Session *s)
1468 {
1469 	fflush(NULL);
1470 	fprintf(stderr, "WARNING: Your password has expired.\n");
1471 	if (s->ttyfd != -1) {
1472 		fprintf(stderr,
1473 		    "You must change your password now and login again!\n");
1474 #ifdef WITH_SELINUX
1475 		setexeccon(NULL);
1476 #endif
1477 #ifdef PASSWD_NEEDS_USERNAME
1478 		execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1479 		    (char *)NULL);
1480 #else
1481 		execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1482 #endif
1483 		perror("passwd");
1484 	} else {
1485 		fprintf(stderr,
1486 		    "Password change required but no TTY available.\n");
1487 	}
1488 	exit(1);
1489 }
1490 
1491 static void
1492 child_close_fds(struct ssh *ssh)
1493 {
1494 	extern int auth_sock;
1495 
1496 	if (auth_sock != -1) {
1497 		close(auth_sock);
1498 		auth_sock = -1;
1499 	}
1500 
1501 	if (ssh_packet_get_connection_in(ssh) ==
1502 	    ssh_packet_get_connection_out(ssh))
1503 		close(ssh_packet_get_connection_in(ssh));
1504 	else {
1505 		close(ssh_packet_get_connection_in(ssh));
1506 		close(ssh_packet_get_connection_out(ssh));
1507 	}
1508 	/*
1509 	 * Close all descriptors related to channels.  They will still remain
1510 	 * open in the parent.
1511 	 */
1512 	/* XXX better use close-on-exec? -markus */
1513 	channel_close_all(ssh);
1514 
1515 	/*
1516 	 * Close any extra file descriptors.  Note that there may still be
1517 	 * descriptors left by system functions.  They will be closed later.
1518 	 */
1519 	endpwent();
1520 
1521 	/* Stop directing logs to a high-numbered fd before we close it */
1522 	log_redirect_stderr_to(NULL);
1523 
1524 	/*
1525 	 * Close any extra open file descriptors so that we don't have them
1526 	 * hanging around in clients.  Note that we want to do this after
1527 	 * initgroups, because at least on Solaris 2.3 it leaves file
1528 	 * descriptors open.
1529 	 */
1530 	closefrom(STDERR_FILENO + 1);
1531 }
1532 
1533 /*
1534  * Performs common processing for the child, such as setting up the
1535  * environment, closing extra file descriptors, setting the user and group
1536  * ids, and executing the command or shell.
1537  */
1538 #define ARGV_MAX 10
1539 void
1540 do_child(struct ssh *ssh, Session *s, const char *command)
1541 {
1542 	extern char **environ;
1543 	char **env, *argv[ARGV_MAX], remote_id[512];
1544 	const char *shell, *shell0;
1545 	struct passwd *pw = s->pw;
1546 	int r = 0;
1547 
1548 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1549 
1550 	/* remove hostkey from the child's memory */
1551 	destroy_sensitive_data();
1552 	ssh_packet_clear_keys(ssh);
1553 
1554 	/* Force a password change */
1555 	if (s->authctxt->force_pwchange) {
1556 		do_setusercontext(pw);
1557 		child_close_fds(ssh);
1558 		do_pwchange(s);
1559 		exit(1);
1560 	}
1561 
1562 	/*
1563 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1564 	 * switch, so we let login(1) to this for us.
1565 	 */
1566 #ifdef HAVE_OSF_SIA
1567 	session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1568 	if (!check_quietlogin(s, command))
1569 		do_motd();
1570 #else /* HAVE_OSF_SIA */
1571 	/* When PAM is enabled we rely on it to do the nologin check */
1572 	if (!options.use_pam)
1573 		do_nologin(pw);
1574 	do_setusercontext(pw);
1575 	/*
1576 	 * PAM session modules in do_setusercontext may have
1577 	 * generated messages, so if this in an interactive
1578 	 * login then display them too.
1579 	 */
1580 	if (!check_quietlogin(s, command))
1581 		display_loginmsg();
1582 #endif /* HAVE_OSF_SIA */
1583 
1584 #ifdef USE_PAM
1585 	if (options.use_pam && !is_pam_session_open()) {
1586 		debug3("PAM session not opened, exiting");
1587 		display_loginmsg();
1588 		exit(254);
1589 	}
1590 #endif
1591 
1592 	/*
1593 	 * Get the shell from the password data.  An empty shell field is
1594 	 * legal, and means /bin/sh.
1595 	 */
1596 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1597 
1598 	/*
1599 	 * Make sure $SHELL points to the shell from the password file,
1600 	 * even if shell is overridden from login.conf
1601 	 */
1602 	env = do_setup_env(ssh, s, shell);
1603 
1604 #ifdef HAVE_LOGIN_CAP
1605 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1606 #endif
1607 
1608 	/*
1609 	 * Close the connection descriptors; note that this is the child, and
1610 	 * the server will still have the socket open, and it is important
1611 	 * that we do not shutdown it.  Note that the descriptors cannot be
1612 	 * closed before building the environment, as we call
1613 	 * ssh_remote_ipaddr there.
1614 	 */
1615 	child_close_fds(ssh);
1616 
1617 	/*
1618 	 * Must take new environment into use so that .ssh/rc,
1619 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1620 	 */
1621 	environ = env;
1622 
1623 #if defined(KRB5) && defined(USE_AFS)
1624 	/*
1625 	 * At this point, we check to see if AFS is active and if we have
1626 	 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1627 	 * if we can (and need to) extend the ticket into an AFS token. If
1628 	 * we don't do this, we run into potential problems if the user's
1629 	 * home directory is in AFS and it's not world-readable.
1630 	 */
1631 
1632 	if (options.kerberos_get_afs_token && k_hasafs() &&
1633 	    (s->authctxt->krb5_ctx != NULL)) {
1634 		char cell[64];
1635 
1636 		debug("Getting AFS token");
1637 
1638 		k_setpag();
1639 
1640 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1641 			krb5_afslog(s->authctxt->krb5_ctx,
1642 			    s->authctxt->krb5_fwd_ccache, cell, NULL);
1643 
1644 		krb5_afslog_home(s->authctxt->krb5_ctx,
1645 		    s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1646 	}
1647 #endif
1648 
1649 	/* Change current directory to the user's home directory. */
1650 	if (chdir(pw->pw_dir) == -1) {
1651 		/* Suppress missing homedir warning for chroot case */
1652 #ifdef HAVE_LOGIN_CAP
1653 		r = login_getcapbool(lc, "requirehome", 0);
1654 #endif
1655 		if (r || !in_chroot) {
1656 			fprintf(stderr, "Could not chdir to home "
1657 			    "directory %s: %s\n", pw->pw_dir,
1658 			    strerror(errno));
1659 		}
1660 		if (r)
1661 			exit(1);
1662 	}
1663 
1664 	closefrom(STDERR_FILENO + 1);
1665 
1666 	do_rc_files(ssh, s, shell);
1667 
1668 	/* restore SIGPIPE for child */
1669 	ssh_signal(SIGPIPE, SIG_DFL);
1670 
1671 	if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1672 		error("Connection from %s: refusing non-sftp session",
1673 		    remote_id);
1674 		printf("This service allows sftp connections only.\n");
1675 		fflush(NULL);
1676 		exit(1);
1677 	} else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1678 		extern int optind, optreset;
1679 		int i;
1680 		char *p, *args;
1681 
1682 		setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1683 		args = xstrdup(command ? command : "sftp-server");
1684 		for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1685 			if (i < ARGV_MAX - 1)
1686 				argv[i++] = p;
1687 		argv[i] = NULL;
1688 		optind = optreset = 1;
1689 		__progname = argv[0];
1690 #ifdef WITH_SELINUX
1691 		ssh_selinux_change_context("sftpd_t");
1692 #endif
1693 		exit(sftp_server_main(i, argv, s->pw));
1694 	}
1695 
1696 	fflush(NULL);
1697 
1698 	/* Get the last component of the shell name. */
1699 	if ((shell0 = strrchr(shell, '/')) != NULL)
1700 		shell0++;
1701 	else
1702 		shell0 = shell;
1703 
1704 	/*
1705 	 * If we have no command, execute the shell.  In this case, the shell
1706 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1707 	 * this is a login shell.
1708 	 */
1709 	if (!command) {
1710 		char argv0[256];
1711 
1712 		/* Start the shell.  Set initial character to '-'. */
1713 		argv0[0] = '-';
1714 
1715 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1716 		    >= sizeof(argv0) - 1) {
1717 			errno = EINVAL;
1718 			perror(shell);
1719 			exit(1);
1720 		}
1721 
1722 		/* Execute the shell. */
1723 		argv[0] = argv0;
1724 		argv[1] = NULL;
1725 		execve(shell, argv, env);
1726 
1727 		/* Executing the shell failed. */
1728 		perror(shell);
1729 		exit(1);
1730 	}
1731 	/*
1732 	 * Execute the command using the user's shell.  This uses the -c
1733 	 * option to execute the command.
1734 	 */
1735 	argv[0] = (char *) shell0;
1736 	argv[1] = "-c";
1737 	argv[2] = (char *) command;
1738 	argv[3] = NULL;
1739 	execve(shell, argv, env);
1740 	perror(shell);
1741 	exit(1);
1742 }
1743 
1744 void
1745 session_unused(int id)
1746 {
1747 	debug3_f("session id %d unused", id);
1748 	if (id >= options.max_sessions ||
1749 	    id >= sessions_nalloc) {
1750 		fatal_f("insane session id %d (max %d nalloc %d)",
1751 		    id, options.max_sessions, sessions_nalloc);
1752 	}
1753 	memset(&sessions[id], 0, sizeof(*sessions));
1754 	sessions[id].self = id;
1755 	sessions[id].used = 0;
1756 	sessions[id].chanid = -1;
1757 	sessions[id].ptyfd = -1;
1758 	sessions[id].ttyfd = -1;
1759 	sessions[id].ptymaster = -1;
1760 	sessions[id].x11_chanids = NULL;
1761 	sessions[id].next_unused = sessions_first_unused;
1762 	sessions_first_unused = id;
1763 }
1764 
1765 Session *
1766 session_new(void)
1767 {
1768 	Session *s, *tmp;
1769 
1770 	if (sessions_first_unused == -1) {
1771 		if (sessions_nalloc >= options.max_sessions)
1772 			return NULL;
1773 		debug2_f("allocate (allocated %d max %d)",
1774 		    sessions_nalloc, options.max_sessions);
1775 		tmp = xrecallocarray(sessions, sessions_nalloc,
1776 		    sessions_nalloc + 1, sizeof(*sessions));
1777 		if (tmp == NULL) {
1778 			error_f("cannot allocate %d sessions",
1779 			    sessions_nalloc + 1);
1780 			return NULL;
1781 		}
1782 		sessions = tmp;
1783 		session_unused(sessions_nalloc++);
1784 	}
1785 
1786 	if (sessions_first_unused >= sessions_nalloc ||
1787 	    sessions_first_unused < 0) {
1788 		fatal_f("insane first_unused %d max %d nalloc %d",
1789 		    sessions_first_unused, options.max_sessions,
1790 		    sessions_nalloc);
1791 	}
1792 
1793 	s = &sessions[sessions_first_unused];
1794 	if (s->used)
1795 		fatal_f("session %d already used", sessions_first_unused);
1796 	sessions_first_unused = s->next_unused;
1797 	s->used = 1;
1798 	s->next_unused = -1;
1799 	debug("session_new: session %d", s->self);
1800 
1801 	return s;
1802 }
1803 
1804 static void
1805 session_dump(void)
1806 {
1807 	int i;
1808 	for (i = 0; i < sessions_nalloc; i++) {
1809 		Session *s = &sessions[i];
1810 
1811 		debug("dump: used %d next_unused %d session %d "
1812 		    "channel %d pid %ld",
1813 		    s->used,
1814 		    s->next_unused,
1815 		    s->self,
1816 		    s->chanid,
1817 		    (long)s->pid);
1818 	}
1819 }
1820 
1821 int
1822 session_open(Authctxt *authctxt, int chanid)
1823 {
1824 	Session *s = session_new();
1825 	debug("session_open: channel %d", chanid);
1826 	if (s == NULL) {
1827 		error("no more sessions");
1828 		return 0;
1829 	}
1830 	s->authctxt = authctxt;
1831 	s->pw = authctxt->pw;
1832 	if (s->pw == NULL || !authctxt->valid)
1833 		fatal("no user for session %d", s->self);
1834 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1835 	s->chanid = chanid;
1836 	return 1;
1837 }
1838 
1839 Session *
1840 session_by_tty(char *tty)
1841 {
1842 	int i;
1843 	for (i = 0; i < sessions_nalloc; i++) {
1844 		Session *s = &sessions[i];
1845 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1846 			debug("session_by_tty: session %d tty %s", i, tty);
1847 			return s;
1848 		}
1849 	}
1850 	debug("session_by_tty: unknown tty %.100s", tty);
1851 	session_dump();
1852 	return NULL;
1853 }
1854 
1855 static Session *
1856 session_by_channel(int id)
1857 {
1858 	int i;
1859 	for (i = 0; i < sessions_nalloc; i++) {
1860 		Session *s = &sessions[i];
1861 		if (s->used && s->chanid == id) {
1862 			debug("session_by_channel: session %d channel %d",
1863 			    i, id);
1864 			return s;
1865 		}
1866 	}
1867 	debug("session_by_channel: unknown channel %d", id);
1868 	session_dump();
1869 	return NULL;
1870 }
1871 
1872 static Session *
1873 session_by_x11_channel(int id)
1874 {
1875 	int i, j;
1876 
1877 	for (i = 0; i < sessions_nalloc; i++) {
1878 		Session *s = &sessions[i];
1879 
1880 		if (s->x11_chanids == NULL || !s->used)
1881 			continue;
1882 		for (j = 0; s->x11_chanids[j] != -1; j++) {
1883 			if (s->x11_chanids[j] == id) {
1884 				debug("session_by_x11_channel: session %d "
1885 				    "channel %d", s->self, id);
1886 				return s;
1887 			}
1888 		}
1889 	}
1890 	debug("session_by_x11_channel: unknown channel %d", id);
1891 	session_dump();
1892 	return NULL;
1893 }
1894 
1895 static Session *
1896 session_by_pid(pid_t pid)
1897 {
1898 	int i;
1899 	debug("session_by_pid: pid %ld", (long)pid);
1900 	for (i = 0; i < sessions_nalloc; i++) {
1901 		Session *s = &sessions[i];
1902 		if (s->used && s->pid == pid)
1903 			return s;
1904 	}
1905 	error("session_by_pid: unknown pid %ld", (long)pid);
1906 	session_dump();
1907 	return NULL;
1908 }
1909 
1910 static int
1911 session_window_change_req(struct ssh *ssh, Session *s)
1912 {
1913 	int r;
1914 
1915 	if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1916 	    (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1917 	    (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1918 	    (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 ||
1919 	    (r = sshpkt_get_end(ssh)) != 0)
1920 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1921 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1922 	return 1;
1923 }
1924 
1925 static int
1926 session_pty_req(struct ssh *ssh, Session *s)
1927 {
1928 	int r;
1929 
1930 	if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1931 		debug("Allocating a pty not permitted for this connection.");
1932 		return 0;
1933 	}
1934 	if (s->ttyfd != -1) {
1935 		ssh_packet_disconnect(ssh, "Protocol error: you already have a pty.");
1936 		return 0;
1937 	}
1938 
1939 	if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 ||
1940 	    (r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1941 	    (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1942 	    (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1943 	    (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0)
1944 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1945 
1946 	if (strcmp(s->term, "") == 0) {
1947 		free(s->term);
1948 		s->term = NULL;
1949 	}
1950 
1951 	/* Allocate a pty and open it. */
1952 	debug("Allocating pty.");
1953 	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1954 	    sizeof(s->tty)))) {
1955 		free(s->term);
1956 		s->term = NULL;
1957 		s->ptyfd = -1;
1958 		s->ttyfd = -1;
1959 		error("session_pty_req: session %d alloc failed", s->self);
1960 		return 0;
1961 	}
1962 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1963 
1964 	ssh_tty_parse_modes(ssh, s->ttyfd);
1965 
1966 	if ((r = sshpkt_get_end(ssh)) != 0)
1967 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1968 
1969 	if (!use_privsep)
1970 		pty_setowner(s->pw, s->tty);
1971 
1972 	/* Set window size from the packet. */
1973 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1974 
1975 	session_proctitle(s);
1976 	return 1;
1977 }
1978 
1979 static int
1980 session_subsystem_req(struct ssh *ssh, Session *s)
1981 {
1982 	struct stat st;
1983 	int r, success = 0;
1984 	char *prog, *cmd;
1985 	u_int i;
1986 
1987 	if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 ||
1988 	    (r = sshpkt_get_end(ssh)) != 0)
1989 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1990 	debug2("subsystem request for %.100s by user %s", s->subsys,
1991 	    s->pw->pw_name);
1992 
1993 	for (i = 0; i < options.num_subsystems; i++) {
1994 		if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1995 			prog = options.subsystem_command[i];
1996 			cmd = options.subsystem_args[i];
1997 			if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1998 				s->is_subsystem = SUBSYSTEM_INT_SFTP;
1999 				debug("subsystem: %s", prog);
2000 			} else {
2001 				if (stat(prog, &st) == -1)
2002 					debug("subsystem: cannot stat %s: %s",
2003 					    prog, strerror(errno));
2004 				s->is_subsystem = SUBSYSTEM_EXT;
2005 				debug("subsystem: exec() %s", cmd);
2006 			}
2007 			success = do_exec(ssh, s, cmd) == 0;
2008 			break;
2009 		}
2010 	}
2011 
2012 	if (!success)
2013 		logit("subsystem request for %.100s by user %s failed, "
2014 		    "subsystem not found", s->subsys, s->pw->pw_name);
2015 
2016 	return success;
2017 }
2018 
2019 static int
2020 session_x11_req(struct ssh *ssh, Session *s)
2021 {
2022 	int r, success;
2023 	u_char single_connection = 0;
2024 
2025 	if (s->auth_proto != NULL || s->auth_data != NULL) {
2026 		error("session_x11_req: session %d: "
2027 		    "x11 forwarding already active", s->self);
2028 		return 0;
2029 	}
2030 	if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 ||
2031 	    (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 ||
2032 	    (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 ||
2033 	    (r = sshpkt_get_u32(ssh, &s->screen)) != 0 ||
2034 	    (r = sshpkt_get_end(ssh)) != 0)
2035 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2036 
2037 	s->single_connection = single_connection;
2038 
2039 	if (xauth_valid_string(s->auth_proto) &&
2040 	    xauth_valid_string(s->auth_data))
2041 		success = session_setup_x11fwd(ssh, s);
2042 	else {
2043 		success = 0;
2044 		error("Invalid X11 forwarding data");
2045 	}
2046 	if (!success) {
2047 		free(s->auth_proto);
2048 		free(s->auth_data);
2049 		s->auth_proto = NULL;
2050 		s->auth_data = NULL;
2051 	}
2052 	return success;
2053 }
2054 
2055 static int
2056 session_shell_req(struct ssh *ssh, Session *s)
2057 {
2058 	int r;
2059 
2060 	if ((r = sshpkt_get_end(ssh)) != 0)
2061 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2062 	return do_exec(ssh, s, NULL) == 0;
2063 }
2064 
2065 static int
2066 session_exec_req(struct ssh *ssh, Session *s)
2067 {
2068 	u_int success;
2069 	int r;
2070 	char *command = NULL;
2071 
2072 	if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 ||
2073 	    (r = sshpkt_get_end(ssh)) != 0)
2074 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2075 
2076 	success = do_exec(ssh, s, command) == 0;
2077 	free(command);
2078 	return success;
2079 }
2080 
2081 static int
2082 session_break_req(struct ssh *ssh, Session *s)
2083 {
2084 	int r;
2085 
2086 	if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */
2087 	    (r = sshpkt_get_end(ssh)) != 0)
2088 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2089 
2090 	if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) == -1)
2091 		return 0;
2092 	return 1;
2093 }
2094 
2095 static int
2096 session_env_req(struct ssh *ssh, Session *s)
2097 {
2098 	char *name, *val;
2099 	u_int i;
2100 	int r;
2101 
2102 	if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
2103 	    (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 ||
2104 	    (r = sshpkt_get_end(ssh)) != 0)
2105 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2106 
2107 	/* Don't set too many environment variables */
2108 	if (s->num_env > 128) {
2109 		debug2("Ignoring env request %s: too many env vars", name);
2110 		goto fail;
2111 	}
2112 
2113 	for (i = 0; i < options.num_accept_env; i++) {
2114 		if (match_pattern(name, options.accept_env[i])) {
2115 			debug2("Setting env %d: %s=%s", s->num_env, name, val);
2116 			s->env = xrecallocarray(s->env, s->num_env,
2117 			    s->num_env + 1, sizeof(*s->env));
2118 			s->env[s->num_env].name = name;
2119 			s->env[s->num_env].val = val;
2120 			s->num_env++;
2121 			return (1);
2122 		}
2123 	}
2124 	debug2("Ignoring env request %s: disallowed name", name);
2125 
2126  fail:
2127 	free(name);
2128 	free(val);
2129 	return (0);
2130 }
2131 
2132 /*
2133  * Conversion of signals from ssh channel request names.
2134  * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
2135  * local extension.
2136  */
2137 static int
2138 name2sig(char *name)
2139 {
2140 #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
2141 	SSH_SIG(HUP);
2142 	SSH_SIG(INT);
2143 	SSH_SIG(KILL);
2144 	SSH_SIG(QUIT);
2145 	SSH_SIG(TERM);
2146 	SSH_SIG(USR1);
2147 	SSH_SIG(USR2);
2148 #undef	SSH_SIG
2149 #ifdef SIGINFO
2150 	if (strcmp(name, "INFO@openssh.com") == 0)
2151 		return SIGINFO;
2152 #endif
2153 	return -1;
2154 }
2155 
2156 static int
2157 session_signal_req(struct ssh *ssh, Session *s)
2158 {
2159 	char *signame = NULL;
2160 	int r, sig, success = 0;
2161 
2162 	if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
2163 	    (r = sshpkt_get_end(ssh)) != 0) {
2164 		error_fr(r, "parse");
2165 		goto out;
2166 	}
2167 	if ((sig = name2sig(signame)) == -1) {
2168 		error_f("unsupported signal \"%s\"", signame);
2169 		goto out;
2170 	}
2171 	if (s->pid <= 0) {
2172 		error_f("no pid for session %d", s->self);
2173 		goto out;
2174 	}
2175 	if (s->forced || s->is_subsystem) {
2176 		error_f("refusing to send signal %s to %s session",
2177 		    signame, s->forced ? "forced-command" : "subsystem");
2178 		goto out;
2179 	}
2180 	if (!use_privsep || mm_is_monitor()) {
2181 		error_f("session signalling requires privilege separation");
2182 		goto out;
2183 	}
2184 
2185 	debug_f("signal %s, killpg(%ld, %d)", signame, (long)s->pid, sig);
2186 	temporarily_use_uid(s->pw);
2187 	r = killpg(s->pid, sig);
2188 	restore_uid();
2189 	if (r != 0) {
2190 		error_f("killpg(%ld, %d): %s", (long)s->pid,
2191 		    sig, strerror(errno));
2192 		goto out;
2193 	}
2194 
2195 	/* success */
2196 	success = 1;
2197  out:
2198 	free(signame);
2199 	return success;
2200 }
2201 
2202 static int
2203 session_auth_agent_req(struct ssh *ssh, Session *s)
2204 {
2205 	static int called = 0;
2206 	int r;
2207 
2208 	if ((r = sshpkt_get_end(ssh)) != 0)
2209 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2210 	if (!auth_opts->permit_agent_forwarding_flag ||
2211 	    !options.allow_agent_forwarding) {
2212 		debug_f("agent forwarding disabled");
2213 		return 0;
2214 	}
2215 	if (called) {
2216 		return 0;
2217 	} else {
2218 		called = 1;
2219 		return auth_input_request_forwarding(ssh, s->pw);
2220 	}
2221 }
2222 
2223 int
2224 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2225 {
2226 	int success = 0;
2227 	Session *s;
2228 
2229 	if ((s = session_by_channel(c->self)) == NULL) {
2230 		logit_f("no session %d req %.100s", c->self, rtype);
2231 		return 0;
2232 	}
2233 	debug_f("session %d req %s", s->self, rtype);
2234 
2235 	/*
2236 	 * a session is in LARVAL state until a shell, a command
2237 	 * or a subsystem is executed
2238 	 */
2239 	if (c->type == SSH_CHANNEL_LARVAL) {
2240 		if (strcmp(rtype, "shell") == 0) {
2241 			success = session_shell_req(ssh, s);
2242 		} else if (strcmp(rtype, "exec") == 0) {
2243 			success = session_exec_req(ssh, s);
2244 		} else if (strcmp(rtype, "pty-req") == 0) {
2245 			success = session_pty_req(ssh, s);
2246 		} else if (strcmp(rtype, "x11-req") == 0) {
2247 			success = session_x11_req(ssh, s);
2248 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2249 			success = session_auth_agent_req(ssh, s);
2250 		} else if (strcmp(rtype, "subsystem") == 0) {
2251 			success = session_subsystem_req(ssh, s);
2252 		} else if (strcmp(rtype, "env") == 0) {
2253 			success = session_env_req(ssh, s);
2254 		}
2255 	}
2256 	if (strcmp(rtype, "window-change") == 0) {
2257 		success = session_window_change_req(ssh, s);
2258 	} else if (strcmp(rtype, "break") == 0) {
2259 		success = session_break_req(ssh, s);
2260 	} else if (strcmp(rtype, "signal") == 0) {
2261 		success = session_signal_req(ssh, s);
2262 	}
2263 
2264 	return success;
2265 }
2266 
2267 void
2268 session_set_fds(struct ssh *ssh, Session *s,
2269     int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2270 {
2271 	/*
2272 	 * now that have a child and a pipe to the child,
2273 	 * we can activate our channel and register the fd's
2274 	 */
2275 	if (s->chanid == -1)
2276 		fatal("no channel for session %d", s->self);
2277 	channel_set_fds(ssh, s->chanid,
2278 	    fdout, fdin, fderr,
2279 	    ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2280 	    1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2281 }
2282 
2283 /*
2284  * Function to perform pty cleanup. Also called if we get aborted abnormally
2285  * (e.g., due to a dropped connection).
2286  */
2287 void
2288 session_pty_cleanup2(Session *s)
2289 {
2290 	if (s == NULL) {
2291 		error_f("no session");
2292 		return;
2293 	}
2294 	if (s->ttyfd == -1)
2295 		return;
2296 
2297 	debug_f("session %d release %s", s->self, s->tty);
2298 
2299 	/* Record that the user has logged out. */
2300 	if (s->pid != 0)
2301 		record_logout(s->pid, s->tty, s->pw->pw_name);
2302 
2303 	/* Release the pseudo-tty. */
2304 	if (getuid() == 0)
2305 		pty_release(s->tty);
2306 
2307 	/*
2308 	 * Close the server side of the socket pairs.  We must do this after
2309 	 * the pty cleanup, so that another process doesn't get this pty
2310 	 * while we're still cleaning up.
2311 	 */
2312 	if (s->ptymaster != -1 && close(s->ptymaster) == -1)
2313 		error("close(s->ptymaster/%d): %s",
2314 		    s->ptymaster, strerror(errno));
2315 
2316 	/* unlink pty from session */
2317 	s->ttyfd = -1;
2318 }
2319 
2320 void
2321 session_pty_cleanup(Session *s)
2322 {
2323 	PRIVSEP(session_pty_cleanup2(s));
2324 }
2325 
2326 static char *
2327 sig2name(int sig)
2328 {
2329 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2330 	SSH_SIG(ABRT);
2331 	SSH_SIG(ALRM);
2332 	SSH_SIG(FPE);
2333 	SSH_SIG(HUP);
2334 	SSH_SIG(ILL);
2335 	SSH_SIG(INT);
2336 	SSH_SIG(KILL);
2337 	SSH_SIG(PIPE);
2338 	SSH_SIG(QUIT);
2339 	SSH_SIG(SEGV);
2340 	SSH_SIG(TERM);
2341 	SSH_SIG(USR1);
2342 	SSH_SIG(USR2);
2343 #undef	SSH_SIG
2344 	return "SIG@openssh.com";
2345 }
2346 
2347 static void
2348 session_close_x11(struct ssh *ssh, int id)
2349 {
2350 	Channel *c;
2351 
2352 	if ((c = channel_by_id(ssh, id)) == NULL) {
2353 		debug_f("x11 channel %d missing", id);
2354 	} else {
2355 		/* Detach X11 listener */
2356 		debug_f("detach x11 channel %d", id);
2357 		channel_cancel_cleanup(ssh, id);
2358 		if (c->ostate != CHAN_OUTPUT_CLOSED)
2359 			chan_mark_dead(ssh, c);
2360 	}
2361 }
2362 
2363 static void
2364 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2365 {
2366 	Session *s;
2367 	u_int i;
2368 
2369 	debug3_f("channel %d", id);
2370 	channel_cancel_cleanup(ssh, id);
2371 	if ((s = session_by_x11_channel(id)) == NULL)
2372 		fatal_f("no x11 channel %d", id);
2373 	for (i = 0; s->x11_chanids[i] != -1; i++) {
2374 		debug_f("session %d: closing channel %d",
2375 		    s->self, s->x11_chanids[i]);
2376 		/*
2377 		 * The channel "id" is already closing, but make sure we
2378 		 * close all of its siblings.
2379 		 */
2380 		if (s->x11_chanids[i] != id)
2381 			session_close_x11(ssh, s->x11_chanids[i]);
2382 	}
2383 	free(s->x11_chanids);
2384 	s->x11_chanids = NULL;
2385 	free(s->display);
2386 	s->display = NULL;
2387 	free(s->auth_proto);
2388 	s->auth_proto = NULL;
2389 	free(s->auth_data);
2390 	s->auth_data = NULL;
2391 	free(s->auth_display);
2392 	s->auth_display = NULL;
2393 }
2394 
2395 static void
2396 session_exit_message(struct ssh *ssh, Session *s, int status)
2397 {
2398 	Channel *c;
2399 	int r;
2400 
2401 	if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2402 		fatal_f("session %d: no channel %d", s->self, s->chanid);
2403 	debug_f("session %d channel %d pid %ld",
2404 	    s->self, s->chanid, (long)s->pid);
2405 
2406 	if (WIFEXITED(status)) {
2407 		channel_request_start(ssh, s->chanid, "exit-status", 0);
2408 		if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 ||
2409 		    (r = sshpkt_send(ssh)) != 0)
2410 			sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2411 	} else if (WIFSIGNALED(status)) {
2412 		channel_request_start(ssh, s->chanid, "exit-signal", 0);
2413 #ifndef WCOREDUMP
2414 # define WCOREDUMP(x) (0)
2415 #endif
2416 		if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 ||
2417 		    (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 ||
2418 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2419 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2420 		    (r = sshpkt_send(ssh)) != 0)
2421 			sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2422 	} else {
2423 		/* Some weird exit cause.  Just exit. */
2424 		ssh_packet_disconnect(ssh, "wait returned status %04x.", status);
2425 	}
2426 
2427 	/* disconnect channel */
2428 	debug_f("release channel %d", s->chanid);
2429 
2430 	/*
2431 	 * Adjust cleanup callback attachment to send close messages when
2432 	 * the channel gets EOF. The session will be then be closed
2433 	 * by session_close_by_channel when the child sessions close their fds.
2434 	 */
2435 	channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2436 
2437 	/*
2438 	 * emulate a write failure with 'chan_write_failed', nobody will be
2439 	 * interested in data we write.
2440 	 * Note that we must not call 'chan_read_failed', since there could
2441 	 * be some more data waiting in the pipe.
2442 	 */
2443 	if (c->ostate != CHAN_OUTPUT_CLOSED)
2444 		chan_write_failed(ssh, c);
2445 }
2446 
2447 void
2448 session_close(struct ssh *ssh, Session *s)
2449 {
2450 	u_int i;
2451 
2452 	verbose("Close session: user %s from %.200s port %d id %d",
2453 	    s->pw->pw_name,
2454 	    ssh_remote_ipaddr(ssh),
2455 	    ssh_remote_port(ssh),
2456 	    s->self);
2457 
2458 	if (s->ttyfd != -1)
2459 		session_pty_cleanup(s);
2460 	free(s->term);
2461 	free(s->display);
2462 	free(s->x11_chanids);
2463 	free(s->auth_display);
2464 	free(s->auth_data);
2465 	free(s->auth_proto);
2466 	free(s->subsys);
2467 	if (s->env != NULL) {
2468 		for (i = 0; i < s->num_env; i++) {
2469 			free(s->env[i].name);
2470 			free(s->env[i].val);
2471 		}
2472 		free(s->env);
2473 	}
2474 	session_proctitle(s);
2475 	session_unused(s->self);
2476 }
2477 
2478 void
2479 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2480 {
2481 	Session *s = session_by_pid(pid);
2482 	if (s == NULL) {
2483 		debug_f("no session for pid %ld", (long)pid);
2484 		return;
2485 	}
2486 	if (s->chanid != -1)
2487 		session_exit_message(ssh, s, status);
2488 	if (s->ttyfd != -1)
2489 		session_pty_cleanup(s);
2490 	s->pid = 0;
2491 }
2492 
2493 /*
2494  * this is called when a channel dies before
2495  * the session 'child' itself dies
2496  */
2497 void
2498 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2499 {
2500 	Session *s = session_by_channel(id);
2501 	u_int i;
2502 
2503 	if (s == NULL) {
2504 		debug_f("no session for id %d", id);
2505 		return;
2506 	}
2507 	debug_f("channel %d child %ld", id, (long)s->pid);
2508 	if (s->pid != 0) {
2509 		debug_f("channel %d: has child, ttyfd %d", id, s->ttyfd);
2510 		/*
2511 		 * delay detach of session, but release pty, since
2512 		 * the fd's to the child are already closed
2513 		 */
2514 		if (s->ttyfd != -1)
2515 			session_pty_cleanup(s);
2516 		return;
2517 	}
2518 	/* detach by removing callback */
2519 	channel_cancel_cleanup(ssh, s->chanid);
2520 
2521 	/* Close any X11 listeners associated with this session */
2522 	if (s->x11_chanids != NULL) {
2523 		for (i = 0; s->x11_chanids[i] != -1; i++) {
2524 			session_close_x11(ssh, s->x11_chanids[i]);
2525 			s->x11_chanids[i] = -1;
2526 		}
2527 	}
2528 
2529 	s->chanid = -1;
2530 	session_close(ssh, s);
2531 }
2532 
2533 void
2534 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2535 {
2536 	int i;
2537 	for (i = 0; i < sessions_nalloc; i++) {
2538 		Session *s = &sessions[i];
2539 		if (s->used) {
2540 			if (closefunc != NULL)
2541 				closefunc(s);
2542 			else
2543 				session_close(ssh, s);
2544 		}
2545 	}
2546 }
2547 
2548 static char *
2549 session_tty_list(void)
2550 {
2551 	static char buf[1024];
2552 	int i;
2553 	char *cp;
2554 
2555 	buf[0] = '\0';
2556 	for (i = 0; i < sessions_nalloc; i++) {
2557 		Session *s = &sessions[i];
2558 		if (s->used && s->ttyfd != -1) {
2559 
2560 			if (strncmp(s->tty, "/dev/", 5) != 0) {
2561 				cp = strrchr(s->tty, '/');
2562 				cp = (cp == NULL) ? s->tty : cp + 1;
2563 			} else
2564 				cp = s->tty + 5;
2565 
2566 			if (buf[0] != '\0')
2567 				strlcat(buf, ",", sizeof buf);
2568 			strlcat(buf, cp, sizeof buf);
2569 		}
2570 	}
2571 	if (buf[0] == '\0')
2572 		strlcpy(buf, "notty", sizeof buf);
2573 	return buf;
2574 }
2575 
2576 void
2577 session_proctitle(Session *s)
2578 {
2579 	if (s->pw == NULL)
2580 		error("no user for session %d", s->self);
2581 	else
2582 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2583 }
2584 
2585 int
2586 session_setup_x11fwd(struct ssh *ssh, Session *s)
2587 {
2588 	struct stat st;
2589 	char display[512], auth_display[512];
2590 	char hostname[NI_MAXHOST];
2591 	u_int i;
2592 
2593 	if (!auth_opts->permit_x11_forwarding_flag) {
2594 		ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options.");
2595 		return 0;
2596 	}
2597 	if (!options.x11_forwarding) {
2598 		debug("X11 forwarding disabled in server configuration file.");
2599 		return 0;
2600 	}
2601 	if (options.xauth_location == NULL ||
2602 	    (stat(options.xauth_location, &st) == -1)) {
2603 		ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11.");
2604 		return 0;
2605 	}
2606 	if (s->display != NULL) {
2607 		debug("X11 display already set.");
2608 		return 0;
2609 	}
2610 	if (x11_create_display_inet(ssh, options.x11_display_offset,
2611 	    options.x11_use_localhost, s->single_connection,
2612 	    &s->display_number, &s->x11_chanids) == -1) {
2613 		debug("x11_create_display_inet failed.");
2614 		return 0;
2615 	}
2616 	for (i = 0; s->x11_chanids[i] != -1; i++) {
2617 		channel_register_cleanup(ssh, s->x11_chanids[i],
2618 		    session_close_single_x11, 0);
2619 	}
2620 
2621 	/* Set up a suitable value for the DISPLAY variable. */
2622 	if (gethostname(hostname, sizeof(hostname)) == -1)
2623 		fatal("gethostname: %.100s", strerror(errno));
2624 	/*
2625 	 * auth_display must be used as the displayname when the
2626 	 * authorization entry is added with xauth(1).  This will be
2627 	 * different than the DISPLAY string for localhost displays.
2628 	 */
2629 	if (options.x11_use_localhost) {
2630 		snprintf(display, sizeof display, "localhost:%u.%u",
2631 		    s->display_number, s->screen);
2632 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2633 		    s->display_number, s->screen);
2634 		s->display = xstrdup(display);
2635 		s->auth_display = xstrdup(auth_display);
2636 	} else {
2637 #ifdef IPADDR_IN_DISPLAY
2638 		struct hostent *he;
2639 		struct in_addr my_addr;
2640 
2641 		he = gethostbyname(hostname);
2642 		if (he == NULL) {
2643 			error("Can't get IP address for X11 DISPLAY.");
2644 			ssh_packet_send_debug(ssh, "Can't get IP address for X11 DISPLAY.");
2645 			return 0;
2646 		}
2647 		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2648 		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2649 		    s->display_number, s->screen);
2650 #else
2651 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2652 		    s->display_number, s->screen);
2653 #endif
2654 		s->display = xstrdup(display);
2655 		s->auth_display = xstrdup(display);
2656 	}
2657 
2658 	return 1;
2659 }
2660 
2661 static void
2662 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2663 {
2664 	server_loop2(ssh, authctxt);
2665 }
2666 
2667 void
2668 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2669 {
2670 	static int called = 0;
2671 
2672 	debug("do_cleanup");
2673 
2674 	/* no cleanup if we're in the child for login shell */
2675 	if (is_child)
2676 		return;
2677 
2678 	/* avoid double cleanup */
2679 	if (called)
2680 		return;
2681 	called = 1;
2682 
2683 	if (authctxt == NULL)
2684 		return;
2685 
2686 #ifdef USE_PAM
2687 	if (options.use_pam) {
2688 		sshpam_cleanup();
2689 		sshpam_thread_cleanup();
2690 	}
2691 #endif
2692 
2693 	if (!authctxt->authenticated)
2694 		return;
2695 
2696 #ifdef KRB5
2697 	if (options.kerberos_ticket_cleanup &&
2698 	    authctxt->krb5_ctx)
2699 		krb5_cleanup_proc(authctxt);
2700 #endif
2701 
2702 #ifdef GSSAPI
2703 	if (options.gss_cleanup_creds)
2704 		ssh_gssapi_cleanup_creds();
2705 #endif
2706 
2707 	/* remove agent socket */
2708 	auth_sock_cleanup_proc(authctxt->pw);
2709 
2710 	/* remove userauth info */
2711 	if (auth_info_file != NULL) {
2712 		temporarily_use_uid(authctxt->pw);
2713 		unlink(auth_info_file);
2714 		restore_uid();
2715 		free(auth_info_file);
2716 		auth_info_file = NULL;
2717 	}
2718 
2719 	/*
2720 	 * Cleanup ptys/utmp only if privsep is disabled,
2721 	 * or if running in monitor.
2722 	 */
2723 	if (!use_privsep || mm_is_monitor())
2724 		session_destroy_all(ssh, session_pty_cleanup2);
2725 }
2726 
2727 /* Return a name for the remote host that fits inside utmp_size */
2728 
2729 const char *
2730 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2731 {
2732 	const char *remote = "";
2733 
2734 	if (utmp_size > 0)
2735 		remote = auth_get_canonical_hostname(ssh, use_dns);
2736 	if (utmp_size == 0 || strlen(remote) > utmp_size)
2737 		remote = ssh_remote_ipaddr(ssh);
2738 	return remote;
2739 }
2740 
2741