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