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