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