xref: /titanic_41/usr/src/cmd/ssh/sshd/session.c (revision 1d7b78a3ad3ba3aedee339128153e8f515cb6f1c)
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 		/* Do common processing for the child, such as execing the command. */
628 		do_child(s, command);
629 		/* NOTREACHED */
630 	}
631 
632 	/* Wait for child to exec() or exit() */
633 	(void) close(pipe_fds[1]);
634 	(void) read(pipe_fds[0], &pipe_fds[1], sizeof(int));
635 
636 #ifdef _UNICOS
637 	signal(WJSIGNAL, cray_job_termination_handler);
638 #endif /* _UNICOS */
639 #ifdef HAVE_CYGWIN
640 	if (is_winnt)
641 		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
642 #endif
643 	if (pid < 0)
644 		packet_disconnect("fork failed: %.100s", strerror(errno));
645 	s->pid = pid;
646 
647 	/* Parent.  Close the slave side of the pseudo tty. */
648 	close(ttyfd);
649 
650 	/*
651 	 * Create another descriptor of the pty master side for use as the
652 	 * standard input.  We could use the original descriptor, but this
653 	 * simplifies code in server_loop.  The descriptor is bidirectional.
654 	 */
655 	fdout = dup(ptyfd);
656 	if (fdout < 0)
657 		packet_disconnect("dup #1 failed: %.100s", strerror(errno));
658 
659 	/* we keep a reference to the pty master */
660 	ptymaster = dup(ptyfd);
661 	if (ptymaster < 0)
662 		packet_disconnect("dup #2 failed: %.100s", strerror(errno));
663 	s->ptymaster = ptymaster;
664 
665 	/* Enter interactive session. */
666 	packet_set_interactive(1);
667 	if (compat20) {
668 		session_set_fds(s, ptyfd, fdout, -1);
669 		/* Don't close channel before sending exit-status! */
670 		channel_set_wait_for_exit(s->chanid, 1);
671 	} else {
672 		server_loop(pid, ptyfd, fdout, -1);
673 		/* server_loop _has_ closed ptyfd and fdout. */
674 	}
675 }
676 
677 /*
678  * This is called to fork and execute a command.  If another command is
679  * to be forced, execute that instead.
680  */
681 void
682 do_exec(Session *s, const char *command)
683 {
684 	if (command)
685 		s->command = xstrdup(command);
686 
687 	if (forced_command) {
688 		original_command = command;
689 		command = forced_command;
690 		debug("Forced command '%.900s'", command);
691 	}
692 
693 	if (s->ttyfd != -1)
694 		do_exec_pty(s, command);
695 	else
696 		do_exec_no_pty(s, command);
697 
698 	original_command = NULL;
699 }
700 
701 
702 /* administrative, login(1)-like work */
703 void
704 do_login(Session *s, const char *command)
705 {
706 	char *time_string;
707 #ifndef ALTPRIVSEP
708 	struct passwd * pw = s->pw;
709 #endif /* ALTPRIVSEP*/
710 	pid_t pid = getpid();
711 
712 	/* Record that there was a login on that tty from the remote host. */
713 #ifdef ALTPRIVSEP
714 	debug3("Recording SSHv2 channel login in utmpx/wtmpx");
715 	altprivsep_record_login(pid, s->tty);
716 #endif /* ALTPRIVSEP*/
717 
718 	if (check_quietlogin(s, command))
719 		return;
720 
721 #ifdef USE_PAM
722 		print_pam_messages();
723 #endif /* USE_PAM */
724 #ifdef WITH_AIXAUTHENTICATE
725 	if (aixloginmsg && *aixloginmsg)
726 		printf("%s\n", aixloginmsg);
727 #endif /* WITH_AIXAUTHENTICATE */
728 
729 #ifndef NO_SSH_LASTLOG
730 	if (options.print_lastlog && s->last_login_time != 0) {
731 		time_string = ctime(&s->last_login_time);
732 		if (strchr(time_string, '\n'))
733 			*strchr(time_string, '\n') = 0;
734 		if (strcmp(s->hostname, "") == 0)
735 			printf("Last login: %s\r\n", time_string);
736 		else
737 			printf("Last login: %s from %s\r\n", time_string,
738 			    s->hostname);
739 	}
740 #endif /* NO_SSH_LASTLOG */
741 
742 	do_motd();
743 }
744 
745 /*
746  * Display the message of the day.
747  */
748 void
749 do_motd(void)
750 {
751 	FILE *f;
752 	char buf[256];
753 
754 	if (options.print_motd) {
755 #ifdef HAVE_LOGIN_CAP
756 		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
757 		    "/etc/motd"), "r");
758 #else
759 		f = fopen("/etc/motd", "r");
760 #endif
761 		if (f) {
762 			while (fgets(buf, sizeof(buf), f))
763 				fputs(buf, stdout);
764 			fclose(f);
765 		}
766 	}
767 }
768 
769 
770 /*
771  * Check for quiet login, either .hushlogin or command given.
772  */
773 int
774 check_quietlogin(Session *s, const char *command)
775 {
776 	char buf[256];
777 	struct passwd *pw = s->pw;
778 	struct stat st;
779 
780 	/* Return 1 if .hushlogin exists or a command given. */
781 	if (command != NULL)
782 		return 1;
783 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
784 #ifdef HAVE_LOGIN_CAP
785 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
786 		return 1;
787 #else
788 	if (stat(buf, &st) >= 0)
789 		return 1;
790 #endif
791 	return 0;
792 }
793 
794 /*
795  * Sets the value of the given variable in the environment.  If the variable
796  * already exists, its value is overriden.
797  */
798 void
799 child_set_env(char ***envp, u_int *envsizep, const char *name,
800 	const char *value)
801 {
802 	debug3("child_set_env(%s, %s)", name, value);
803 	child_set_env_silent(envp, envsizep, name, value);
804 }
805 
806 
807 void
808 child_set_env_silent(char ***envp, u_int *envsizep, const char *name,
809 	const char *value)
810 {
811 	u_int i, namelen;
812 	char **env;
813 
814 	/*
815 	 * Find the slot where the value should be stored.  If the variable
816 	 * already exists, we reuse the slot; otherwise we append a new slot
817 	 * at the end of the array, expanding if necessary.
818 	 */
819 	env = *envp;
820 	namelen = strlen(name);
821 	for (i = 0; env[i]; i++)
822 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
823 			break;
824 	if (env[i]) {
825 		/* Reuse the slot. */
826 		xfree(env[i]);
827 	} else {
828 		/* New variable.  Expand if necessary. */
829 		if (i >= (*envsizep) - 1) {
830 			if (*envsizep >= 1000)
831 				fatal("child_set_env: too many env vars,"
832 				    " skipping: %.100s", name);
833 			(*envsizep) += 50;
834 			env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
835 		}
836 		/* Need to set the NULL pointer at end of array beyond the new slot. */
837 		env[i + 1] = NULL;
838 	}
839 
840 	/* Allocate space and format the variable in the appropriate slot. */
841 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
842 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
843 }
844 
845 /*
846  * Reads environment variables from the given file and adds/overrides them
847  * into the environment.  If the file does not exist, this does nothing.
848  * Otherwise, it must consist of empty lines, comments (line starts with '#')
849  * and assignments of the form name=value.  No other forms are allowed.
850  */
851 static void
852 read_environment_file(char ***env, u_int *envsize,
853 	const char *filename)
854 {
855 	FILE *f;
856 	char buf[4096];
857 	char *cp, *value;
858 	u_int lineno = 0;
859 
860 	f = fopen(filename, "r");
861 	if (!f)
862 		return;
863 
864 	while (fgets(buf, sizeof(buf), f)) {
865 		if (++lineno > 1000)
866 			fatal("Too many lines in environment file %s", filename);
867 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
868 			;
869 		if (!*cp || *cp == '#' || *cp == '\n')
870 			continue;
871 		if (strchr(cp, '\n'))
872 			*strchr(cp, '\n') = '\0';
873 		value = strchr(cp, '=');
874 		if (value == NULL) {
875 			fprintf(stderr, gettext("Bad line %u in %.100s\n"),
876 				lineno, filename);
877 			continue;
878 		}
879 		/*
880 		 * Replace the equals sign by nul, and advance value to
881 		 * the value string.
882 		 */
883 		*value = '\0';
884 		value++;
885 		child_set_env(env, envsize, cp, value);
886 	}
887 	fclose(f);
888 }
889 
890 void copy_environment(char **source, char ***env, u_int *envsize)
891 {
892 	char *var_name, *var_val;
893 	int i;
894 
895 	if (source == NULL)
896 		return;
897 
898 	for(i = 0; source[i] != NULL; i++) {
899 		var_name = xstrdup(source[i]);
900 		if ((var_val = strstr(var_name, "=")) == NULL) {
901 			xfree(var_name);
902 			continue;
903 		}
904 		*var_val++ = '\0';
905 
906 		debug3("Copy environment: %s=%s", var_name, var_val);
907 		child_set_env(env, envsize, var_name, var_val);
908 
909 		xfree(var_name);
910 	}
911 }
912 
913 #ifdef HAVE_DEFOPEN
914 static
915 void
916 deflt_do_setup_env(Session *s, const char *shell, char ***env, u_int *envsize)
917 {
918 	int	flags;
919 	char	*ptr;
920 	mode_t	Umask = 022;
921 
922 	if (defopen(_PATH_DEFAULT_LOGIN))
923 		return;
924 
925 	/* Ignore case */
926 	flags = defcntl(DC_GETFLAGS, 0);
927 	TURNOFF(flags, DC_CASE);
928 	(void) defcntl(DC_SETFLAGS, flags);
929 
930 	/* TZ & HZ */
931 	if ((ptr = defread("TIMEZONE=")) != NULL)
932 		child_set_env(env, envsize, "TZ", ptr);
933 	if ((ptr = defread("HZ=")) != NULL)
934 		child_set_env(env, envsize, "HZ", ptr);
935 
936 	/* PATH */
937 	if (s->pw->pw_uid != 0 && (ptr = defread("PATH=")) != NULL)
938 		child_set_env(env, envsize, "PATH", ptr);
939 	if (s->pw->pw_uid == 0 && (ptr = defread("SUPATH=")) != NULL)
940 		child_set_env(env, envsize, "PATH", ptr);
941 
942 	/* SHELL */
943 	if ((ptr = defread("ALTSHELL=")) != NULL) {
944 		if (strcasecmp("YES", ptr) == 0)
945 			child_set_env(env, envsize, "SHELL", shell);
946 		else
947 			child_set_env(env, envsize, "SHELL", "");
948 	}
949 
950 	/* UMASK */
951 	if ((ptr = defread("UMASK=")) != NULL &&
952 	    sscanf(ptr, "%lo", &Umask) == 1 &&
953 	    Umask <= (mode_t)0777)
954 		(void) umask(Umask);
955 	else
956 		(void) umask(022);
957 
958 	/* ULIMIT */
959 	if ((ptr = defread("ULIMIT=")) != NULL && atol(ptr) > 0L &&
960 	    ulimit(UL_SETFSIZE, atol(ptr)) < 0L)
961 		error("Could not set ULIMIT to %ld from %s\n", atol(ptr),
962 			_PATH_DEFAULT_LOGIN);
963 
964 	(void) defopen(NULL);
965 }
966 #endif /* HAVE_DEFOPEN */
967 
968 static char **
969 do_setup_env(Session *s, const char *shell)
970 {
971 	char buf[256];
972 	char path_maildir[] = _PATH_MAILDIR;
973 	u_int i, envsize, pm_len;
974 	char **env;
975 	struct passwd *pw = s->pw;
976 
977 	/* Initialize the environment. */
978 	envsize = 100;
979 	env = xmalloc(envsize * sizeof(char *));
980 	env[0] = NULL;
981 
982 #ifdef HAVE_CYGWIN
983 	/*
984 	 * The Windows environment contains some setting which are
985 	 * important for a running system. They must not be dropped.
986 	 */
987 	copy_environment(environ, &env, &envsize);
988 #endif
989 
990 #ifdef GSSAPI
991 	/* Allow any GSSAPI methods that we've used to alter
992 	 * the childs environment as they see fit
993 	 */
994 	ssh_gssapi_do_child(xxx_gssctxt, &env,&envsize);
995 #endif
996 
997 	/* Set basic environment. */
998 	child_set_env(&env, &envsize, "USER", pw->pw_name);
999 	child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1000 	child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1001 #ifdef HAVE_LOGIN_CAP
1002 	if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1003 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1004 	else
1005 		child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1006 #else /* HAVE_LOGIN_CAP */
1007 # ifndef HAVE_CYGWIN
1008 	/*
1009 	 * There's no standard path on Windows. The path contains
1010 	 * important components pointing to the system directories,
1011 	 * needed for loading shared libraries. So the path better
1012 	 * remains intact here.
1013 	 */
1014 #  ifdef SUPERUSER_PATH
1015 	child_set_env(&env, &envsize, "PATH",
1016 	    s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1017 #  else
1018 	child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1019 #  endif /* SUPERUSER_PATH */
1020 # endif /* HAVE_CYGWIN */
1021 #endif /* HAVE_LOGIN_CAP */
1022 
1023 	pm_len = strlen(path_maildir);
1024 	if (path_maildir[pm_len - 1] == '/' && pm_len > 1)
1025 		path_maildir[pm_len - 1] = NULL;
1026 	snprintf(buf, sizeof buf, "%.200s/%.50s",
1027 		 path_maildir, pw->pw_name);
1028 	child_set_env(&env, &envsize, "MAIL", buf);
1029 
1030 	/* Normal systems set SHELL by default. */
1031 	child_set_env(&env, &envsize, "SHELL", shell);
1032 
1033 #ifdef HAVE_DEFOPEN
1034 	deflt_do_setup_env(s, shell, &env, &envsize);
1035 #endif /* HAVE_DEFOPEN */
1036 
1037 #define PASS_ENV(x) \
1038 	if (getenv(x)) \
1039 		child_set_env(&env, &envsize, x, getenv(x));
1040 
1041 	if (getenv("TZ"))
1042 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1043 
1044 	if (s->auth_file != NULL)
1045 		child_set_env(&env, &envsize, "XAUTHORITY", s->auth_file);
1046 
1047 	PASS_ENV("LANG")
1048 	PASS_ENV("LC_ALL")
1049 	PASS_ENV("LC_CTYPE")
1050 	PASS_ENV("LC_COLLATE")
1051 	PASS_ENV("LC_TIME")
1052 	PASS_ENV("LC_NUMERIC")
1053 	PASS_ENV("LC_MONETARY")
1054 	PASS_ENV("LC_MESSAGES")
1055 
1056 #undef PASS_ENV
1057 
1058 	if (s->env != NULL)
1059 		copy_environment(s->env, &env, &envsize);
1060 
1061 	/* Set custom environment options from RSA authentication. */
1062 	while (custom_environment) {
1063 		struct envstring *ce = custom_environment;
1064 		char *str = ce->s;
1065 
1066 		for (i = 0; str[i] != '=' && str[i]; i++)
1067 			;
1068 		if (str[i] == '=') {
1069 			str[i] = 0;
1070 			child_set_env(&env, &envsize, str, str + i + 1);
1071 		}
1072 		custom_environment = ce->next;
1073 		xfree(ce->s);
1074 		xfree(ce);
1075 	}
1076 
1077 	/* SSH_CLIENT deprecated */
1078 	snprintf(buf, sizeof buf, "%.50s %d %d",
1079 	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1080 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1081 
1082 	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1083 	    get_remote_ipaddr(), get_remote_port(),
1084 	    get_local_ipaddr(packet_get_connection_in()), get_local_port());
1085 	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1086 
1087 	if (s->ttyfd != -1)
1088 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1089 	if (s->term)
1090 		child_set_env(&env, &envsize, "TERM", s->term);
1091 	if (s->display)
1092 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1093 	if (original_command)
1094 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1095 		    original_command);
1096 
1097 #ifdef _UNICOS
1098 	if (cray_tmpdir[0] != '\0')
1099 		child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1100 #endif /* _UNICOS */
1101 
1102 #ifdef _AIX
1103 	{
1104 		char *cp;
1105 
1106 		if ((cp = getenv("AUTHSTATE")) != NULL)
1107 			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1108 		if ((cp = getenv("KRB5CCNAME")) != NULL)
1109 			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1110 		read_environment_file(&env, &envsize, "/etc/environment");
1111 	}
1112 #endif
1113 #ifdef KRB4
1114 	if (s->authctxt->krb4_ticket_file)
1115 		child_set_env(&env, &envsize, "KRBTKFILE",
1116 		    s->authctxt->krb4_ticket_file);
1117 #endif
1118 #ifdef KRB5
1119 	if (s->authctxt->krb5_ticket_file)
1120 		child_set_env(&env, &envsize, "KRB5CCNAME",
1121 		    s->authctxt->krb5_ticket_file);
1122 #endif
1123 #ifdef USE_PAM
1124 	/*
1125 	 * Pull in any environment variables that may have
1126 	 * been set by PAM.
1127 	 */
1128 	{
1129 		char **p;
1130 
1131 		p = fetch_pam_environment(s->authctxt);
1132 		copy_environment(p, &env, &envsize);
1133 		free_pam_environment(p);
1134 	}
1135 #endif /* USE_PAM */
1136 
1137 	if (auth_sock_name != NULL)
1138 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1139 		    auth_sock_name);
1140 
1141 	/* read $HOME/.ssh/environment. */
1142 	if (options.permit_user_env) {
1143 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1144 		    strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1145 		read_environment_file(&env, &envsize, buf);
1146 	}
1147 	if (debug_flag) {
1148 		/* dump the environment */
1149 		fprintf(stderr, gettext("Environment:\n"));
1150 		for (i = 0; env[i]; i++)
1151 			fprintf(stderr, "  %.200s\n", env[i]);
1152 	}
1153 	return env;
1154 }
1155 
1156 /*
1157  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1158  * first in this order).
1159  */
1160 static void
1161 do_rc_files(Session *s, const char *shell)
1162 {
1163 	FILE *f = NULL;
1164 	char cmd[1024];
1165 	int do_xauth;
1166 	struct stat st;
1167 
1168 	do_xauth =
1169 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1170 
1171 	/* ignore _PATH_SSH_USER_RC for subsystems */
1172 	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1173 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1174 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1175 		if (debug_flag)
1176 			fprintf(stderr, "Running %s\n", cmd);
1177 		f = popen(cmd, "w");
1178 		if (f) {
1179 			if (do_xauth)
1180 				fprintf(f, "%s %s\n", s->auth_proto,
1181 				    s->auth_data);
1182 			pclose(f);
1183 		} else
1184 			fprintf(stderr, "Could not run %s\n",
1185 			    _PATH_SSH_USER_RC);
1186 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1187 		if (debug_flag)
1188 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1189 			    _PATH_SSH_SYSTEM_RC);
1190 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "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_SYSTEM_RC);
1199 	} else if (do_xauth && options.xauth_location != NULL) {
1200 		/* Add authority data to .Xauthority if appropriate. */
1201 		if (debug_flag) {
1202 			fprintf(stderr,
1203 			    "Running %.500s add "
1204 			    "%.100s %.100s %.100s\n",
1205 			    options.xauth_location, s->auth_display,
1206 			    s->auth_proto, s->auth_data);
1207 		}
1208 		snprintf(cmd, sizeof cmd, "%s -q -",
1209 		    options.xauth_location);
1210 		f = popen(cmd, "w");
1211 		if (f) {
1212 			fprintf(f, "add %s %s %s\n",
1213 			    s->auth_display, s->auth_proto,
1214 			    s->auth_data);
1215 			pclose(f);
1216 		} else {
1217 			fprintf(stderr, "Could not run %s\n",
1218 			    cmd);
1219 		}
1220 	}
1221 }
1222 
1223 static void
1224 do_nologin(struct passwd *pw)
1225 {
1226 	FILE *f = NULL;
1227 	char buf[1024];
1228 
1229 #ifdef HAVE_LOGIN_CAP
1230 	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1231 		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1232 		    _PATH_NOLOGIN), "r");
1233 #else
1234 	if (pw->pw_uid)
1235 		f = fopen(_PATH_NOLOGIN, "r");
1236 #endif
1237 	if (f) {
1238 		/* /etc/nologin exists.  Print its contents and exit. */
1239 		log("User %.100s not allowed because %s exists",
1240 		    pw->pw_name, _PATH_NOLOGIN);
1241 		while (fgets(buf, sizeof(buf), f))
1242 			fputs(buf, stderr);
1243 		fclose(f);
1244 		exit(254);
1245 	}
1246 }
1247 
1248 /* Chroot into ChrootDirectory if the option is set. */
1249 void
1250 chroot_if_needed(struct passwd *pw)
1251 {
1252 	char *chroot_path, *tmp;
1253 
1254 	if (chroot_requested(options.chroot_directory)) {
1255 		tmp = tilde_expand_filename(options.chroot_directory,
1256 		    pw->pw_uid);
1257 		chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1258 		    "u", pw->pw_name, (char *)NULL);
1259 		safely_chroot(chroot_path, pw->pw_uid);
1260 		free(tmp);
1261 		free(chroot_path);
1262 	}
1263 }
1264 
1265 /*
1266  * Chroot into a directory after checking it for safety: all path components
1267  * must be root-owned directories with strict permissions.
1268  */
1269 static void
1270 safely_chroot(const char *path, uid_t uid)
1271 {
1272 	const char *cp;
1273 	char component[MAXPATHLEN];
1274 	struct stat st;
1275 
1276 	if (*path != '/')
1277 		fatal("chroot path does not begin at root");
1278 	if (strlen(path) >= sizeof(component))
1279 		fatal("chroot path too long");
1280 
1281 	/*
1282 	 * Descend the path, checking that each component is a
1283 	 * root-owned directory with strict permissions.
1284 	 */
1285 	for (cp = path; cp != NULL;) {
1286 		if ((cp = strchr(cp, '/')) == NULL)
1287 			strlcpy(component, path, sizeof(component));
1288 		else {
1289 			cp++;
1290 			memcpy(component, path, cp - path);
1291 			component[cp - path] = '\0';
1292 		}
1293 
1294 		debug3("%s: checking '%s'", __func__, component);
1295 
1296 		if (stat(component, &st) != 0)
1297 			fatal("%s: stat(\"%s\"): %s", __func__,
1298 			    component, strerror(errno));
1299 		if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1300 			fatal("bad ownership or modes for chroot "
1301 			    "directory %s\"%s\"",
1302 			    cp == NULL ? "" : "component ", component);
1303 		if (!S_ISDIR(st.st_mode))
1304 			fatal("chroot path %s\"%s\" is not a directory",
1305 			    cp == NULL ? "" : "component ", component);
1306 	}
1307 
1308 	if (chdir(path) == -1)
1309 		fatal("Unable to chdir to chroot path \"%s\": "
1310 		    "%s", path, strerror(errno));
1311 	if (chroot(path) == -1)
1312 		fatal("chroot(\"%s\"): %s", path, strerror(errno));
1313 	if (chdir("/") == -1)
1314 		fatal("%s: chdir(/) after chroot: %s",
1315 		    __func__, strerror(errno));
1316 	verbose("Changed root directory to \"%s\"", path);
1317 }
1318 
1319 static void
1320 launch_login(struct passwd *pw, const char *hostname)
1321 {
1322 	/* Launch login(1). */
1323 
1324 	execl(LOGIN_PROGRAM, "login", "-h", hostname,
1325 #ifdef xxxLOGIN_NEEDS_TERM
1326 		    (s->term ? s->term : "unknown"),
1327 #endif /* LOGIN_NEEDS_TERM */
1328 #ifdef LOGIN_NO_ENDOPT
1329 	    "-p", "-f", pw->pw_name, (char *)NULL);
1330 #else
1331 	    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1332 #endif
1333 
1334 	/* Login couldn't be executed, die. */
1335 
1336 	perror("login");
1337 	exit(1);
1338 }
1339 
1340 /*
1341  * Performs common processing for the child, such as setting up the
1342  * environment, closing extra file descriptors, setting the user and group
1343  * ids, and executing the command or shell.
1344  */
1345 #define ARGV_MAX 10
1346 void
1347 do_child(Session *s, const char *command)
1348 {
1349 	extern char **environ;
1350 	char **env;
1351 	char *argv[ARGV_MAX];
1352 	const char *shell, *shell0;
1353 	struct passwd *pw = s->pw;
1354 
1355 	/* remove hostkey from the child's memory */
1356 	destroy_sensitive_data();
1357 
1358 	do_nologin(pw);
1359 	chroot_if_needed(pw);
1360 
1361 	/*
1362 	 * Get the shell from the password data.  An empty shell field is
1363 	 * legal, and means /bin/sh.
1364 	 */
1365 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1366 #ifdef HAVE_LOGIN_CAP
1367 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1368 #endif
1369 
1370 	env = do_setup_env(s, shell);
1371 
1372 	/*
1373 	 * Close the connection descriptors; note that this is the child, and
1374 	 * the server will still have the socket open, and it is important
1375 	 * that we do not shutdown it.  Note that the descriptors cannot be
1376 	 * closed before building the environment, as we call
1377 	 * get_remote_ipaddr there.
1378 	 */
1379 	if (packet_get_connection_in() == packet_get_connection_out())
1380 		close(packet_get_connection_in());
1381 	else {
1382 		close(packet_get_connection_in());
1383 		close(packet_get_connection_out());
1384 	}
1385 	/*
1386 	 * Close all descriptors related to channels.  They will still remain
1387 	 * open in the parent.
1388 	 */
1389 	/* XXX better use close-on-exec? -markus */
1390 	channel_close_all();
1391 
1392 	/*
1393 	 * Close any extra file descriptors.  Note that there may still be
1394 	 * descriptors left by system functions.  They will be closed later.
1395 	 */
1396 	endpwent();
1397 
1398 	/*
1399 	 * Must switch to the new environment variables so that .ssh/rc,
1400 	 * /etc/ssh/sshrc, and xauth are run in the proper environment.
1401 	 */
1402 	environ = env;
1403 
1404 	/*
1405 	 * New environment has been installed. We need to update locale
1406 	 * so that error messages beyond this point have the proper
1407 	 * character encoding.
1408 	 */
1409 	(void) setlocale(LC_ALL, "");
1410 
1411 	/*
1412 	 * Close any extra open file descriptors so that we don\'t have them
1413 	 * hanging around in clients.  Note that we want to do this after
1414 	 * initgroups, because at least on Solaris 2.3 it leaves file
1415 	 * descriptors open.
1416 	 */
1417 	closefrom(STDERR_FILENO + 1);
1418 
1419 #ifdef AFS
1420 	/* Try to get AFS tokens for the local cell. */
1421 	if (k_hasafs()) {
1422 		char cell[64];
1423 
1424 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1425 			krb_afslog(cell, 0);
1426 
1427 		krb_afslog(0, 0);
1428 	}
1429 #endif /* AFS */
1430 
1431 	/* Change current directory to the user's home directory. */
1432 	if (chdir(pw->pw_dir) < 0) {
1433 		/* Suppress missing homedir warning for chroot case */
1434 		if (!chroot_requested(options.chroot_directory))
1435 			fprintf(stderr, "Could not chdir to home "
1436 			    "directory %s: %s\n", pw->pw_dir,
1437 			    strerror(errno));
1438 	}
1439 
1440 	do_rc_files(s, shell);
1441 
1442 	/* restore SIGPIPE for child */
1443 	signal(SIGPIPE,  SIG_DFL);
1444 
1445 	if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1446 		int i;
1447 		char *p, *args;
1448 		extern int optind, optreset;
1449 
1450 		/* This will set the E/P sets here, simulating exec(2). */
1451 		drop_privs(pw->pw_uid);
1452 
1453 		setproctitle("%s@internal-sftp-server", s->pw->pw_name);
1454 		args = xstrdup(command ? command : "sftp-server");
1455 
1456 		i = 0;
1457 		for ((p = strtok(args, " ")); p != NULL; (p = strtok(NULL, " "))) {
1458 			if (i < ARGV_MAX - 1)
1459 				argv[i++] = p;
1460 		}
1461 
1462 		argv[i] = NULL;
1463 		optind = optreset = 1;
1464 		__progname = argv[0];
1465 		exit(sftp_server_main(i, argv, s->pw));
1466 	}
1467 
1468 	/* Get the last component of the shell name. */
1469 	if ((shell0 = strrchr(shell, '/')) != NULL)
1470 		shell0++;
1471 	else
1472 		shell0 = shell;
1473 
1474 	/*
1475 	 * If we have no command, execute the shell.  In this case, the shell
1476 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1477 	 * this is a login shell.
1478 	 */
1479 	if (!command) {
1480 		char argv0[256];
1481 
1482 		/* Start the shell.  Set initial character to '-'. */
1483 		argv0[0] = '-';
1484 
1485 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1486 		    >= sizeof(argv0) - 1) {
1487 			errno = EINVAL;
1488 			perror(shell);
1489 			exit(1);
1490 		}
1491 
1492 		/* Execute the shell. */
1493 		argv[0] = argv0;
1494 		argv[1] = NULL;
1495 		execve(shell, argv, env);
1496 
1497 		/* Executing the shell failed. */
1498 		perror(shell);
1499 		exit(1);
1500 	}
1501 	/*
1502 	 * Execute the command using the user's shell.  This uses the -c
1503 	 * option to execute the command.
1504 	 */
1505 	argv[0] = (char *) shell0;
1506 	argv[1] = "-c";
1507 	argv[2] = (char *) command;
1508 	argv[3] = NULL;
1509 	execve(shell, argv, env);
1510 	perror(shell);
1511 	exit(1);
1512 }
1513 
1514 Session *
1515 session_new(void)
1516 {
1517 	int i;
1518 	static int did_init = 0;
1519 	if (!did_init) {
1520 		debug("session_new: init");
1521 		for (i = 0; i < MAX_SESSIONS; i++) {
1522 			sessions[i].used = 0;
1523 		}
1524 		did_init = 1;
1525 	}
1526 	for (i = 0; i < MAX_SESSIONS; i++) {
1527 		Session *s = &sessions[i];
1528 		if (! s->used) {
1529 			memset(s, 0, sizeof(*s));
1530 			s->chanid = -1;
1531 			s->ptyfd = -1;
1532 			s->ttyfd = -1;
1533 			s->used = 1;
1534 			s->self = i;
1535 			s->env = NULL;
1536 			debug("session_new: session %d", i);
1537 			return s;
1538 		}
1539 	}
1540 	return NULL;
1541 }
1542 
1543 static void
1544 session_dump(void)
1545 {
1546 	int i;
1547 	for (i = 0; i < MAX_SESSIONS; i++) {
1548 		Session *s = &sessions[i];
1549 		debug("dump: used %d session %d %p channel %d pid %ld",
1550 		    s->used,
1551 		    s->self,
1552 		    s,
1553 		    s->chanid,
1554 		    (long)s->pid);
1555 	}
1556 }
1557 
1558 int
1559 session_open(Authctxt *authctxt, int chanid)
1560 {
1561 	Session *s = session_new();
1562 	debug("session_open: channel %d", chanid);
1563 	if (s == NULL) {
1564 		error("no more sessions");
1565 		return 0;
1566 	}
1567 	s->authctxt = authctxt;
1568 	s->pw = authctxt->pw;
1569 	if (s->pw == NULL)
1570 		fatal("no user for session %d", s->self);
1571 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1572 	s->chanid = chanid;
1573 	return 1;
1574 }
1575 
1576 #ifndef lint
1577 Session *
1578 session_by_tty(char *tty)
1579 {
1580 	int i;
1581 	for (i = 0; i < MAX_SESSIONS; i++) {
1582 		Session *s = &sessions[i];
1583 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1584 			debug("session_by_tty: session %d tty %s", i, tty);
1585 			return s;
1586 		}
1587 	}
1588 	debug("session_by_tty: unknown tty %.100s", tty);
1589 	session_dump();
1590 	return NULL;
1591 }
1592 #endif /* lint */
1593 
1594 static Session *
1595 session_by_channel(int id)
1596 {
1597 	int i;
1598 	for (i = 0; i < MAX_SESSIONS; i++) {
1599 		Session *s = &sessions[i];
1600 		if (s->used && s->chanid == id) {
1601 			debug("session_by_channel: session %d channel %d", i, id);
1602 			return s;
1603 		}
1604 	}
1605 	debug("session_by_channel: unknown channel %d", id);
1606 	session_dump();
1607 	return NULL;
1608 }
1609 
1610 static Session *
1611 session_by_pid(pid_t pid)
1612 {
1613 	int i;
1614 	debug("session_by_pid: pid %ld", (long)pid);
1615 	for (i = 0; i < MAX_SESSIONS; i++) {
1616 		Session *s = &sessions[i];
1617 		if (s->used && s->pid == pid)
1618 			return s;
1619 	}
1620 	error("session_by_pid: unknown pid %ld", (long)pid);
1621 	session_dump();
1622 	return NULL;
1623 }
1624 
1625 static int
1626 session_window_change_req(Session *s)
1627 {
1628 	s->col = packet_get_int();
1629 	s->row = packet_get_int();
1630 	s->xpixel = packet_get_int();
1631 	s->ypixel = packet_get_int();
1632 	packet_check_eom();
1633 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1634 	return 1;
1635 }
1636 
1637 static int
1638 session_pty_req(Session *s)
1639 {
1640 	u_int len;
1641 	int n_bytes;
1642 
1643 	if (no_pty_flag) {
1644 		debug("Allocating a pty not permitted for this authentication.");
1645 		return 0;
1646 	}
1647 	if (s->ttyfd != -1) {
1648 		packet_disconnect("Protocol error: you already have a pty.");
1649 		return 0;
1650 	}
1651 	/* Get the time and hostname when the user last logged in. */
1652 	if (options.print_lastlog) {
1653 		s->hostname[0] = '\0';
1654 		s->last_login_time = get_last_login_time(s->pw->pw_uid,
1655 		    s->pw->pw_name, s->hostname, sizeof(s->hostname));
1656 
1657 		/*
1658 		 * PAM may update the last login date.
1659 		 *
1660 		 * Ideally PAM would also show the last login date as a
1661 		 * PAM_TEXT_INFO conversation message, and then we could just
1662 		 * always force the use of keyboard-interactive just so we can
1663 		 * pass any such PAM prompts and messages from the account and
1664 		 * session stacks, but skip pam_authenticate() if other userauth
1665 		 * has succeeded and the user's password isn't expired.
1666 		 *
1667 		 * Unfortunately this depends on support for keyboard-
1668 		 * interactive in the client, and support for lastlog messages
1669 		 * in some PAM module.
1670 		 *
1671 		 * As it is Solaris updates the lastlog in PAM, but does
1672 		 * not show the lastlog date in PAM.  If and when this state of
1673 		 * affairs changes this hack can be reconsidered, and, maybe,
1674 		 * removed.
1675 		 *
1676 		 * So we're stuck with a crude hack: get the lastlog
1677 		 * time before calling pam_open_session() and store it
1678 		 * in the Authctxt and then use it here once.  After
1679 		 * that, if the client opens any more pty sessions we'll
1680 		 * show the last lastlog entry since userauth.
1681 		 */
1682 		if (s->authctxt != NULL && s->authctxt->last_login_time > 0) {
1683 			s->last_login_time = s->authctxt->last_login_time;
1684 			(void) strlcpy(s->hostname,
1685 				       s->authctxt->last_login_host,
1686 				       sizeof(s->hostname));
1687 			s->authctxt->last_login_time = 0;
1688 			s->authctxt->last_login_host[0] = '\0';
1689 		}
1690 	}
1691 
1692 	s->term = packet_get_string(&len);
1693 
1694 	if (compat20) {
1695 		s->col = packet_get_int();
1696 		s->row = packet_get_int();
1697 	} else {
1698 		s->row = packet_get_int();
1699 		s->col = packet_get_int();
1700 	}
1701 	s->xpixel = packet_get_int();
1702 	s->ypixel = packet_get_int();
1703 
1704 	if (strcmp(s->term, "") == 0) {
1705 		xfree(s->term);
1706 		s->term = NULL;
1707 	}
1708 
1709 	/* Allocate a pty and open it. */
1710 	debug("Allocating pty.");
1711 	if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1712 		if (s->term)
1713 			xfree(s->term);
1714 		s->term = NULL;
1715 		s->ptyfd = -1;
1716 		s->ttyfd = -1;
1717 		error("session_pty_req: session %d alloc failed", s->self);
1718 		return 0;
1719 	}
1720 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1721 
1722 	/* for SSH1 the tty modes length is not given */
1723 	if (!compat20)
1724 		n_bytes = packet_remaining();
1725 	tty_parse_modes(s->ttyfd, &n_bytes);
1726 
1727 	/*
1728 	 * Add a cleanup function to clear the utmp entry and record logout
1729 	 * time in case we call fatal() (e.g., the connection gets closed).
1730 	 */
1731 	fatal_add_cleanup(session_pty_cleanup, (void *)s);
1732 	pty_setowner(s->pw, s->tty);
1733 
1734 	/* Set window size from the packet. */
1735 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1736 
1737 	packet_check_eom();
1738 	session_proctitle(s);
1739 	return 1;
1740 }
1741 
1742 static int
1743 session_subsystem_req(Session *s)
1744 {
1745 	struct stat st;
1746 	u_int len;
1747 	int success = 0;
1748 	char *prog, *cmd, *subsys = packet_get_string(&len);
1749 	u_int i;
1750 
1751 	packet_check_eom();
1752 	log("subsystem request for %.100s", subsys);
1753 
1754 	for (i = 0; i < options.num_subsystems; i++) {
1755 		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1756 			prog = options.subsystem_command[i];
1757 			cmd = options.subsystem_args[i];
1758 			if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1759 				s->is_subsystem = SUBSYSTEM_INT_SFTP;
1760 			/*
1761 			 * We must stat(2) the subsystem before we chroot in
1762 			 * order to be able to send a proper error message.
1763 			 */
1764 			} else if (chroot_requested(options.chroot_directory)) {
1765 				char chdirsub[MAXPATHLEN];
1766 
1767 				strlcpy(chdirsub, options.chroot_directory,
1768 				    sizeof (chdirsub));
1769 				strlcat(chdirsub, "/", sizeof (chdirsub));
1770 				strlcat(chdirsub, prog, sizeof (chdirsub));
1771 				if (stat(chdirsub, &st) < 0) {
1772 					error("subsystem: cannot stat %s under "
1773 					    "chroot directory %s: %s", prog,
1774 					    options.chroot_directory,
1775 					    strerror(errno));
1776 					if (strcmp(subsys, "sftp") == 0)
1777 						error("subsystem: please see "
1778 						    "the Subsystem option in "
1779 						    "sshd_config(4) for an "
1780 						    "explanation of '%s'.",
1781 						    INTERNAL_SFTP_NAME);
1782 					break;
1783 				}
1784 			} else if (stat(prog, &st) < 0) {
1785 				error("subsystem: cannot stat %s: %s", prog,
1786 				    strerror(errno));
1787 				break;
1788 			} else {
1789 				s->is_subsystem = SUBSYSTEM_EXT;
1790 			}
1791 			debug("subsystem: exec() %s", cmd);
1792 			do_exec(s, cmd);
1793 			success = 1;
1794 			break;
1795 		}
1796 	}
1797 
1798 	if (!success)
1799 		log("subsystem request for %.100s failed, subsystem not found",
1800 		    subsys);
1801 
1802 	xfree(subsys);
1803 	return success;
1804 }
1805 
1806 /*
1807  * Serve "x11-req" channel request for X11 forwarding for the current session
1808  * channel.
1809  */
1810 static int
1811 session_x11_req(Session *s)
1812 {
1813 	int success, fd;
1814 	char xauthdir[] = "/tmp/ssh-xauth-XXXXXX";
1815 
1816 	s->single_connection = packet_get_char();
1817 	s->auth_proto = packet_get_string(NULL);
1818 	s->auth_data = packet_get_string(NULL);
1819 	s->screen = packet_get_int();
1820 	packet_check_eom();
1821 
1822 	success = session_setup_x11fwd(s);
1823 	if (!success) {
1824 		xfree(s->auth_proto);
1825 		xfree(s->auth_data);
1826 		s->auth_proto = NULL;
1827 		s->auth_data = NULL;
1828 		return (success);
1829 	}
1830 
1831 	/*
1832 	 * Create per session X authority file so that different sessions
1833 	 * don't contend for one common file. The reason for this is that
1834 	 * xauth(1) locking doesn't work too well over network filesystems.
1835 	 *
1836 	 * If mkdtemp() or open() fails then s->auth_file remains NULL which
1837 	 * means that we won't set XAUTHORITY variable in child's environment
1838 	 * and xauth(1) will use the default location for the authority file.
1839 	 */
1840 	if (mkdtemp(xauthdir) != NULL) {
1841 		s->auth_file = xmalloc(MAXPATHLEN);
1842 		snprintf(s->auth_file, MAXPATHLEN, "%s/xauthfile",
1843 		    xauthdir);
1844 		/*
1845 		 * we don't want that "creating new authority file" message to
1846 		 * be printed by xauth(1) so we must create that file
1847 		 * beforehand.
1848 		 */
1849 		if ((fd = open(s->auth_file, O_CREAT | O_EXCL | O_RDONLY,
1850 		    S_IRUSR | S_IWUSR)) == -1) {
1851 			error("failed to create the temporary X authority "
1852 			    "file %s: %.100s; will use the default one",
1853 			    s->auth_file, strerror(errno));
1854 			xfree(s->auth_file);
1855 			s->auth_file = NULL;
1856 			if (rmdir(xauthdir) == -1) {
1857 				error("cannot remove xauth directory %s: %.100s",
1858 				    xauthdir, strerror(errno));
1859 			}
1860 		} else {
1861 			close(fd);
1862 			debug("temporary X authority file %s created",
1863 			    s->auth_file);
1864 
1865 			/*
1866 			 * add a cleanup function to remove the temporary
1867 			 * xauth file in case we call fatal() (e.g., the
1868 			 * connection gets closed).
1869 			 */
1870 			fatal_add_cleanup(session_xauthfile_cleanup, (void *)s);
1871 		}
1872 	}
1873 	else {
1874 		error("failed to create a directory for the temporary X "
1875 		    "authority file: %.100s; will use the default xauth file",
1876 		    strerror(errno));
1877 	}
1878 
1879 	return (success);
1880 }
1881 
1882 static int
1883 session_shell_req(Session *s)
1884 {
1885 	packet_check_eom();
1886 	do_exec(s, NULL);
1887 	return 1;
1888 }
1889 
1890 static int
1891 session_exec_req(Session *s)
1892 {
1893 	u_int len;
1894 	char *command = packet_get_string(&len);
1895 	packet_check_eom();
1896 	do_exec(s, command);
1897 	xfree(command);
1898 	return 1;
1899 }
1900 
1901 static int
1902 session_auth_agent_req(Session *s)
1903 {
1904 	static int called = 0;
1905 	packet_check_eom();
1906 	if (no_agent_forwarding_flag) {
1907 		debug("session_auth_agent_req: no_agent_forwarding_flag");
1908 		return 0;
1909 	}
1910 	if (called) {
1911 		return 0;
1912 	} else {
1913 		called = 1;
1914 		return auth_input_request_forwarding(s->pw);
1915 	}
1916 }
1917 
1918 static int
1919 session_loc_env_check(char *var, char *val)
1920 {
1921 	char *current;
1922 	int cat, ret;
1923 
1924 	if (strcmp(var, "LANG") == 0)
1925 		cat = LC_ALL;
1926 	else if (strcmp(var, "LC_ALL") == 0)
1927 		cat = LC_ALL;
1928 	else if (strcmp(var, "LC_CTYPE") == 0)
1929 		cat = LC_CTYPE;
1930 	else if (strcmp(var, "LC_COLLATE") == 0)
1931 		cat = LC_COLLATE;
1932 	else if (strcmp(var, "LC_TIME") == 0)
1933 		cat = LC_TIME;
1934 	else if (strcmp(var, "LC_NUMERIC") == 0)
1935 		cat = LC_NUMERIC;
1936 	else if (strcmp(var, "LC_MONETARY") == 0)
1937 		cat = LC_MONETARY;
1938 	else if (strcmp(var, "LC_MESSAGES") == 0)
1939 		cat = LC_MESSAGES;
1940 
1941 	current = setlocale(cat, NULL);
1942 
1943 	ret = (setlocale(cat, val) != NULL);
1944 	(void) setlocale(cat, current);
1945 	return (ret);
1946 }
1947 
1948 static int
1949 session_env_req(Session *s)
1950 {
1951 	Channel *c;
1952 	char *var, *val, *e;
1953 	char **p;
1954 	size_t len;
1955 	int ret = 0;
1956 
1957 	/* Get var/val from the rest of this packet */
1958 	var = packet_get_string(NULL);
1959 	val = packet_get_string(NULL);
1960 
1961 	/*
1962 	 * We'll need the channel ID for the packet_send_debug messages,
1963 	 * so get it now.
1964 	 */
1965 	if ((c = channel_lookup(s->chanid)) == NULL)
1966 		goto done;	/* shouldn't happen! */
1967 
1968 	debug2("Received request for environment variable %s=%s", var, val);
1969 
1970 	/* For now allow only LANG and LC_* */
1971 	if (strcmp(var, "LANG") != 0 && strncmp(var, "LC_", 3) != 0) {
1972 		debug2("Rejecting request for environment variable %s", var);
1973 		goto done;
1974 	}
1975 
1976 	if (!session_loc_env_check(var, val)) {
1977 		packet_send_debug(gettext("Missing locale support for %s=%s"),
1978 			var, val);
1979 		goto done;
1980 	}
1981 
1982 	packet_send_debug(gettext("Channel %d set: %s=%s"), c->remote_id,
1983 		var, val);
1984 
1985 	/*
1986 	 * Always append new environment variables without regard to old
1987 	 * ones being overriden.  The way these are actually added to
1988 	 * the environment of the session process later settings
1989 	 * override earlier ones; see copy_environment().
1990 	 */
1991 	if (s->env == NULL) {
1992 		char **env;
1993 
1994 		env = xmalloc(sizeof (char **) * 2);
1995 		memset(env, 0, sizeof (char **) * 2);
1996 
1997 		s->env = env;
1998 		p = env;
1999 	} else {
2000 		for (p = s->env; *p != NULL ; p++);
2001 
2002 		s->env = xrealloc(s->env, (p - s->env + 2) * sizeof (char **));
2003 
2004 		for (p = s->env; *p != NULL ; p++);
2005 	}
2006 
2007 	len = snprintf(NULL, 0, "%s=%s", var, val);
2008 	e = xmalloc(len + 1);
2009 	(void) snprintf(e, len + 1, "%s=%s", var, val);
2010 
2011 	(*p++) = e;
2012 	*p = NULL;
2013 
2014 	ret = 1;
2015 
2016 done:
2017 	xfree(var);
2018 	xfree(val);
2019 
2020 	return (ret);
2021 }
2022 
2023 static void
2024 session_free_env(char ***envp)
2025 {
2026 	char **env, **p;
2027 
2028 	if (envp == NULL || *envp == NULL)
2029 		return;
2030 
2031 	env = *envp;
2032 
2033 	*envp = NULL;
2034 
2035 	for (p = env; *p != NULL; p++)
2036 		xfree(*p);
2037 
2038 	xfree(env);
2039 }
2040 
2041 int
2042 session_input_channel_req(Channel *c, const char *rtype)
2043 {
2044 	int success = 0;
2045 	Session *s;
2046 
2047 	if ((s = session_by_channel(c->self)) == NULL) {
2048 		log("session_input_channel_req: no session %d req %.100s",
2049 		    c->self, rtype);
2050 		return 0;
2051 	}
2052 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
2053 
2054 	/*
2055 	 * a session is in LARVAL state until a shell, a command
2056 	 * or a subsystem is executed
2057 	 */
2058 	if (c->type == SSH_CHANNEL_LARVAL) {
2059 		if (strcmp(rtype, "shell") == 0) {
2060 			success = session_shell_req(s);
2061 		} else if (strcmp(rtype, "exec") == 0) {
2062 			success = session_exec_req(s);
2063 		} else if (strcmp(rtype, "pty-req") == 0) {
2064 			success =  session_pty_req(s);
2065 		} else if (strcmp(rtype, "x11-req") == 0) {
2066 			success = session_x11_req(s);
2067 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2068 			success = session_auth_agent_req(s);
2069 		} else if (strcmp(rtype, "subsystem") == 0) {
2070 			success = session_subsystem_req(s);
2071 		} else if (strcmp(rtype, "env") == 0) {
2072 			success = session_env_req(s);
2073 		}
2074 	}
2075 	if (strcmp(rtype, "window-change") == 0) {
2076 		success = session_window_change_req(s);
2077 	}
2078 	return success;
2079 }
2080 
2081 void
2082 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2083 {
2084 	if (!compat20)
2085 		fatal("session_set_fds: called for proto != 2.0");
2086 	/*
2087 	 * now that have a child and a pipe to the child,
2088 	 * we can activate our channel and register the fd's
2089 	 */
2090 	if (s->chanid == -1)
2091 		fatal("no channel for session %d", s->self);
2092 	channel_set_fds(s->chanid,
2093 	    fdout, fdin, fderr,
2094 	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2095 	    1,
2096 	    CHAN_SES_WINDOW_DEFAULT);
2097 }
2098 
2099 /*
2100  * Function to perform pty cleanup. Also called if we get aborted abnormally
2101  * (e.g., due to a dropped connection).
2102  */
2103 void
2104 session_pty_cleanup2(void *session)
2105 {
2106 	Session *s = session;
2107 
2108 	if (s == NULL) {
2109 		error("session_pty_cleanup: no session");
2110 		return;
2111 	}
2112 	if (s->ttyfd == -1)
2113 		return;
2114 
2115 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2116 
2117 #ifdef USE_PAM
2118 	session_do_pam(s, 0);
2119 #endif /* USE_PAM */
2120 
2121 	/* Record that the user has logged out. */
2122 	if (s->pid != 0) {
2123 		debug3("Recording SSHv2 channel logout in utmpx/wtmpx");
2124 #ifdef ALTPRIVSEP
2125 		altprivsep_record_logout(s->pid);
2126 #endif /* ALTPRIVSEP */
2127 	}
2128 
2129 	/* Release the pseudo-tty. */
2130 	if (getuid() == 0)
2131 		pty_release(s->tty);
2132 
2133 	/*
2134 	 * Close the server side of the socket pairs.  We must do this after
2135 	 * the pty cleanup, so that another process doesn't get this pty
2136 	 * while we're still cleaning up.
2137 	 */
2138 	if (close(s->ptymaster) < 0)
2139 		error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2140 
2141 	/* unlink pty from session */
2142 	s->ttyfd = -1;
2143 }
2144 
2145 void
2146 session_pty_cleanup(void *session)
2147 {
2148 	session_pty_cleanup2(session);
2149 }
2150 
2151 /*
2152  * We use a different temporary X authority file per every session so we
2153  * should remove those files when fatal() is called.
2154  */
2155 void
2156 session_xauthfile_cleanup(void *session)
2157 {
2158 	Session *s = session;
2159 
2160 	if (s == NULL) {
2161 		error("session_xauthfile_cleanup: no session");
2162 		return;
2163 	}
2164 
2165 	debug("session_xauthfile_cleanup: session %d removing %s", s->self,
2166 	    s->auth_file);
2167 
2168 	if (unlink(s->auth_file) == -1) {
2169 		error("session_xauthfile_cleanup: cannot remove xauth file: "
2170 		    "%.100s", strerror(errno));
2171 		return;
2172 	}
2173 
2174 	/* dirname() will modify s->auth_file but that's ok */
2175 	if (rmdir(dirname(s->auth_file)) == -1) {
2176 		error("session_xauthfile_cleanup: "
2177 		    "cannot remove xauth directory: %.100s", strerror(errno));
2178 		return;
2179 	}
2180 }
2181 
2182 static char *
2183 sig2name(int sig)
2184 {
2185 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2186 	SSH_SIG(ABRT);
2187 	SSH_SIG(ALRM);
2188 	SSH_SIG(FPE);
2189 	SSH_SIG(HUP);
2190 	SSH_SIG(ILL);
2191 	SSH_SIG(INT);
2192 	SSH_SIG(KILL);
2193 	SSH_SIG(PIPE);
2194 	SSH_SIG(QUIT);
2195 	SSH_SIG(SEGV);
2196 	SSH_SIG(TERM);
2197 	SSH_SIG(USR1);
2198 	SSH_SIG(USR2);
2199 #undef	SSH_SIG
2200 	return "SIG@openssh.com";
2201 }
2202 
2203 static void
2204 session_exit_message(Session *s, int status)
2205 {
2206 	Channel *c;
2207 
2208 	if ((c = channel_lookup(s->chanid)) == NULL)
2209 		fatal("session_exit_message: session %d: no channel %d",
2210 		    s->self, s->chanid);
2211 	debug("session_exit_message: session %d channel %d pid %ld",
2212 	    s->self, s->chanid, (long)s->pid);
2213 
2214 	if (WIFEXITED(status)) {
2215 		channel_request_start(s->chanid, "exit-status", 0);
2216 		packet_put_int(WEXITSTATUS(status));
2217 		packet_send();
2218 	} else if (WIFSIGNALED(status)) {
2219 		channel_request_start(s->chanid, "exit-signal", 0);
2220 		packet_put_cstring(sig2name(WTERMSIG(status)));
2221 #ifdef WCOREDUMP
2222 		packet_put_char(WCOREDUMP(status));
2223 #else /* WCOREDUMP */
2224 		packet_put_char(0);
2225 #endif /* WCOREDUMP */
2226 		packet_put_cstring("");
2227 		packet_put_cstring("");
2228 		packet_send();
2229 	} else {
2230 		/* Some weird exit cause.  Just exit. */
2231 		packet_disconnect("wait returned status %04x.", status);
2232 	}
2233 
2234 	/* Ok to close channel now */
2235 	channel_set_wait_for_exit(s->chanid, 0);
2236 
2237 	/* disconnect channel */
2238 	debug("session_exit_message: release channel %d", s->chanid);
2239 	channel_cancel_cleanup(s->chanid);
2240 	/*
2241 	 * emulate a write failure with 'chan_write_failed', nobody will be
2242 	 * interested in data we write.
2243 	 * Note that we must not call 'chan_read_failed', since there could
2244 	 * be some more data waiting in the pipe.
2245 	 */
2246 	if (c->ostate != CHAN_OUTPUT_CLOSED)
2247 		chan_write_failed(c);
2248 	s->chanid = -1;
2249 }
2250 
2251 void
2252 session_close(Session *s)
2253 {
2254 	debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2255 	if (s->ttyfd != -1) {
2256 		fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2257 		session_pty_cleanup(s);
2258 	}
2259 	if (s->auth_file != NULL) {
2260 		fatal_remove_cleanup(session_xauthfile_cleanup, (void *)s);
2261 		session_xauthfile_cleanup(s);
2262 		xfree(s->auth_file);
2263 	}
2264 	if (s->term)
2265 		xfree(s->term);
2266 	if (s->display)
2267 		xfree(s->display);
2268 	if (s->auth_display)
2269 		xfree(s->auth_display);
2270 	if (s->auth_data)
2271 		xfree(s->auth_data);
2272 	if (s->auth_proto)
2273 		xfree(s->auth_proto);
2274 	if (s->command)
2275 		xfree(s->command);
2276 	session_free_env(&s->env);
2277 	s->used = 0;
2278 	session_proctitle(s);
2279 }
2280 
2281 void
2282 session_close_by_pid(pid_t pid, int status)
2283 {
2284 	Session *s = session_by_pid(pid);
2285 	if (s == NULL) {
2286 		debug("session_close_by_pid: no session for pid %ld",
2287 		    (long)pid);
2288 		return;
2289 	}
2290 	if (s->chanid != -1)
2291 		session_exit_message(s, status);
2292 	session_close(s);
2293 }
2294 
2295 /*
2296  * This is called when a channel dies before the session 'child' itself dies.
2297  * It can happen for example if we exit from an interactive shell before we
2298  * exit from forwarded X11 applications.
2299  */
2300 void
2301 session_close_by_channel(int id, void *arg)
2302 {
2303 	Session *s = session_by_channel(id);
2304 	if (s == NULL) {
2305 		debug("session_close_by_channel: no session for id %d", id);
2306 		return;
2307 	}
2308 	debug("session_close_by_channel: channel %d child %ld",
2309 	    id, (long)s->pid);
2310 	if (s->pid != 0) {
2311 		debug("session_close_by_channel: channel %d: has child", id);
2312 		/*
2313 		 * delay detach of session, but release pty, since
2314 		 * the fd's to the child are already closed
2315 		 */
2316 		if (s->ttyfd != -1) {
2317 			fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2318 			session_pty_cleanup(s);
2319 		}
2320 		return;
2321 	}
2322 	/* detach by removing callback */
2323 	channel_cancel_cleanup(s->chanid);
2324 	s->chanid = -1;
2325 	session_close(s);
2326 }
2327 
2328 void
2329 session_destroy_all(void (*closefunc)(Session *))
2330 {
2331 	int i;
2332 	for (i = 0; i < MAX_SESSIONS; i++) {
2333 		Session *s = &sessions[i];
2334 		if (s->used) {
2335 			if (closefunc != NULL)
2336 				closefunc(s);
2337 			else
2338 				session_close(s);
2339 		}
2340 	}
2341 }
2342 
2343 static char *
2344 session_tty_list(void)
2345 {
2346 	static char buf[1024];
2347 	int i;
2348 	buf[0] = '\0';
2349 	for (i = 0; i < MAX_SESSIONS; i++) {
2350 		Session *s = &sessions[i];
2351 		if (s->used && s->ttyfd != -1) {
2352 			if (buf[0] != '\0')
2353 				strlcat(buf, ",", sizeof buf);
2354 			strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2355 		}
2356 	}
2357 	if (buf[0] == '\0')
2358 		strlcpy(buf, "notty", sizeof buf);
2359 	return buf;
2360 }
2361 
2362 void
2363 session_proctitle(Session *s)
2364 {
2365 	if (s->pw == NULL)
2366 		error("no user for session %d", s->self);
2367 	else
2368 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2369 }
2370 
2371 int
2372 session_setup_x11fwd(Session *s)
2373 {
2374 	struct stat st;
2375 	char display[512], auth_display[512];
2376 	char hostname[MAXHOSTNAMELEN];
2377 
2378 	if (no_x11_forwarding_flag) {
2379 		packet_send_debug("X11 forwarding disabled in user configuration file.");
2380 		return 0;
2381 	}
2382 	if (!options.x11_forwarding) {
2383 		debug("X11 forwarding disabled in server configuration file.");
2384 		return 0;
2385 	}
2386 	if (!options.xauth_location ||
2387 	    (stat(options.xauth_location, &st) == -1)) {
2388 		packet_send_debug("No xauth program; cannot forward with spoofing.");
2389 		return 0;
2390 	}
2391 	if (s->display != NULL) {
2392 		debug("X11 display already set.");
2393 		return 0;
2394 	}
2395 	if (x11_create_display_inet(options.x11_display_offset,
2396 	    options.x11_use_localhost, s->single_connection,
2397 	    &s->display_number) == -1) {
2398 		debug("x11_create_display_inet failed.");
2399 		return 0;
2400 	}
2401 
2402 	/* Set up a suitable value for the DISPLAY variable. */
2403 	if (gethostname(hostname, sizeof(hostname)) < 0)
2404 		fatal("gethostname: %.100s", strerror(errno));
2405 	/*
2406 	 * auth_display must be used as the displayname when the
2407 	 * authorization entry is added with xauth(1).  This will be
2408 	 * different than the DISPLAY string for localhost displays.
2409 	 */
2410 	if (options.x11_use_localhost) {
2411 		snprintf(display, sizeof display, "localhost:%u.%u",
2412 		    s->display_number, s->screen);
2413 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2414 		    s->display_number, s->screen);
2415 		s->display = xstrdup(display);
2416 		s->auth_display = xstrdup(auth_display);
2417 	} else {
2418 #ifdef IPADDR_IN_DISPLAY
2419 		struct hostent *he;
2420 		struct in_addr my_addr;
2421 
2422 		he = gethostbyname(hostname);
2423 		if (he == NULL) {
2424 			error("Can't get IP address for X11 DISPLAY.");
2425 			packet_send_debug("Can't get IP address for X11 DISPLAY.");
2426 			return 0;
2427 		}
2428 		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2429 		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2430 		    s->display_number, s->screen);
2431 #else
2432 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2433 		    s->display_number, s->screen);
2434 #endif
2435 		s->display = xstrdup(display);
2436 		s->auth_display = xstrdup(display);
2437 	}
2438 
2439 	return 1;
2440 }
2441 
2442 #ifdef USE_PAM
2443 int session_do_pam_conv(int, struct pam_message **,
2444 			struct pam_response **, void *);
2445 
2446 static struct pam_conv session_pam_conv = {
2447 	session_do_pam_conv,
2448 	NULL
2449 };
2450 
2451 static void
2452 session_do_pam(Session *s, int do_open)
2453 {
2454 	int pam_retval;
2455 	char *where, *old_tty, *old_tty_copy = NULL;
2456 	struct pam_conv old_conv, *old_conv_ptr;
2457 
2458 	if (!s || !s->authctxt || !s->authctxt->pam || !s->authctxt->pam->h)
2459 		return;
2460 
2461 	/* Save current PAM item values */
2462 	where = "getting PAM_CONV";
2463 	pam_retval = pam_get_item(s->authctxt->pam->h, PAM_CONV,
2464 				  (void **) &old_conv_ptr);
2465 	if (pam_retval != PAM_SUCCESS)
2466 		goto done;
2467 	old_conv = *old_conv_ptr;
2468 
2469 	where = "getting PAM_TTY";
2470 	pam_retval = pam_get_item(s->authctxt->pam->h, PAM_TTY,
2471 				  (void **) &old_tty);
2472 	if (pam_retval != PAM_SUCCESS)
2473 		goto done;
2474 	old_tty_copy = xstrdup(old_tty);
2475 
2476 	/* Change PAM_TTY and PAM_CONV items */
2477 	where = "setting PAM_TTY";
2478 	pam_retval = pam_set_item(s->authctxt->pam->h, PAM_TTY, s->tty);
2479 	if (pam_retval != PAM_SUCCESS)
2480 		goto done;
2481 
2482 	where = "setting PAM_CONV";
2483 	session_pam_conv.appdata_ptr = s;
2484 	pam_retval = pam_set_item(s->authctxt->pam->h,
2485 				  PAM_CONV, &session_pam_conv);
2486 	if (pam_retval != PAM_SUCCESS)
2487 		goto done;
2488 
2489 	/* Call pam_open/close_session() */
2490 	if (do_open) {
2491 		where = "calling pam_open_session()";
2492 		pam_retval = pam_open_session(s->authctxt->pam->h, 0);
2493 	}
2494 	else {
2495 		where = "calling pam_close_session()";
2496 		pam_retval = pam_close_session(s->authctxt->pam->h, 0);
2497 	}
2498 
2499 	/* Reset PAM_TTY and PAM_CONV items to previous values */
2500 	where = "setting PAM_TTY";
2501 	pam_retval = pam_set_item(s->authctxt->pam->h, PAM_TTY, old_tty_copy);
2502 	if (pam_retval != PAM_SUCCESS)
2503 		goto done;
2504 
2505 	where = "setting PAM_CONV";
2506 	pam_retval = pam_set_item(s->authctxt->pam->h, PAM_CONV, &old_conv);
2507 	if (pam_retval != PAM_SUCCESS)
2508 		goto done;
2509 
2510 	session_pam_conv.appdata_ptr = NULL;
2511 
2512 done:
2513 	if (old_tty_copy)
2514 		xfree(old_tty_copy);
2515 
2516 	if (pam_retval == PAM_SUCCESS)
2517 		return;
2518 
2519 	/* fatal()? probably not... */
2520 	log("PAM failed[%d] while %s: %s", pam_retval, where,
2521 	    PAM_STRERROR(s->authctxt->pam->h, pam_retval));
2522 }
2523 
2524 int
2525 session_do_pam_conv(int num_prompts,
2526 		    struct pam_message **prompts,
2527 		    struct pam_response **resp,
2528 		    void *app_data)
2529 {
2530 	Session *s = (Session *) app_data;
2531 
2532 	struct pam_response *reply;
2533 	int count;
2534 	char *prompt;
2535 
2536 	if (channel_lookup(s->chanid) == NULL)
2537 		return PAM_CONV_ERR;
2538 
2539 	/* PAM will free this later */
2540 	reply = xmalloc(num_prompts * sizeof(*reply));
2541 
2542 	(void) memset(reply, 0, num_prompts * sizeof(*reply));
2543 	for (count = 0; count < num_prompts; count++) {
2544 		switch(PAM_MSG_MEMBER(prompts, count, msg_style)) {
2545 		case PAM_TEXT_INFO:
2546 			/* Write to stdout of channel */
2547 			prompt = PAM_MSG_MEMBER(prompts, count, msg);
2548 			if (prompt != NULL && s->ttyfd != -1) {
2549 				debug2("session_do_pam_conv: text info "
2550 				       "prompt: %s", prompt);
2551 				(void) write(s->ttyfd, prompt, strlen(prompt));
2552 				(void) write(s->ttyfd, "\n", 1);
2553 			}
2554 			reply[count].resp = xstrdup("");
2555 			reply[count].resp_retcode = PAM_SUCCESS;
2556 			break;
2557 		case PAM_ERROR_MSG:
2558 			/* Write to stderr of channel */
2559 			prompt = PAM_MSG_MEMBER(prompts, count, msg);
2560 			if (prompt != NULL && s->ttyfd != -1) {
2561 				debug2("session_do_pam_conv: error "
2562 				       "prompt: %s", prompt);
2563 				(void) write(s->ttyfd, prompt, strlen(prompt));
2564 				(void) write(s->ttyfd, "\n", 1);
2565 			}
2566 			reply[count].resp = xstrdup("");
2567 			reply[count].resp_retcode = PAM_SUCCESS;
2568 			break;
2569 		case PAM_PROMPT_ECHO_ON:
2570 		case PAM_PROMPT_ECHO_OFF:
2571 		    /*
2572 		     * XXX Someday add support for echo on/off prompts
2573 		     *     here on sessions with ttys.
2574 		     */
2575 		default:
2576 			xfree(reply);
2577 			return PAM_CONV_ERR;
2578 		}
2579 	}
2580 
2581 	*resp = reply;
2582 
2583 	return PAM_SUCCESS;
2584 }
2585 #endif /* USE_PAM */
2586 
2587 static void
2588 do_authenticated2(Authctxt *authctxt)
2589 {
2590 	server_loop2(authctxt);
2591 }
2592 
2593 /*
2594  * Drop the privileges. We need this for the in-process SFTP server only. For
2595  * the shell and the external subsystem the exec(2) call will do the P = E = I
2596  * assignment itself. Never change the privileges if the connecting user is
2597  * root. See privileges(5) if the terminology used here is not known to you.
2598  */
2599 static void
2600 drop_privs(uid_t uid)
2601 {
2602 	priv_set_t *priv_inherit;
2603 
2604 	/* If root is connecting we are done. */
2605 	if (uid == 0)
2606 		return;
2607 
2608 	if ((priv_inherit = priv_allocset()) == NULL)
2609 		fatal("priv_allocset: %s", strerror(errno));
2610 	if (getppriv(PRIV_INHERITABLE, priv_inherit) != 0)
2611 		fatal("getppriv: %s", strerror(errno));
2612 
2613 	/*
2614 	 * This will limit E as well. Note that before this P was a
2615 	 * superset of I, see permanently_set_uid().
2616 	 */
2617 	if (setppriv(PRIV_SET, PRIV_PERMITTED, priv_inherit) == -1)
2618 		fatal("setppriv: %s", strerror(errno));
2619 
2620 	priv_freeset(priv_inherit);
2621 
2622 	/*
2623 	 * By manipulating the P set above we entered a PA mode which we
2624 	 * do not need to retain in.
2625 	 */
2626 	if (setpflags(PRIV_AWARE, 0) == -1)
2627 		fatal("setpflags: %s", strerror(errno));
2628 }
2629