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