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