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