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