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