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