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