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