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