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