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