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