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