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