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