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