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