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