xref: /dragonfly/crypto/openssh/session.c (revision ad9f8794)
1 /* $OpenBSD: session.c,v 1.258 2010/11/25 04:10:09 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 	    options.ip_qos_interactive, options.ip_qos_bulk);
591 
592 	/*
593 	 * Clear loginmsg, since it's the child's responsibility to display
594 	 * it to the user, otherwise multiple sessions may accumulate
595 	 * multiple copies of the login messages.
596 	 */
597 	buffer_clear(&loginmsg);
598 
599 #ifdef USE_PIPES
600 	/* We are the parent.  Close the child sides of the pipes. */
601 	close(pin[0]);
602 	close(pout[1]);
603 	close(perr[1]);
604 
605 	if (compat20) {
606 		session_set_fds(s, pin[1], pout[0], perr[0],
607 		    s->is_subsystem, 0);
608 	} else {
609 		/* Enter the interactive session. */
610 		server_loop(pid, pin[1], pout[0], perr[0]);
611 		/* server_loop has closed pin[1], pout[0], and perr[0]. */
612 	}
613 #else
614 	/* We are the parent.  Close the child sides of the socket pairs. */
615 	close(inout[0]);
616 	close(err[0]);
617 
618 	/*
619 	 * Enter the interactive session.  Note: server_loop must be able to
620 	 * handle the case that fdin and fdout are the same.
621 	 */
622 	if (compat20) {
623 		session_set_fds(s, inout[1], inout[1], err[1],
624 		    s->is_subsystem, 0);
625 	} else {
626 		server_loop(pid, inout[1], inout[1], err[1]);
627 		/* server_loop has closed inout[1] and err[1]. */
628 	}
629 #endif
630 	return 0;
631 }
632 
633 /*
634  * This is called to fork and execute a command when we have a tty.  This
635  * will call do_child from the child, and server_loop from the parent after
636  * setting up file descriptors, controlling tty, updating wtmp, utmp,
637  * lastlog, and other such operations.
638  */
639 int
640 do_exec_pty(Session *s, const char *command)
641 {
642 	int fdout, ptyfd, ttyfd, ptymaster;
643 	pid_t pid;
644 
645 	if (s == NULL)
646 		fatal("do_exec_pty: no session");
647 	ptyfd = s->ptyfd;
648 	ttyfd = s->ttyfd;
649 
650 	/*
651 	 * Create another descriptor of the pty master side for use as the
652 	 * standard input.  We could use the original descriptor, but this
653 	 * simplifies code in server_loop.  The descriptor is bidirectional.
654 	 * Do this before forking (and cleanup in the child) so as to
655 	 * detect and gracefully fail out-of-fd conditions.
656 	 */
657 	if ((fdout = dup(ptyfd)) < 0) {
658 		error("%s: dup #1: %s", __func__, strerror(errno));
659 		close(ttyfd);
660 		close(ptyfd);
661 		return -1;
662 	}
663 	/* we keep a reference to the pty master */
664 	if ((ptymaster = dup(ptyfd)) < 0) {
665 		error("%s: dup #2: %s", __func__, strerror(errno));
666 		close(ttyfd);
667 		close(ptyfd);
668 		close(fdout);
669 		return -1;
670 	}
671 
672 	/* Fork the child. */
673 	switch ((pid = fork())) {
674 	case -1:
675 		error("%s: fork: %.100s", __func__, strerror(errno));
676 		close(fdout);
677 		close(ptymaster);
678 		close(ttyfd);
679 		close(ptyfd);
680 		return -1;
681 	case 0:
682 		is_child = 1;
683 
684 		close(fdout);
685 		close(ptymaster);
686 
687 		/* Child.  Reinitialize the log because the pid has changed. */
688 		log_init(__progname, options.log_level,
689 		    options.log_facility, log_stderr);
690 		/* Close the master side of the pseudo tty. */
691 		close(ptyfd);
692 
693 		/* Make the pseudo tty our controlling tty. */
694 		pty_make_controlling_tty(&ttyfd, s->tty);
695 
696 		/* Redirect stdin/stdout/stderr from the pseudo tty. */
697 		if (dup2(ttyfd, 0) < 0)
698 			error("dup2 stdin: %s", strerror(errno));
699 		if (dup2(ttyfd, 1) < 0)
700 			error("dup2 stdout: %s", strerror(errno));
701 		if (dup2(ttyfd, 2) < 0)
702 			error("dup2 stderr: %s", strerror(errno));
703 
704 		/* Close the extra descriptor for the pseudo tty. */
705 		close(ttyfd);
706 
707 		/* record login, etc. similar to login(1) */
708 #ifndef HAVE_OSF_SIA
709 		if (!(options.use_login && command == NULL)) {
710 #ifdef _UNICOS
711 			cray_init_job(s->pw); /* set up cray jid and tmpdir */
712 #endif /* _UNICOS */
713 			do_login(s, command);
714 		}
715 # ifdef LOGIN_NEEDS_UTMPX
716 		else
717 			do_pre_login(s);
718 # endif
719 #endif
720 		/*
721 		 * Do common processing for the child, such as execing
722 		 * the command.
723 		 */
724 		do_child(s, command);
725 		/* NOTREACHED */
726 	default:
727 		break;
728 	}
729 
730 #ifdef _UNICOS
731 	signal(WJSIGNAL, cray_job_termination_handler);
732 #endif /* _UNICOS */
733 #ifdef HAVE_CYGWIN
734 	cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
735 #endif
736 
737 	s->pid = pid;
738 
739 	/* Parent.  Close the slave side of the pseudo tty. */
740 	close(ttyfd);
741 
742 	/* Enter interactive session. */
743 	s->ptymaster = ptymaster;
744 	packet_set_interactive(1,
745 	    options.ip_qos_interactive, options.ip_qos_bulk);
746 	if (compat20) {
747 		session_set_fds(s, ptyfd, fdout, -1, 1, 1);
748 	} else {
749 		server_loop(pid, ptyfd, fdout, -1);
750 		/* server_loop _has_ closed ptyfd and fdout. */
751 	}
752 	return 0;
753 }
754 
755 #ifdef LOGIN_NEEDS_UTMPX
756 static void
757 do_pre_login(Session *s)
758 {
759 	socklen_t fromlen;
760 	struct sockaddr_storage from;
761 	pid_t pid = getpid();
762 
763 	/*
764 	 * Get IP address of client. If the connection is not a socket, let
765 	 * the address be 0.0.0.0.
766 	 */
767 	memset(&from, 0, sizeof(from));
768 	fromlen = sizeof(from);
769 	if (packet_connection_is_on_socket()) {
770 		if (getpeername(packet_get_connection_in(),
771 		    (struct sockaddr *)&from, &fromlen) < 0) {
772 			debug("getpeername: %.100s", strerror(errno));
773 			cleanup_exit(255);
774 		}
775 	}
776 
777 	record_utmp_only(pid, s->tty, s->pw->pw_name,
778 	    get_remote_name_or_ip(utmp_len, options.use_dns),
779 	    (struct sockaddr *)&from, fromlen);
780 }
781 #endif
782 
783 /*
784  * This is called to fork and execute a command.  If another command is
785  * to be forced, execute that instead.
786  */
787 int
788 do_exec(Session *s, const char *command)
789 {
790 	int ret;
791 
792 	if (options.adm_forced_command) {
793 		original_command = command;
794 		command = options.adm_forced_command;
795 		if (IS_INTERNAL_SFTP(command)) {
796 			s->is_subsystem = s->is_subsystem ?
797 			    SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
798 		} else if (s->is_subsystem)
799 			s->is_subsystem = SUBSYSTEM_EXT;
800 		debug("Forced command (config) '%.900s'", command);
801 	} else if (forced_command) {
802 		original_command = command;
803 		command = forced_command;
804 		if (IS_INTERNAL_SFTP(command)) {
805 			s->is_subsystem = s->is_subsystem ?
806 			    SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
807 		} else if (s->is_subsystem)
808 			s->is_subsystem = SUBSYSTEM_EXT;
809 		debug("Forced command (key option) '%.900s'", command);
810 	}
811 
812 #ifdef SSH_AUDIT_EVENTS
813 	if (command != NULL)
814 		PRIVSEP(audit_run_command(command));
815 	else if (s->ttyfd == -1) {
816 		char *shell = s->pw->pw_shell;
817 
818 		if (shell[0] == '\0')	/* empty shell means /bin/sh */
819 			shell =_PATH_BSHELL;
820 		PRIVSEP(audit_run_command(shell));
821 	}
822 #endif
823 	if (s->ttyfd != -1)
824 		ret = do_exec_pty(s, command);
825 	else
826 		ret = do_exec_no_pty(s, command);
827 
828 	original_command = NULL;
829 
830 	/*
831 	 * Clear loginmsg: it's the child's responsibility to display
832 	 * it to the user, otherwise multiple sessions may accumulate
833 	 * multiple copies of the login messages.
834 	 */
835 	buffer_clear(&loginmsg);
836 
837 	return ret;
838 }
839 
840 /* administrative, login(1)-like work */
841 void
842 do_login(Session *s, const char *command)
843 {
844 	socklen_t fromlen;
845 	struct sockaddr_storage from;
846 	struct passwd * pw = s->pw;
847 	pid_t pid = getpid();
848 
849 	/*
850 	 * Get IP address of client. If the connection is not a socket, let
851 	 * the address be 0.0.0.0.
852 	 */
853 	memset(&from, 0, sizeof(from));
854 	fromlen = sizeof(from);
855 	if (packet_connection_is_on_socket()) {
856 		if (getpeername(packet_get_connection_in(),
857 		    (struct sockaddr *)&from, &fromlen) < 0) {
858 			debug("getpeername: %.100s", strerror(errno));
859 			cleanup_exit(255);
860 		}
861 	}
862 
863 	/* Record that there was a login on that tty from the remote host. */
864 	if (!use_privsep)
865 		record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
866 		    get_remote_name_or_ip(utmp_len,
867 		    options.use_dns),
868 		    (struct sockaddr *)&from, fromlen);
869 
870 #ifdef USE_PAM
871 	/*
872 	 * If password change is needed, do it now.
873 	 * This needs to occur before the ~/.hushlogin check.
874 	 */
875 	if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
876 		display_loginmsg();
877 		do_pam_chauthtok();
878 		s->authctxt->force_pwchange = 0;
879 		/* XXX - signal [net] parent to enable forwardings */
880 	}
881 #endif
882 
883 	if (check_quietlogin(s, command))
884 		return;
885 
886 	display_loginmsg();
887 
888 	do_motd();
889 }
890 
891 /*
892  * Display the message of the day.
893  */
894 void
895 do_motd(void)
896 {
897 	FILE *f;
898 	char buf[256];
899 #ifdef HAVE_LOGIN_CAP
900 	const char *fname;
901 #endif
902 
903 #ifdef HAVE_LOGIN_CAP
904 	fname = login_getcapstr(lc, "copyright", NULL, NULL);
905 	if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
906 		while (fgets(buf, sizeof(buf), f) != NULL)
907 			fputs(buf, stdout);
908 			fclose(f);
909 	} else
910 #endif /* HAVE_LOGIN_CAP */
911 		(void)printf("%s\n\t%s %s\n",
912 	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
913 	"The Regents of the University of California. ",
914 	"All rights reserved.");
915 
916 	(void)printf("\n");
917 
918 	if (options.print_motd) {
919 #ifdef HAVE_LOGIN_CAP
920 		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
921 		    "/etc/motd"), "r");
922 #else
923 		f = fopen("/etc/motd", "r");
924 #endif
925 		if (f) {
926 			while (fgets(buf, sizeof(buf), f))
927 				fputs(buf, stdout);
928 			fclose(f);
929 		}
930 	}
931 }
932 
933 
934 /*
935  * Check for quiet login, either .hushlogin or command given.
936  */
937 int
938 check_quietlogin(Session *s, const char *command)
939 {
940 	char buf[256];
941 	struct passwd *pw = s->pw;
942 	struct stat st;
943 
944 	/* Return 1 if .hushlogin exists or a command given. */
945 	if (command != NULL)
946 		return 1;
947 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
948 #ifdef HAVE_LOGIN_CAP
949 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
950 		return 1;
951 #else
952 	if (stat(buf, &st) >= 0)
953 		return 1;
954 #endif
955 	return 0;
956 }
957 
958 /*
959  * Sets the value of the given variable in the environment.  If the variable
960  * already exists, its value is overridden.
961  */
962 void
963 child_set_env(char ***envp, u_int *envsizep, const char *name,
964 	const char *value)
965 {
966 	char **env;
967 	u_int envsize;
968 	u_int i, namelen;
969 
970 	/*
971 	 * If we're passed an uninitialized list, allocate a single null
972 	 * entry before continuing.
973 	 */
974 	if (*envp == NULL && *envsizep == 0) {
975 		*envp = xmalloc(sizeof(char *));
976 		*envp[0] = NULL;
977 		*envsizep = 1;
978 	}
979 
980 	/*
981 	 * Find the slot where the value should be stored.  If the variable
982 	 * already exists, we reuse the slot; otherwise we append a new slot
983 	 * at the end of the array, expanding if necessary.
984 	 */
985 	env = *envp;
986 	namelen = strlen(name);
987 	for (i = 0; env[i]; i++)
988 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
989 			break;
990 	if (env[i]) {
991 		/* Reuse the slot. */
992 		xfree(env[i]);
993 	} else {
994 		/* New variable.  Expand if necessary. */
995 		envsize = *envsizep;
996 		if (i >= envsize - 1) {
997 			if (envsize >= 1000)
998 				fatal("child_set_env: too many env vars");
999 			envsize += 50;
1000 			env = (*envp) = xrealloc(env, envsize, sizeof(char *));
1001 			*envsizep = envsize;
1002 		}
1003 		/* Need to set the NULL pointer at end of array beyond the new slot. */
1004 		env[i + 1] = NULL;
1005 	}
1006 
1007 	/* Allocate space and format the variable in the appropriate slot. */
1008 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1009 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1010 }
1011 
1012 /*
1013  * Reads environment variables from the given file and adds/overrides them
1014  * into the environment.  If the file does not exist, this does nothing.
1015  * Otherwise, it must consist of empty lines, comments (line starts with '#')
1016  * and assignments of the form name=value.  No other forms are allowed.
1017  */
1018 static void
1019 read_environment_file(char ***env, u_int *envsize,
1020 	const char *filename)
1021 {
1022 	FILE *f;
1023 	char buf[4096];
1024 	char *cp, *value;
1025 	u_int lineno = 0;
1026 
1027 	f = fopen(filename, "r");
1028 	if (!f)
1029 		return;
1030 
1031 	while (fgets(buf, sizeof(buf), f)) {
1032 		if (++lineno > 1000)
1033 			fatal("Too many lines in environment file %s", filename);
1034 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1035 			;
1036 		if (!*cp || *cp == '#' || *cp == '\n')
1037 			continue;
1038 
1039 		cp[strcspn(cp, "\n")] = '\0';
1040 
1041 		value = strchr(cp, '=');
1042 		if (value == NULL) {
1043 			fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1044 			    filename);
1045 			continue;
1046 		}
1047 		/*
1048 		 * Replace the equals sign by nul, and advance value to
1049 		 * the value string.
1050 		 */
1051 		*value = '\0';
1052 		value++;
1053 		child_set_env(env, envsize, cp, value);
1054 	}
1055 	fclose(f);
1056 }
1057 
1058 #ifdef HAVE_ETC_DEFAULT_LOGIN
1059 /*
1060  * Return named variable from specified environment, or NULL if not present.
1061  */
1062 static char *
1063 child_get_env(char **env, const char *name)
1064 {
1065 	int i;
1066 	size_t len;
1067 
1068 	len = strlen(name);
1069 	for (i=0; env[i] != NULL; i++)
1070 		if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1071 			return(env[i] + len + 1);
1072 	return NULL;
1073 }
1074 
1075 /*
1076  * Read /etc/default/login.
1077  * We pick up the PATH (or SUPATH for root) and UMASK.
1078  */
1079 static void
1080 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1081 {
1082 	char **tmpenv = NULL, *var;
1083 	u_int i, tmpenvsize = 0;
1084 	u_long mask;
1085 
1086 	/*
1087 	 * We don't want to copy the whole file to the child's environment,
1088 	 * so we use a temporary environment and copy the variables we're
1089 	 * interested in.
1090 	 */
1091 	read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1092 
1093 	if (tmpenv == NULL)
1094 		return;
1095 
1096 	if (uid == 0)
1097 		var = child_get_env(tmpenv, "SUPATH");
1098 	else
1099 		var = child_get_env(tmpenv, "PATH");
1100 	if (var != NULL)
1101 		child_set_env(env, envsize, "PATH", var);
1102 
1103 	if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1104 		if (sscanf(var, "%5lo", &mask) == 1)
1105 			umask((mode_t)mask);
1106 
1107 	for (i = 0; tmpenv[i] != NULL; i++)
1108 		xfree(tmpenv[i]);
1109 	xfree(tmpenv);
1110 }
1111 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1112 
1113 void
1114 copy_environment(char **source, char ***env, u_int *envsize)
1115 {
1116 	char *var_name, *var_val;
1117 	int i;
1118 
1119 	if (source == NULL)
1120 		return;
1121 
1122 	for(i = 0; source[i] != NULL; i++) {
1123 		var_name = xstrdup(source[i]);
1124 		if ((var_val = strstr(var_name, "=")) == NULL) {
1125 			xfree(var_name);
1126 			continue;
1127 		}
1128 		*var_val++ = '\0';
1129 
1130 		debug3("Copy environment: %s=%s", var_name, var_val);
1131 		child_set_env(env, envsize, var_name, var_val);
1132 
1133 		xfree(var_name);
1134 	}
1135 }
1136 
1137 static char **
1138 do_setup_env(Session *s, const char *shell)
1139 {
1140 	char buf[256];
1141 	u_int i, envsize;
1142 	char **env, *laddr;
1143 	struct passwd *pw = s->pw;
1144 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1145 	char *path = NULL;
1146 #else
1147 	extern char **environ;
1148 	char **senv;
1149 #if 0
1150 	char **var;
1151 #endif
1152 #endif
1153 
1154 	/* Initialize the environment. */
1155 	envsize = 100;
1156 	env = xcalloc(envsize, sizeof(char *));
1157 	env[0] = NULL;
1158 
1159 #ifdef HAVE_CYGWIN
1160 	/*
1161 	 * The Windows environment contains some setting which are
1162 	 * important for a running system. They must not be dropped.
1163 	 */
1164 	{
1165 		char **p;
1166 
1167 		p = fetch_windows_environment();
1168 		copy_environment(p, &env, &envsize);
1169 		free_windows_environment(p);
1170 	}
1171 #endif
1172 
1173 	if (getenv("TZ"))
1174 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1175 
1176 #ifdef GSSAPI
1177 	/* Allow any GSSAPI methods that we've used to alter
1178 	 * the childs environment as they see fit
1179 	 */
1180 	ssh_gssapi_do_child(&env, &envsize);
1181 #endif
1182 
1183 	if (!options.use_login) {
1184 		/* Set basic environment. */
1185 		for (i = 0; i < s->num_env; i++)
1186 			child_set_env(&env, &envsize, s->env[i].name,
1187 			    s->env[i].val);
1188 
1189 		child_set_env(&env, &envsize, "USER", pw->pw_name);
1190 		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1191 #ifdef _AIX
1192 		child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1193 #endif
1194 		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1195 		snprintf(buf, sizeof buf, "%.200s/%.50s",
1196 			 _PATH_MAILDIR, pw->pw_name);
1197 		child_set_env(&env, &envsize, "MAIL", buf);
1198 #ifdef HAVE_LOGIN_CAP
1199 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1200 		child_set_env(&env, &envsize, "TERM", "su");
1201 		senv = environ;
1202 		environ = xmalloc(sizeof(char *));
1203 		*environ = NULL;
1204 		(void) setusercontext(lc, pw, pw->pw_uid,
1205 		    LOGIN_SETENV|LOGIN_SETPATH);
1206 		copy_environment(environ, &env, &envsize);
1207 #if 0
1208 		/*
1209 		 * This interferes with libc's management of the environment
1210 		 * in horrible ways that can cause sshd to crash.
1211 		 */
1212 		for (var = environ; *var != NULL; ++var)
1213 			xfree(*var);
1214 		xfree(environ);
1215 #endif
1216 		environ = senv;
1217 #else /* HAVE_LOGIN_CAP */
1218 # ifndef HAVE_CYGWIN
1219 		/*
1220 		 * There's no standard path on Windows. The path contains
1221 		 * important components pointing to the system directories,
1222 		 * needed for loading shared libraries. So the path better
1223 		 * remains intact here.
1224 		 */
1225 #  ifdef HAVE_ETC_DEFAULT_LOGIN
1226 		read_etc_default_login(&env, &envsize, pw->pw_uid);
1227 		path = child_get_env(env, "PATH");
1228 #  endif /* HAVE_ETC_DEFAULT_LOGIN */
1229 		if (path == NULL || *path == '\0') {
1230 			child_set_env(&env, &envsize, "PATH",
1231 			    s->pw->pw_uid == 0 ?
1232 				SUPERUSER_PATH : _PATH_STDPATH);
1233 		}
1234 # endif /* HAVE_CYGWIN */
1235 #endif /* HAVE_LOGIN_CAP */
1236 
1237 		/* Normal systems set SHELL by default. */
1238 		child_set_env(&env, &envsize, "SHELL", shell);
1239 	}
1240 
1241 	/* Set custom environment options from RSA authentication. */
1242 	if (!options.use_login) {
1243 		while (custom_environment) {
1244 			struct envstring *ce = custom_environment;
1245 			char *str = ce->s;
1246 
1247 			for (i = 0; str[i] != '=' && str[i]; i++)
1248 				;
1249 			if (str[i] == '=') {
1250 				str[i] = 0;
1251 				child_set_env(&env, &envsize, str, str + i + 1);
1252 			}
1253 			custom_environment = ce->next;
1254 			xfree(ce->s);
1255 			xfree(ce);
1256 		}
1257 	}
1258 
1259 	/* SSH_CLIENT deprecated */
1260 	snprintf(buf, sizeof buf, "%.50s %d %d",
1261 	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1262 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1263 
1264 	laddr = get_local_ipaddr(packet_get_connection_in());
1265 	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1266 	    get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1267 	xfree(laddr);
1268 	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1269 
1270 	if (s->ttyfd != -1)
1271 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1272 	if (s->term)
1273 		child_set_env(&env, &envsize, "TERM", s->term);
1274 	if (s->display)
1275 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1276 	if (original_command)
1277 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1278 		    original_command);
1279 
1280 #ifdef _UNICOS
1281 	if (cray_tmpdir[0] != '\0')
1282 		child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1283 #endif /* _UNICOS */
1284 
1285 	/*
1286 	 * Since we clear KRB5CCNAME at startup, if it's set now then it
1287 	 * must have been set by a native authentication method (eg AIX or
1288 	 * SIA), so copy it to the child.
1289 	 */
1290 	{
1291 		char *cp;
1292 
1293 		if ((cp = getenv("KRB5CCNAME")) != NULL)
1294 			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1295 	}
1296 
1297 #ifdef _AIX
1298 	{
1299 		char *cp;
1300 
1301 		if ((cp = getenv("AUTHSTATE")) != NULL)
1302 			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1303 		read_environment_file(&env, &envsize, "/etc/environment");
1304 	}
1305 #endif
1306 #ifdef KRB5
1307 	if (s->authctxt->krb5_ccname)
1308 		child_set_env(&env, &envsize, "KRB5CCNAME",
1309 		    s->authctxt->krb5_ccname);
1310 #endif
1311 #ifdef USE_PAM
1312 	/*
1313 	 * Pull in any environment variables that may have
1314 	 * been set by PAM.
1315 	 */
1316 	if (options.use_pam) {
1317 		char **p;
1318 
1319 		p = fetch_pam_child_environment();
1320 		copy_environment(p, &env, &envsize);
1321 		free_pam_environment(p);
1322 
1323 		p = fetch_pam_environment();
1324 		copy_environment(p, &env, &envsize);
1325 		free_pam_environment(p);
1326 	}
1327 #endif /* USE_PAM */
1328 
1329 	if (auth_sock_name != NULL)
1330 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1331 		    auth_sock_name);
1332 
1333 	/* read $HOME/.ssh/environment. */
1334 	if (options.permit_user_env && !options.use_login) {
1335 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1336 		    strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1337 		read_environment_file(&env, &envsize, buf);
1338 	}
1339 	if (debug_flag) {
1340 		/* dump the environment */
1341 		fprintf(stderr, "Environment:\n");
1342 		for (i = 0; env[i]; i++)
1343 			fprintf(stderr, "  %.200s\n", env[i]);
1344 	}
1345 	return env;
1346 }
1347 
1348 /*
1349  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1350  * first in this order).
1351  */
1352 static void
1353 do_rc_files(Session *s, const char *shell)
1354 {
1355 	FILE *f = NULL;
1356 	char cmd[1024];
1357 	int do_xauth;
1358 	struct stat st;
1359 
1360 	do_xauth =
1361 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1362 
1363 	/* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1364 	if (!s->is_subsystem && options.adm_forced_command == NULL &&
1365 	    !no_user_rc && stat(_PATH_SSH_USER_RC, &st) >= 0) {
1366 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1367 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1368 		if (debug_flag)
1369 			fprintf(stderr, "Running %s\n", cmd);
1370 		f = popen(cmd, "w");
1371 		if (f) {
1372 			if (do_xauth)
1373 				fprintf(f, "%s %s\n", s->auth_proto,
1374 				    s->auth_data);
1375 			pclose(f);
1376 		} else
1377 			fprintf(stderr, "Could not run %s\n",
1378 			    _PATH_SSH_USER_RC);
1379 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1380 		if (debug_flag)
1381 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1382 			    _PATH_SSH_SYSTEM_RC);
1383 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1384 		if (f) {
1385 			if (do_xauth)
1386 				fprintf(f, "%s %s\n", s->auth_proto,
1387 				    s->auth_data);
1388 			pclose(f);
1389 		} else
1390 			fprintf(stderr, "Could not run %s\n",
1391 			    _PATH_SSH_SYSTEM_RC);
1392 	} else if (do_xauth && options.xauth_location != NULL) {
1393 		/* Add authority data to .Xauthority if appropriate. */
1394 		if (debug_flag) {
1395 			fprintf(stderr,
1396 			    "Running %.500s remove %.100s\n",
1397 			    options.xauth_location, s->auth_display);
1398 			fprintf(stderr,
1399 			    "%.500s add %.100s %.100s %.100s\n",
1400 			    options.xauth_location, s->auth_display,
1401 			    s->auth_proto, s->auth_data);
1402 		}
1403 		snprintf(cmd, sizeof cmd, "%s -q -",
1404 		    options.xauth_location);
1405 		f = popen(cmd, "w");
1406 		if (f) {
1407 			fprintf(f, "remove %s\n",
1408 			    s->auth_display);
1409 			fprintf(f, "add %s %s %s\n",
1410 			    s->auth_display, s->auth_proto,
1411 			    s->auth_data);
1412 			pclose(f);
1413 		} else {
1414 			fprintf(stderr, "Could not run %s\n",
1415 			    cmd);
1416 		}
1417 	}
1418 }
1419 
1420 static void
1421 do_nologin(struct passwd *pw)
1422 {
1423 	FILE *f = NULL;
1424 	char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1425 	struct stat sb;
1426 
1427 #ifdef HAVE_LOGIN_CAP
1428 	if (login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1429 		return;
1430 	nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1431 #else
1432 	if (pw->pw_uid == 0)
1433 		return;
1434 	nl = def_nl;
1435 #endif
1436 	if (stat(nl, &sb) == -1) {
1437 		if (nl != def_nl)
1438 			xfree(nl);
1439 		return;
1440 	}
1441 
1442 	/* /etc/nologin exists.  Print its contents if we can and exit. */
1443 	logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1444 	if ((f = fopen(nl, "r")) != NULL) {
1445  		while (fgets(buf, sizeof(buf), f))
1446  			fputs(buf, stderr);
1447  		fclose(f);
1448  	}
1449 	exit(254);
1450 }
1451 
1452 /*
1453  * Chroot into a directory after checking it for safety: all path components
1454  * must be root-owned directories with strict permissions.
1455  */
1456 static void
1457 safely_chroot(const char *path, uid_t uid)
1458 {
1459 	const char *cp;
1460 	char component[MAXPATHLEN];
1461 	struct stat st;
1462 
1463 	if (*path != '/')
1464 		fatal("chroot path does not begin at root");
1465 	if (strlen(path) >= sizeof(component))
1466 		fatal("chroot path too long");
1467 
1468 	/*
1469 	 * Descend the path, checking that each component is a
1470 	 * root-owned directory with strict permissions.
1471 	 */
1472 	for (cp = path; cp != NULL;) {
1473 		if ((cp = strchr(cp, '/')) == NULL)
1474 			strlcpy(component, path, sizeof(component));
1475 		else {
1476 			cp++;
1477 			memcpy(component, path, cp - path);
1478 			component[cp - path] = '\0';
1479 		}
1480 
1481 		debug3("%s: checking '%s'", __func__, component);
1482 
1483 		if (stat(component, &st) != 0)
1484 			fatal("%s: stat(\"%s\"): %s", __func__,
1485 			    component, strerror(errno));
1486 		if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1487 			fatal("bad ownership or modes for chroot "
1488 			    "directory %s\"%s\"",
1489 			    cp == NULL ? "" : "component ", component);
1490 		if (!S_ISDIR(st.st_mode))
1491 			fatal("chroot path %s\"%s\" is not a directory",
1492 			    cp == NULL ? "" : "component ", component);
1493 
1494 	}
1495 
1496 	if (chdir(path) == -1)
1497 		fatal("Unable to chdir to chroot path \"%s\": "
1498 		    "%s", path, strerror(errno));
1499 	if (chroot(path) == -1)
1500 		fatal("chroot(\"%s\"): %s", path, strerror(errno));
1501 	if (chdir("/") == -1)
1502 		fatal("%s: chdir(/) after chroot: %s",
1503 		    __func__, strerror(errno));
1504 	verbose("Changed root directory to \"%s\"", path);
1505 }
1506 
1507 /* Set login name, uid, gid, and groups. */
1508 void
1509 do_setusercontext(struct passwd *pw)
1510 {
1511 	char *chroot_path, *tmp;
1512 
1513 	platform_setusercontext(pw);
1514 
1515 	if (platform_privileged_uidswap()) {
1516 #ifdef HAVE_LOGIN_CAP
1517 		if (setusercontext(lc, pw, pw->pw_uid,
1518 		    (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1519 			perror("unable to set user context");
1520 			exit(1);
1521 		}
1522 #else
1523 		if (setlogin(pw->pw_name) < 0)
1524 			error("setlogin failed: %s", strerror(errno));
1525 		if (setgid(pw->pw_gid) < 0) {
1526 			perror("setgid");
1527 			exit(1);
1528 		}
1529 		/* Initialize the group list. */
1530 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1531 			perror("initgroups");
1532 			exit(1);
1533 		}
1534 		endgrent();
1535 #endif
1536 
1537 		platform_setusercontext_post_groups(pw);
1538 
1539 		if (options.chroot_directory != NULL &&
1540 		    strcasecmp(options.chroot_directory, "none") != 0) {
1541                         tmp = tilde_expand_filename(options.chroot_directory,
1542 			    pw->pw_uid);
1543 			chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1544 			    "u", pw->pw_name, (char *)NULL);
1545 			safely_chroot(chroot_path, pw->pw_uid);
1546 			free(tmp);
1547 			free(chroot_path);
1548 		}
1549 
1550 #ifdef HAVE_LOGIN_CAP
1551 		if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1552 			perror("unable to set user context (setuser)");
1553 			exit(1);
1554 		}
1555 #else
1556 		/* Permanently switch to the desired uid. */
1557 		permanently_set_uid(pw);
1558 #endif
1559 	}
1560 
1561 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1562 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1563 }
1564 
1565 static void
1566 do_pwchange(Session *s)
1567 {
1568 	fflush(NULL);
1569 	fprintf(stderr, "WARNING: Your password has expired.\n");
1570 	if (s->ttyfd != -1) {
1571 		fprintf(stderr,
1572 		    "You must change your password now and login again!\n");
1573 #ifdef PASSWD_NEEDS_USERNAME
1574 		execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1575 		    (char *)NULL);
1576 #else
1577 		execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1578 #endif
1579 		perror("passwd");
1580 	} else {
1581 		fprintf(stderr,
1582 		    "Password change required but no TTY available.\n");
1583 	}
1584 	exit(1);
1585 }
1586 
1587 static void
1588 launch_login(struct passwd *pw, const char *hostname)
1589 {
1590 	/* Launch login(1). */
1591 
1592 	execl(LOGIN_PROGRAM, "login", "-h", hostname,
1593 #ifdef xxxLOGIN_NEEDS_TERM
1594 		    (s->term ? s->term : "unknown"),
1595 #endif /* LOGIN_NEEDS_TERM */
1596 #ifdef LOGIN_NO_ENDOPT
1597 	    "-p", "-f", pw->pw_name, (char *)NULL);
1598 #else
1599 	    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1600 #endif
1601 
1602 	/* Login couldn't be executed, die. */
1603 
1604 	perror("login");
1605 	exit(1);
1606 }
1607 
1608 static void
1609 child_close_fds(void)
1610 {
1611 	if (packet_get_connection_in() == packet_get_connection_out())
1612 		close(packet_get_connection_in());
1613 	else {
1614 		close(packet_get_connection_in());
1615 		close(packet_get_connection_out());
1616 	}
1617 	/*
1618 	 * Close all descriptors related to channels.  They will still remain
1619 	 * open in the parent.
1620 	 */
1621 	/* XXX better use close-on-exec? -markus */
1622 	channel_close_all();
1623 
1624 	/*
1625 	 * Close any extra file descriptors.  Note that there may still be
1626 	 * descriptors left by system functions.  They will be closed later.
1627 	 */
1628 	endpwent();
1629 
1630 	/*
1631 	 * Close any extra open file descriptors so that we don't have them
1632 	 * hanging around in clients.  Note that we want to do this after
1633 	 * initgroups, because at least on Solaris 2.3 it leaves file
1634 	 * descriptors open.
1635 	 */
1636 	closefrom(STDERR_FILENO + 1);
1637 }
1638 
1639 /*
1640  * Performs common processing for the child, such as setting up the
1641  * environment, closing extra file descriptors, setting the user and group
1642  * ids, and executing the command or shell.
1643  */
1644 #define ARGV_MAX 10
1645 void
1646 do_child(Session *s, const char *command)
1647 {
1648 	extern char **environ;
1649 	char **env;
1650 	char *argv[ARGV_MAX];
1651 	const char *shell, *shell0, *hostname = NULL;
1652 	struct passwd *pw = s->pw;
1653 	int r = 0;
1654 
1655 	/* remove hostkey from the child's memory */
1656 	destroy_sensitive_data();
1657 
1658 	/* Force a password change */
1659 	if (s->authctxt->force_pwchange) {
1660 		do_setusercontext(pw);
1661 		child_close_fds();
1662 		do_pwchange(s);
1663 		exit(1);
1664 	}
1665 
1666 	/* login(1) is only called if we execute the login shell */
1667 	if (options.use_login && command != NULL)
1668 		options.use_login = 0;
1669 
1670 #ifdef _UNICOS
1671 	cray_setup(pw->pw_uid, pw->pw_name, command);
1672 #endif /* _UNICOS */
1673 
1674 	/*
1675 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1676 	 * switch, so we let login(1) to this for us.
1677 	 */
1678 	if (!options.use_login) {
1679 #ifdef HAVE_OSF_SIA
1680 		session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1681 		if (!check_quietlogin(s, command))
1682 			do_motd();
1683 #else /* HAVE_OSF_SIA */
1684 		/* When PAM is enabled we rely on it to do the nologin check */
1685 		if (!options.use_pam)
1686 			do_nologin(pw);
1687 		do_setusercontext(pw);
1688 		/*
1689 		 * PAM session modules in do_setusercontext may have
1690 		 * generated messages, so if this in an interactive
1691 		 * login then display them too.
1692 		 */
1693 		if (!check_quietlogin(s, command))
1694 			display_loginmsg();
1695 #endif /* HAVE_OSF_SIA */
1696 	}
1697 
1698 #ifdef USE_PAM
1699 	if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1700 		debug3("PAM session not opened, exiting");
1701 		display_loginmsg();
1702 		exit(254);
1703 	}
1704 #endif
1705 
1706 	/*
1707 	 * Get the shell from the password data.  An empty shell field is
1708 	 * legal, and means /bin/sh.
1709 	 */
1710 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1711 
1712 	/*
1713 	 * Make sure $SHELL points to the shell from the password file,
1714 	 * even if shell is overridden from login.conf
1715 	 */
1716 	env = do_setup_env(s, shell);
1717 
1718 #ifdef HAVE_LOGIN_CAP
1719 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1720 #endif
1721 
1722 	/* we have to stash the hostname before we close our socket. */
1723 	if (options.use_login)
1724 		hostname = get_remote_name_or_ip(utmp_len,
1725 		    options.use_dns);
1726 	/*
1727 	 * Close the connection descriptors; note that this is the child, and
1728 	 * the server will still have the socket open, and it is important
1729 	 * that we do not shutdown it.  Note that the descriptors cannot be
1730 	 * closed before building the environment, as we call
1731 	 * get_remote_ipaddr there.
1732 	 */
1733 	child_close_fds();
1734 
1735 	/*
1736 	 * Must take new environment into use so that .ssh/rc,
1737 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1738 	 */
1739 	environ = env;
1740 
1741 #if defined(KRB5) && defined(USE_AFS)
1742 	/*
1743 	 * At this point, we check to see if AFS is active and if we have
1744 	 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1745 	 * if we can (and need to) extend the ticket into an AFS token. If
1746 	 * we don't do this, we run into potential problems if the user's
1747 	 * home directory is in AFS and it's not world-readable.
1748 	 */
1749 
1750 	if (options.kerberos_get_afs_token && k_hasafs() &&
1751 	    (s->authctxt->krb5_ctx != NULL)) {
1752 		char cell[64];
1753 
1754 		debug("Getting AFS token");
1755 
1756 		k_setpag();
1757 
1758 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1759 			krb5_afslog(s->authctxt->krb5_ctx,
1760 			    s->authctxt->krb5_fwd_ccache, cell, NULL);
1761 
1762 		krb5_afslog_home(s->authctxt->krb5_ctx,
1763 		    s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1764 	}
1765 #endif
1766 
1767 	/* Change current directory to the user's home directory. */
1768 	if (chdir(pw->pw_dir) < 0) {
1769 		/* Suppress missing homedir warning for chroot case */
1770 #ifdef HAVE_LOGIN_CAP
1771 		r = login_getcapbool(lc, "requirehome", 0);
1772 #endif
1773 		if (r || options.chroot_directory == NULL ||
1774 		    strcasecmp(options.chroot_directory, "none") == 0)
1775 			fprintf(stderr, "Could not chdir to home "
1776 			    "directory %s: %s\n", pw->pw_dir,
1777 			    strerror(errno));
1778 		if (r)
1779 			exit(1);
1780 	}
1781 
1782 	closefrom(STDERR_FILENO + 1);
1783 
1784 	if (!options.use_login)
1785 		do_rc_files(s, shell);
1786 
1787 	/* restore SIGPIPE for child */
1788 	signal(SIGPIPE, SIG_DFL);
1789 
1790 	if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1791 		printf("This service allows sftp connections only.\n");
1792 		fflush(NULL);
1793 		exit(1);
1794 	} else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1795 		extern int optind, optreset;
1796 		int i;
1797 		char *p, *args;
1798 
1799 		setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1800 		args = xstrdup(command ? command : "sftp-server");
1801 		for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1802 			if (i < ARGV_MAX - 1)
1803 				argv[i++] = p;
1804 		argv[i] = NULL;
1805 		optind = optreset = 1;
1806 		__progname = argv[0];
1807 #ifdef WITH_SELINUX
1808 		ssh_selinux_change_context("sftpd_t");
1809 #endif
1810 		exit(sftp_server_main(i, argv, s->pw));
1811 	}
1812 
1813 	fflush(NULL);
1814 
1815 	if (options.use_login) {
1816 		launch_login(pw, hostname);
1817 		/* NEVERREACHED */
1818 	}
1819 
1820 	/* Get the last component of the shell name. */
1821 	if ((shell0 = strrchr(shell, '/')) != NULL)
1822 		shell0++;
1823 	else
1824 		shell0 = shell;
1825 
1826 	/*
1827 	 * If we have no command, execute the shell.  In this case, the shell
1828 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1829 	 * this is a login shell.
1830 	 */
1831 	if (!command) {
1832 		char argv0[256];
1833 
1834 		/* Start the shell.  Set initial character to '-'. */
1835 		argv0[0] = '-';
1836 
1837 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1838 		    >= sizeof(argv0) - 1) {
1839 			errno = EINVAL;
1840 			perror(shell);
1841 			exit(1);
1842 		}
1843 
1844 		/* Execute the shell. */
1845 		argv[0] = argv0;
1846 		argv[1] = NULL;
1847 		execve(shell, argv, env);
1848 
1849 		/* Executing the shell failed. */
1850 		perror(shell);
1851 		exit(1);
1852 	}
1853 	/*
1854 	 * Execute the command using the user's shell.  This uses the -c
1855 	 * option to execute the command.
1856 	 */
1857 	argv[0] = (char *) shell0;
1858 	argv[1] = "-c";
1859 	argv[2] = (char *) command;
1860 	argv[3] = NULL;
1861 	execve(shell, argv, env);
1862 	perror(shell);
1863 	exit(1);
1864 }
1865 
1866 void
1867 session_unused(int id)
1868 {
1869 	debug3("%s: session id %d unused", __func__, id);
1870 	if (id >= options.max_sessions ||
1871 	    id >= sessions_nalloc) {
1872 		fatal("%s: insane session id %d (max %d nalloc %d)",
1873 		    __func__, id, options.max_sessions, sessions_nalloc);
1874 	}
1875 	bzero(&sessions[id], sizeof(*sessions));
1876 	sessions[id].self = id;
1877 	sessions[id].used = 0;
1878 	sessions[id].chanid = -1;
1879 	sessions[id].ptyfd = -1;
1880 	sessions[id].ttyfd = -1;
1881 	sessions[id].ptymaster = -1;
1882 	sessions[id].x11_chanids = NULL;
1883 	sessions[id].next_unused = sessions_first_unused;
1884 	sessions_first_unused = id;
1885 }
1886 
1887 Session *
1888 session_new(void)
1889 {
1890 	Session *s, *tmp;
1891 
1892 	if (sessions_first_unused == -1) {
1893 		if (sessions_nalloc >= options.max_sessions)
1894 			return NULL;
1895 		debug2("%s: allocate (allocated %d max %d)",
1896 		    __func__, sessions_nalloc, options.max_sessions);
1897 		tmp = xrealloc(sessions, sessions_nalloc + 1,
1898 		    sizeof(*sessions));
1899 		if (tmp == NULL) {
1900 			error("%s: cannot allocate %d sessions",
1901 			    __func__, sessions_nalloc + 1);
1902 			return NULL;
1903 		}
1904 		sessions = tmp;
1905 		session_unused(sessions_nalloc++);
1906 	}
1907 
1908 	if (sessions_first_unused >= sessions_nalloc ||
1909 	    sessions_first_unused < 0) {
1910 		fatal("%s: insane first_unused %d max %d nalloc %d",
1911 		    __func__, sessions_first_unused, options.max_sessions,
1912 		    sessions_nalloc);
1913 	}
1914 
1915 	s = &sessions[sessions_first_unused];
1916 	if (s->used) {
1917 		fatal("%s: session %d already used",
1918 		    __func__, sessions_first_unused);
1919 	}
1920 	sessions_first_unused = s->next_unused;
1921 	s->used = 1;
1922 	s->next_unused = -1;
1923 	debug("session_new: session %d", s->self);
1924 
1925 	return s;
1926 }
1927 
1928 static void
1929 session_dump(void)
1930 {
1931 	int i;
1932 	for (i = 0; i < sessions_nalloc; i++) {
1933 		Session *s = &sessions[i];
1934 
1935 		debug("dump: used %d next_unused %d session %d %p "
1936 		    "channel %d pid %ld",
1937 		    s->used,
1938 		    s->next_unused,
1939 		    s->self,
1940 		    s,
1941 		    s->chanid,
1942 		    (long)s->pid);
1943 	}
1944 }
1945 
1946 int
1947 session_open(Authctxt *authctxt, int chanid)
1948 {
1949 	Session *s = session_new();
1950 	debug("session_open: channel %d", chanid);
1951 	if (s == NULL) {
1952 		error("no more sessions");
1953 		return 0;
1954 	}
1955 	s->authctxt = authctxt;
1956 	s->pw = authctxt->pw;
1957 	if (s->pw == NULL || !authctxt->valid)
1958 		fatal("no user for session %d", s->self);
1959 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1960 	s->chanid = chanid;
1961 	return 1;
1962 }
1963 
1964 Session *
1965 session_by_tty(char *tty)
1966 {
1967 	int i;
1968 	for (i = 0; i < sessions_nalloc; i++) {
1969 		Session *s = &sessions[i];
1970 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1971 			debug("session_by_tty: session %d tty %s", i, tty);
1972 			return s;
1973 		}
1974 	}
1975 	debug("session_by_tty: unknown tty %.100s", tty);
1976 	session_dump();
1977 	return NULL;
1978 }
1979 
1980 static Session *
1981 session_by_channel(int id)
1982 {
1983 	int i;
1984 	for (i = 0; i < sessions_nalloc; i++) {
1985 		Session *s = &sessions[i];
1986 		if (s->used && s->chanid == id) {
1987 			debug("session_by_channel: session %d channel %d",
1988 			    i, id);
1989 			return s;
1990 		}
1991 	}
1992 	debug("session_by_channel: unknown channel %d", id);
1993 	session_dump();
1994 	return NULL;
1995 }
1996 
1997 static Session *
1998 session_by_x11_channel(int id)
1999 {
2000 	int i, j;
2001 
2002 	for (i = 0; i < sessions_nalloc; i++) {
2003 		Session *s = &sessions[i];
2004 
2005 		if (s->x11_chanids == NULL || !s->used)
2006 			continue;
2007 		for (j = 0; s->x11_chanids[j] != -1; j++) {
2008 			if (s->x11_chanids[j] == id) {
2009 				debug("session_by_x11_channel: session %d "
2010 				    "channel %d", s->self, id);
2011 				return s;
2012 			}
2013 		}
2014 	}
2015 	debug("session_by_x11_channel: unknown channel %d", id);
2016 	session_dump();
2017 	return NULL;
2018 }
2019 
2020 static Session *
2021 session_by_pid(pid_t pid)
2022 {
2023 	int i;
2024 	debug("session_by_pid: pid %ld", (long)pid);
2025 	for (i = 0; i < sessions_nalloc; i++) {
2026 		Session *s = &sessions[i];
2027 		if (s->used && s->pid == pid)
2028 			return s;
2029 	}
2030 	error("session_by_pid: unknown pid %ld", (long)pid);
2031 	session_dump();
2032 	return NULL;
2033 }
2034 
2035 static int
2036 session_window_change_req(Session *s)
2037 {
2038 	s->col = packet_get_int();
2039 	s->row = packet_get_int();
2040 	s->xpixel = packet_get_int();
2041 	s->ypixel = packet_get_int();
2042 	packet_check_eom();
2043 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2044 	return 1;
2045 }
2046 
2047 static int
2048 session_pty_req(Session *s)
2049 {
2050 	u_int len;
2051 	int n_bytes;
2052 
2053 	if (no_pty_flag) {
2054 		debug("Allocating a pty not permitted for this authentication.");
2055 		return 0;
2056 	}
2057 	if (s->ttyfd != -1) {
2058 		packet_disconnect("Protocol error: you already have a pty.");
2059 		return 0;
2060 	}
2061 
2062 	s->term = packet_get_string(&len);
2063 
2064 	if (compat20) {
2065 		s->col = packet_get_int();
2066 		s->row = packet_get_int();
2067 	} else {
2068 		s->row = packet_get_int();
2069 		s->col = packet_get_int();
2070 	}
2071 	s->xpixel = packet_get_int();
2072 	s->ypixel = packet_get_int();
2073 
2074 	if (strcmp(s->term, "") == 0) {
2075 		xfree(s->term);
2076 		s->term = NULL;
2077 	}
2078 
2079 	/* Allocate a pty and open it. */
2080 	debug("Allocating pty.");
2081 	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
2082 	    sizeof(s->tty)))) {
2083 		if (s->term)
2084 			xfree(s->term);
2085 		s->term = NULL;
2086 		s->ptyfd = -1;
2087 		s->ttyfd = -1;
2088 		error("session_pty_req: session %d alloc failed", s->self);
2089 		return 0;
2090 	}
2091 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2092 
2093 	/* for SSH1 the tty modes length is not given */
2094 	if (!compat20)
2095 		n_bytes = packet_remaining();
2096 	tty_parse_modes(s->ttyfd, &n_bytes);
2097 
2098 	if (!use_privsep)
2099 		pty_setowner(s->pw, s->tty);
2100 
2101 	/* Set window size from the packet. */
2102 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2103 
2104 	packet_check_eom();
2105 	session_proctitle(s);
2106 	return 1;
2107 }
2108 
2109 static int
2110 session_subsystem_req(Session *s)
2111 {
2112 	struct stat st;
2113 	u_int len;
2114 	int success = 0;
2115 	char *prog, *cmd, *subsys = packet_get_string(&len);
2116 	u_int i;
2117 
2118 	packet_check_eom();
2119 	logit("subsystem request for %.100s by user %s", subsys,
2120 	    s->pw->pw_name);
2121 
2122 	for (i = 0; i < options.num_subsystems; i++) {
2123 		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
2124 			prog = options.subsystem_command[i];
2125 			cmd = options.subsystem_args[i];
2126 			if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2127 				s->is_subsystem = SUBSYSTEM_INT_SFTP;
2128 				debug("subsystem: %s", prog);
2129 			} else {
2130 				if (stat(prog, &st) < 0)
2131 					debug("subsystem: cannot stat %s: %s",
2132 					    prog, strerror(errno));
2133 				s->is_subsystem = SUBSYSTEM_EXT;
2134 				debug("subsystem: exec() %s", cmd);
2135 			}
2136 			success = do_exec(s, cmd) == 0;
2137 			break;
2138 		}
2139 	}
2140 
2141 	if (!success)
2142 		logit("subsystem request for %.100s failed, subsystem not found",
2143 		    subsys);
2144 
2145 	xfree(subsys);
2146 	return success;
2147 }
2148 
2149 static int
2150 session_x11_req(Session *s)
2151 {
2152 	int success;
2153 
2154 	if (s->auth_proto != NULL || s->auth_data != NULL) {
2155 		error("session_x11_req: session %d: "
2156 		    "x11 forwarding already active", s->self);
2157 		return 0;
2158 	}
2159 	s->single_connection = packet_get_char();
2160 	s->auth_proto = packet_get_string(NULL);
2161 	s->auth_data = packet_get_string(NULL);
2162 	s->screen = packet_get_int();
2163 	packet_check_eom();
2164 
2165 	success = session_setup_x11fwd(s);
2166 	if (!success) {
2167 		xfree(s->auth_proto);
2168 		xfree(s->auth_data);
2169 		s->auth_proto = NULL;
2170 		s->auth_data = NULL;
2171 	}
2172 	return success;
2173 }
2174 
2175 static int
2176 session_shell_req(Session *s)
2177 {
2178 	packet_check_eom();
2179 	return do_exec(s, NULL) == 0;
2180 }
2181 
2182 static int
2183 session_exec_req(Session *s)
2184 {
2185 	u_int len, success;
2186 
2187 	char *command = packet_get_string(&len);
2188 	packet_check_eom();
2189 	success = do_exec(s, command) == 0;
2190 	xfree(command);
2191 	return success;
2192 }
2193 
2194 static int
2195 session_break_req(Session *s)
2196 {
2197 
2198 	packet_get_int();	/* ignored */
2199 	packet_check_eom();
2200 
2201 	if (s->ttyfd == -1 || tcsendbreak(s->ttyfd, 0) < 0)
2202 		return 0;
2203 	return 1;
2204 }
2205 
2206 static int
2207 session_env_req(Session *s)
2208 {
2209 	char *name, *val;
2210 	u_int name_len, val_len, i;
2211 
2212 	name = packet_get_string(&name_len);
2213 	val = packet_get_string(&val_len);
2214 	packet_check_eom();
2215 
2216 	/* Don't set too many environment variables */
2217 	if (s->num_env > 128) {
2218 		debug2("Ignoring env request %s: too many env vars", name);
2219 		goto fail;
2220 	}
2221 
2222 	for (i = 0; i < options.num_accept_env; i++) {
2223 		if (match_pattern(name, options.accept_env[i])) {
2224 			debug2("Setting env %d: %s=%s", s->num_env, name, val);
2225 			s->env = xrealloc(s->env, s->num_env + 1,
2226 			    sizeof(*s->env));
2227 			s->env[s->num_env].name = name;
2228 			s->env[s->num_env].val = val;
2229 			s->num_env++;
2230 			return (1);
2231 		}
2232 	}
2233 	debug2("Ignoring env request %s: disallowed name", name);
2234 
2235  fail:
2236 	xfree(name);
2237 	xfree(val);
2238 	return (0);
2239 }
2240 
2241 static int
2242 session_auth_agent_req(Session *s)
2243 {
2244 	static int called = 0;
2245 	packet_check_eom();
2246 	if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2247 		debug("session_auth_agent_req: no_agent_forwarding_flag");
2248 		return 0;
2249 	}
2250 	if (called) {
2251 		return 0;
2252 	} else {
2253 		called = 1;
2254 		return auth_input_request_forwarding(s->pw);
2255 	}
2256 }
2257 
2258 int
2259 session_input_channel_req(Channel *c, const char *rtype)
2260 {
2261 	int success = 0;
2262 	Session *s;
2263 
2264 	if ((s = session_by_channel(c->self)) == NULL) {
2265 		logit("session_input_channel_req: no session %d req %.100s",
2266 		    c->self, rtype);
2267 		return 0;
2268 	}
2269 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
2270 
2271 	/*
2272 	 * a session is in LARVAL state until a shell, a command
2273 	 * or a subsystem is executed
2274 	 */
2275 	if (c->type == SSH_CHANNEL_LARVAL) {
2276 		if (strcmp(rtype, "shell") == 0) {
2277 			success = session_shell_req(s);
2278 		} else if (strcmp(rtype, "exec") == 0) {
2279 			success = session_exec_req(s);
2280 		} else if (strcmp(rtype, "pty-req") == 0) {
2281 			success = session_pty_req(s);
2282 		} else if (strcmp(rtype, "x11-req") == 0) {
2283 			success = session_x11_req(s);
2284 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2285 			success = session_auth_agent_req(s);
2286 		} else if (strcmp(rtype, "subsystem") == 0) {
2287 			success = session_subsystem_req(s);
2288 		} else if (strcmp(rtype, "env") == 0) {
2289 			success = session_env_req(s);
2290 		}
2291 	}
2292 	if (strcmp(rtype, "window-change") == 0) {
2293 		success = session_window_change_req(s);
2294 	} else if (strcmp(rtype, "break") == 0) {
2295 		success = session_break_req(s);
2296 	}
2297 
2298 	return success;
2299 }
2300 
2301 void
2302 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2303     int is_tty)
2304 {
2305 	if (!compat20)
2306 		fatal("session_set_fds: called for proto != 2.0");
2307 	/*
2308 	 * now that have a child and a pipe to the child,
2309 	 * we can activate our channel and register the fd's
2310 	 */
2311 	if (s->chanid == -1)
2312 		fatal("no channel for session %d", s->self);
2313 	if (options.hpn_disabled)
2314 	channel_set_fds(s->chanid,
2315 	    fdout, fdin, fderr,
2316 	    ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2317 	    1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2318 	else
2319 		channel_set_fds(s->chanid,
2320 		    fdout, fdin, fderr,
2321 	            ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2322 		    1, is_tty, options.hpn_buffer_size);
2323 }
2324 
2325 /*
2326  * Function to perform pty cleanup. Also called if we get aborted abnormally
2327  * (e.g., due to a dropped connection).
2328  */
2329 void
2330 session_pty_cleanup2(Session *s)
2331 {
2332 	if (s == NULL) {
2333 		error("session_pty_cleanup: no session");
2334 		return;
2335 	}
2336 	if (s->ttyfd == -1)
2337 		return;
2338 
2339 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2340 
2341 	/* Record that the user has logged out. */
2342 	if (s->pid != 0)
2343 		record_logout(s->pid, s->tty, s->pw->pw_name);
2344 
2345 	/* Release the pseudo-tty. */
2346 	if (getuid() == 0)
2347 		pty_release(s->tty);
2348 
2349 	/*
2350 	 * Close the server side of the socket pairs.  We must do this after
2351 	 * the pty cleanup, so that another process doesn't get this pty
2352 	 * while we're still cleaning up.
2353 	 */
2354 	if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2355 		error("close(s->ptymaster/%d): %s",
2356 		    s->ptymaster, strerror(errno));
2357 
2358 	/* unlink pty from session */
2359 	s->ttyfd = -1;
2360 }
2361 
2362 void
2363 session_pty_cleanup(Session *s)
2364 {
2365 	PRIVSEP(session_pty_cleanup2(s));
2366 }
2367 
2368 static char *
2369 sig2name(int sig)
2370 {
2371 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2372 	SSH_SIG(ABRT);
2373 	SSH_SIG(ALRM);
2374 	SSH_SIG(FPE);
2375 	SSH_SIG(HUP);
2376 	SSH_SIG(ILL);
2377 	SSH_SIG(INT);
2378 	SSH_SIG(KILL);
2379 	SSH_SIG(PIPE);
2380 	SSH_SIG(QUIT);
2381 	SSH_SIG(SEGV);
2382 	SSH_SIG(TERM);
2383 	SSH_SIG(USR1);
2384 	SSH_SIG(USR2);
2385 #undef	SSH_SIG
2386 	return "SIG@openssh.com";
2387 }
2388 
2389 static void
2390 session_close_x11(int id)
2391 {
2392 	Channel *c;
2393 
2394 	if ((c = channel_by_id(id)) == NULL) {
2395 		debug("session_close_x11: x11 channel %d missing", id);
2396 	} else {
2397 		/* Detach X11 listener */
2398 		debug("session_close_x11: detach x11 channel %d", id);
2399 		channel_cancel_cleanup(id);
2400 		if (c->ostate != CHAN_OUTPUT_CLOSED)
2401 			chan_mark_dead(c);
2402 	}
2403 }
2404 
2405 static void
2406 session_close_single_x11(int id, void *arg)
2407 {
2408 	Session *s;
2409 	u_int i;
2410 
2411 	debug3("session_close_single_x11: channel %d", id);
2412 	channel_cancel_cleanup(id);
2413 	if ((s = session_by_x11_channel(id)) == NULL)
2414 		fatal("session_close_single_x11: no x11 channel %d", id);
2415 	for (i = 0; s->x11_chanids[i] != -1; i++) {
2416 		debug("session_close_single_x11: session %d: "
2417 		    "closing channel %d", s->self, s->x11_chanids[i]);
2418 		/*
2419 		 * The channel "id" is already closing, but make sure we
2420 		 * close all of its siblings.
2421 		 */
2422 		if (s->x11_chanids[i] != id)
2423 			session_close_x11(s->x11_chanids[i]);
2424 	}
2425 	xfree(s->x11_chanids);
2426 	s->x11_chanids = NULL;
2427 	if (s->display) {
2428 		xfree(s->display);
2429 		s->display = NULL;
2430 	}
2431 	if (s->auth_proto) {
2432 		xfree(s->auth_proto);
2433 		s->auth_proto = NULL;
2434 	}
2435 	if (s->auth_data) {
2436 		xfree(s->auth_data);
2437 		s->auth_data = NULL;
2438 	}
2439 	if (s->auth_display) {
2440 		xfree(s->auth_display);
2441 		s->auth_display = NULL;
2442 	}
2443 }
2444 
2445 static void
2446 session_exit_message(Session *s, int status)
2447 {
2448 	Channel *c;
2449 
2450 	if ((c = channel_lookup(s->chanid)) == NULL)
2451 		fatal("session_exit_message: session %d: no channel %d",
2452 		    s->self, s->chanid);
2453 	debug("session_exit_message: session %d channel %d pid %ld",
2454 	    s->self, s->chanid, (long)s->pid);
2455 
2456 	if (WIFEXITED(status)) {
2457 		channel_request_start(s->chanid, "exit-status", 0);
2458 		packet_put_int(WEXITSTATUS(status));
2459 		packet_send();
2460 	} else if (WIFSIGNALED(status)) {
2461 		channel_request_start(s->chanid, "exit-signal", 0);
2462 		packet_put_cstring(sig2name(WTERMSIG(status)));
2463 #ifdef WCOREDUMP
2464 		packet_put_char(WCOREDUMP(status)? 1 : 0);
2465 #else /* WCOREDUMP */
2466 		packet_put_char(0);
2467 #endif /* WCOREDUMP */
2468 		packet_put_cstring("");
2469 		packet_put_cstring("");
2470 		packet_send();
2471 	} else {
2472 		/* Some weird exit cause.  Just exit. */
2473 		packet_disconnect("wait returned status %04x.", status);
2474 	}
2475 
2476 	/* disconnect channel */
2477 	debug("session_exit_message: release channel %d", s->chanid);
2478 
2479 	/*
2480 	 * Adjust cleanup callback attachment to send close messages when
2481 	 * the channel gets EOF. The session will be then be closed
2482 	 * by session_close_by_channel when the childs close their fds.
2483 	 */
2484 	channel_register_cleanup(c->self, session_close_by_channel, 1);
2485 
2486 	/*
2487 	 * emulate a write failure with 'chan_write_failed', nobody will be
2488 	 * interested in data we write.
2489 	 * Note that we must not call 'chan_read_failed', since there could
2490 	 * be some more data waiting in the pipe.
2491 	 */
2492 	if (c->ostate != CHAN_OUTPUT_CLOSED)
2493 		chan_write_failed(c);
2494 }
2495 
2496 void
2497 session_close(Session *s)
2498 {
2499 	u_int i;
2500 
2501 	debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2502 	if (s->ttyfd != -1)
2503 		session_pty_cleanup(s);
2504 	if (s->term)
2505 		xfree(s->term);
2506 	if (s->display)
2507 		xfree(s->display);
2508 	if (s->x11_chanids)
2509 		xfree(s->x11_chanids);
2510 	if (s->auth_display)
2511 		xfree(s->auth_display);
2512 	if (s->auth_data)
2513 		xfree(s->auth_data);
2514 	if (s->auth_proto)
2515 		xfree(s->auth_proto);
2516 	if (s->env != NULL) {
2517 		for (i = 0; i < s->num_env; i++) {
2518 			xfree(s->env[i].name);
2519 			xfree(s->env[i].val);
2520 		}
2521 		xfree(s->env);
2522 	}
2523 	session_proctitle(s);
2524 	session_unused(s->self);
2525 }
2526 
2527 void
2528 session_close_by_pid(pid_t pid, int status)
2529 {
2530 	Session *s = session_by_pid(pid);
2531 	if (s == NULL) {
2532 		debug("session_close_by_pid: no session for pid %ld",
2533 		    (long)pid);
2534 		return;
2535 	}
2536 	if (s->chanid != -1)
2537 		session_exit_message(s, status);
2538 	if (s->ttyfd != -1)
2539 		session_pty_cleanup(s);
2540 	s->pid = 0;
2541 }
2542 
2543 /*
2544  * this is called when a channel dies before
2545  * the session 'child' itself dies
2546  */
2547 void
2548 session_close_by_channel(int id, void *arg)
2549 {
2550 	Session *s = session_by_channel(id);
2551 	u_int i;
2552 
2553 	if (s == NULL) {
2554 		debug("session_close_by_channel: no session for id %d", id);
2555 		return;
2556 	}
2557 	debug("session_close_by_channel: channel %d child %ld",
2558 	    id, (long)s->pid);
2559 	if (s->pid != 0) {
2560 		debug("session_close_by_channel: channel %d: has child", id);
2561 		/*
2562 		 * delay detach of session, but release pty, since
2563 		 * the fd's to the child are already closed
2564 		 */
2565 		if (s->ttyfd != -1)
2566 			session_pty_cleanup(s);
2567 		return;
2568 	}
2569 	/* detach by removing callback */
2570 	channel_cancel_cleanup(s->chanid);
2571 
2572 	/* Close any X11 listeners associated with this session */
2573 	if (s->x11_chanids != NULL) {
2574 		for (i = 0; s->x11_chanids[i] != -1; i++) {
2575 			session_close_x11(s->x11_chanids[i]);
2576 			s->x11_chanids[i] = -1;
2577 		}
2578 	}
2579 
2580 	s->chanid = -1;
2581 	session_close(s);
2582 }
2583 
2584 void
2585 session_destroy_all(void (*closefunc)(Session *))
2586 {
2587 	int i;
2588 	for (i = 0; i < sessions_nalloc; i++) {
2589 		Session *s = &sessions[i];
2590 		if (s->used) {
2591 			if (closefunc != NULL)
2592 				closefunc(s);
2593 			else
2594 				session_close(s);
2595 		}
2596 	}
2597 }
2598 
2599 static char *
2600 session_tty_list(void)
2601 {
2602 	static char buf[1024];
2603 	int i;
2604 	char *cp;
2605 
2606 	buf[0] = '\0';
2607 	for (i = 0; i < sessions_nalloc; i++) {
2608 		Session *s = &sessions[i];
2609 		if (s->used && s->ttyfd != -1) {
2610 
2611 			if (strncmp(s->tty, "/dev/", 5) != 0) {
2612 				cp = strrchr(s->tty, '/');
2613 				cp = (cp == NULL) ? s->tty : cp + 1;
2614 			} else
2615 				cp = s->tty + 5;
2616 
2617 			if (buf[0] != '\0')
2618 				strlcat(buf, ",", sizeof buf);
2619 			strlcat(buf, cp, sizeof buf);
2620 		}
2621 	}
2622 	if (buf[0] == '\0')
2623 		strlcpy(buf, "notty", sizeof buf);
2624 	return buf;
2625 }
2626 
2627 void
2628 session_proctitle(Session *s)
2629 {
2630 	if (s->pw == NULL)
2631 		error("no user for session %d", s->self);
2632 	else
2633 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2634 }
2635 
2636 int
2637 session_setup_x11fwd(Session *s)
2638 {
2639 	struct stat st;
2640 	char display[512], auth_display[512];
2641 	char hostname[MAXHOSTNAMELEN];
2642 	u_int i;
2643 
2644 	if (no_x11_forwarding_flag) {
2645 		packet_send_debug("X11 forwarding disabled in user configuration file.");
2646 		return 0;
2647 	}
2648 	if (!options.x11_forwarding) {
2649 		debug("X11 forwarding disabled in server configuration file.");
2650 		return 0;
2651 	}
2652 	if (!options.xauth_location ||
2653 	    (stat(options.xauth_location, &st) == -1)) {
2654 		packet_send_debug("No xauth program; cannot forward with spoofing.");
2655 		return 0;
2656 	}
2657 	if (options.use_login) {
2658 		packet_send_debug("X11 forwarding disabled; "
2659 		    "not compatible with UseLogin=yes.");
2660 		return 0;
2661 	}
2662 	if (s->display != NULL) {
2663 		debug("X11 display already set.");
2664 		return 0;
2665 	}
2666 	if (x11_create_display_inet(options.x11_display_offset,
2667 	    options.x11_use_localhost, s->single_connection,
2668 	    &s->display_number, &s->x11_chanids) == -1) {
2669 		debug("x11_create_display_inet failed.");
2670 		return 0;
2671 	}
2672 	for (i = 0; s->x11_chanids[i] != -1; i++) {
2673 		channel_register_cleanup(s->x11_chanids[i],
2674 		    session_close_single_x11, 0);
2675 	}
2676 
2677 	/* Set up a suitable value for the DISPLAY variable. */
2678 	if (gethostname(hostname, sizeof(hostname)) < 0)
2679 		fatal("gethostname: %.100s", strerror(errno));
2680 	/*
2681 	 * auth_display must be used as the displayname when the
2682 	 * authorization entry is added with xauth(1).  This will be
2683 	 * different than the DISPLAY string for localhost displays.
2684 	 */
2685 	if (options.x11_use_localhost) {
2686 		snprintf(display, sizeof display, "localhost:%u.%u",
2687 		    s->display_number, s->screen);
2688 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2689 		    s->display_number, s->screen);
2690 		s->display = xstrdup(display);
2691 		s->auth_display = xstrdup(auth_display);
2692 	} else {
2693 #ifdef IPADDR_IN_DISPLAY
2694 		struct hostent *he;
2695 		struct in_addr my_addr;
2696 
2697 		he = gethostbyname(hostname);
2698 		if (he == NULL) {
2699 			error("Can't get IP address for X11 DISPLAY.");
2700 			packet_send_debug("Can't get IP address for X11 DISPLAY.");
2701 			return 0;
2702 		}
2703 		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2704 		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2705 		    s->display_number, s->screen);
2706 #else
2707 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2708 		    s->display_number, s->screen);
2709 #endif
2710 		s->display = xstrdup(display);
2711 		s->auth_display = xstrdup(display);
2712 	}
2713 
2714 	return 1;
2715 }
2716 
2717 static void
2718 do_authenticated2(Authctxt *authctxt)
2719 {
2720 	server_loop2(authctxt);
2721 }
2722 
2723 void
2724 do_cleanup(Authctxt *authctxt)
2725 {
2726 	static int called = 0;
2727 
2728 	debug("do_cleanup");
2729 
2730 	/* no cleanup if we're in the child for login shell */
2731 	if (is_child)
2732 		return;
2733 
2734 	/* avoid double cleanup */
2735 	if (called)
2736 		return;
2737 	called = 1;
2738 
2739 	if (authctxt == NULL)
2740 		return;
2741 
2742 #ifdef USE_PAM
2743 	if (options.use_pam) {
2744 		sshpam_cleanup();
2745 		sshpam_thread_cleanup();
2746 	}
2747 #endif
2748 
2749 	if (!authctxt->authenticated)
2750 		return;
2751 
2752 #ifdef KRB5
2753 	if (options.kerberos_ticket_cleanup &&
2754 	    authctxt->krb5_ctx)
2755 		krb5_cleanup_proc(authctxt);
2756 #endif
2757 
2758 #ifdef GSSAPI
2759 	if (compat20 && options.gss_cleanup_creds)
2760 		ssh_gssapi_cleanup_creds();
2761 #endif
2762 
2763 	/* remove agent socket */
2764 	auth_sock_cleanup_proc(authctxt->pw);
2765 
2766 	/*
2767 	 * Cleanup ptys/utmp only if privsep is disabled,
2768 	 * or if running in monitor.
2769 	 */
2770 	if (!use_privsep || mm_is_monitor())
2771 		session_destroy_all(session_pty_cleanup2);
2772 }
2773