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