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