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