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