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