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