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