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