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