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