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