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