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