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