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