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