session.c revision 107858
1/*
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 *                    All rights reserved
4 *
5 * As far as I am concerned, the code I have written for this software
6 * can be used freely for any purpose.  Any derived versions of this
7 * software must be clearly marked as such, and if the derived work is
8 * incompatible with the protocol description in the RFC file, it must be
9 * called by a name other than "ssh" or "Secure Shell".
10 *
11 * SSH2 support by Markus Friedl.
12 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 *    notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 *    notice, this list of conditions and the following disclaimer in the
21 *    documentation and/or other materials provided with the distribution.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35#include "includes.h"
36RCSID("$OpenBSD: session.c,v 1.150 2002/09/16 19:55:33 stevesk Exp $");
37RCSID("$FreeBSD: head/crypto/openssh/session.c 107858 2002-12-14 13:40:21Z des $");
38
39#include "ssh.h"
40#include "ssh1.h"
41#include "ssh2.h"
42#include "xmalloc.h"
43#include "sshpty.h"
44#include "packet.h"
45#include "buffer.h"
46#include "mpaux.h"
47#include "uidswap.h"
48#include "compat.h"
49#include "channels.h"
50#include "bufaux.h"
51#include "auth.h"
52#include "auth-options.h"
53#include "pathnames.h"
54#include "log.h"
55#include "servconf.h"
56#include "sshlogin.h"
57#include "serverloop.h"
58#include "canohost.h"
59#include "session.h"
60#include "monitor_wrap.h"
61
62#ifdef HAVE_CYGWIN
63#include <windows.h>
64#include <sys/cygwin.h>
65#define is_winnt       (GetVersion() < 0x80000000)
66#endif
67
68/* func */
69
70Session *session_new(void);
71void	session_set_fds(Session *, int, int, int);
72void	session_pty_cleanup(void *);
73void	session_proctitle(Session *);
74int	session_setup_x11fwd(Session *);
75void	do_exec_pty(Session *, const char *);
76void	do_exec_no_pty(Session *, const char *);
77void	do_exec(Session *, const char *);
78void	do_login(Session *, const char *);
79#ifdef LOGIN_NEEDS_UTMPX
80static void	do_pre_login(Session *s);
81#endif
82void	do_child(Session *, const char *);
83void	do_motd(void);
84int	check_quietlogin(Session *, const char *);
85
86static void do_authenticated1(Authctxt *);
87static void do_authenticated2(Authctxt *);
88
89static int session_pty_req(Session *);
90
91/* import */
92extern ServerOptions options;
93extern char *__progname;
94extern int log_stderr;
95extern int debug_flag;
96extern u_int utmp_len;
97extern int startup_pipe;
98extern void destroy_sensitive_data(void);
99
100/* original command from peer. */
101const char *original_command = NULL;
102
103/* data */
104#define MAX_SESSIONS 10
105Session	sessions[MAX_SESSIONS];
106
107#ifdef WITH_AIXAUTHENTICATE
108char *aixloginmsg;
109#endif /* WITH_AIXAUTHENTICATE */
110
111#ifdef HAVE_LOGIN_CAP
112login_cap_t *lc;
113#endif
114
115/* Name and directory of socket for authentication agent forwarding. */
116static char *auth_sock_name = NULL;
117static char *auth_sock_dir = NULL;
118
119/* removes the agent forwarding socket */
120
121static void
122auth_sock_cleanup_proc(void *_pw)
123{
124	struct passwd *pw = _pw;
125
126	if (auth_sock_name != NULL) {
127		temporarily_use_uid(pw);
128		unlink(auth_sock_name);
129		rmdir(auth_sock_dir);
130		auth_sock_name = NULL;
131		restore_uid();
132	}
133}
134
135static int
136auth_input_request_forwarding(struct passwd * pw)
137{
138	Channel *nc;
139	int sock;
140	struct sockaddr_un sunaddr;
141
142	if (auth_sock_name != NULL) {
143		error("authentication forwarding requested twice.");
144		return 0;
145	}
146
147	/* Temporarily drop privileged uid for mkdir/bind. */
148	temporarily_use_uid(pw);
149
150	/* Allocate a buffer for the socket name, and format the name. */
151	auth_sock_name = xmalloc(MAXPATHLEN);
152	auth_sock_dir = xmalloc(MAXPATHLEN);
153	strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
154
155	/* Create private directory for socket */
156	if (mkdtemp(auth_sock_dir) == NULL) {
157		packet_send_debug("Agent forwarding disabled: "
158		    "mkdtemp() failed: %.100s", strerror(errno));
159		restore_uid();
160		xfree(auth_sock_name);
161		xfree(auth_sock_dir);
162		auth_sock_name = NULL;
163		auth_sock_dir = NULL;
164		return 0;
165	}
166	snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
167		 auth_sock_dir, (long) getpid());
168
169	/* delete agent socket on fatal() */
170	fatal_add_cleanup(auth_sock_cleanup_proc, pw);
171
172	/* Create the socket. */
173	sock = socket(AF_UNIX, SOCK_STREAM, 0);
174	if (sock < 0)
175		packet_disconnect("socket: %.100s", strerror(errno));
176
177	/* Bind it to the name. */
178	memset(&sunaddr, 0, sizeof(sunaddr));
179	sunaddr.sun_family = AF_UNIX;
180	strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
181
182	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
183		packet_disconnect("bind: %.100s", strerror(errno));
184
185	/* Restore the privileged uid. */
186	restore_uid();
187
188	/* Start listening on the socket. */
189	if (listen(sock, 5) < 0)
190		packet_disconnect("listen: %.100s", strerror(errno));
191
192	/* Allocate a channel for the authentication agent socket. */
193	nc = channel_new("auth socket",
194	    SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
195	    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
196	    0, xstrdup("auth socket"), 1);
197	strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
198	return 1;
199}
200
201
202void
203do_authenticated(Authctxt *authctxt)
204{
205	/*
206	 * Cancel the alarm we set to limit the time taken for
207	 * authentication.
208	 */
209	alarm(0);
210	if (startup_pipe != -1) {
211		close(startup_pipe);
212		startup_pipe = -1;
213	}
214
215	/* setup the channel layer */
216	if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
217		channel_permit_all_opens();
218
219	if (compat20)
220		do_authenticated2(authctxt);
221	else
222		do_authenticated1(authctxt);
223
224	/* remove agent socket */
225	if (auth_sock_name != NULL)
226		auth_sock_cleanup_proc(authctxt->pw);
227#ifdef KRB4
228	if (options.kerberos_ticket_cleanup)
229		krb4_cleanup_proc(authctxt);
230#endif
231#ifdef KRB5
232	if (options.kerberos_ticket_cleanup)
233		krb5_cleanup_proc(authctxt);
234#endif
235}
236
237/*
238 * Prepares for an interactive session.  This is called after the user has
239 * been successfully authenticated.  During this message exchange, pseudo
240 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
241 * are requested, etc.
242 */
243static void
244do_authenticated1(Authctxt *authctxt)
245{
246	Session *s;
247	char *command;
248	int success, type, screen_flag;
249	int enable_compression_after_reply = 0;
250	u_int proto_len, data_len, dlen, compression_level = 0;
251
252	s = session_new();
253	s->authctxt = authctxt;
254	s->pw = authctxt->pw;
255
256	/*
257	 * We stay in this loop until the client requests to execute a shell
258	 * or a command.
259	 */
260	for (;;) {
261		success = 0;
262
263		/* Get a packet from the client. */
264		type = packet_read();
265
266		/* Process the packet. */
267		switch (type) {
268		case SSH_CMSG_REQUEST_COMPRESSION:
269			compression_level = packet_get_int();
270			packet_check_eom();
271			if (compression_level < 1 || compression_level > 9) {
272				packet_send_debug("Received illegal compression level %d.",
273				    compression_level);
274				break;
275			}
276			if (!options.compression) {
277				debug2("compression disabled");
278				break;
279			}
280			/* Enable compression after we have responded with SUCCESS. */
281			enable_compression_after_reply = 1;
282			success = 1;
283			break;
284
285		case SSH_CMSG_REQUEST_PTY:
286			success = session_pty_req(s);
287			break;
288
289		case SSH_CMSG_X11_REQUEST_FORWARDING:
290			s->auth_proto = packet_get_string(&proto_len);
291			s->auth_data = packet_get_string(&data_len);
292
293			screen_flag = packet_get_protocol_flags() &
294			    SSH_PROTOFLAG_SCREEN_NUMBER;
295			debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
296
297			if (packet_remaining() == 4) {
298				if (!screen_flag)
299					debug2("Buggy client: "
300					    "X11 screen flag missing");
301				s->screen = packet_get_int();
302			} else {
303				s->screen = 0;
304			}
305			packet_check_eom();
306			success = session_setup_x11fwd(s);
307			if (!success) {
308				xfree(s->auth_proto);
309				xfree(s->auth_data);
310				s->auth_proto = NULL;
311				s->auth_data = NULL;
312			}
313			break;
314
315		case SSH_CMSG_AGENT_REQUEST_FORWARDING:
316			if (no_agent_forwarding_flag || compat13) {
317				debug("Authentication agent forwarding not permitted for this authentication.");
318				break;
319			}
320			debug("Received authentication agent forwarding request.");
321			success = auth_input_request_forwarding(s->pw);
322			break;
323
324		case SSH_CMSG_PORT_FORWARD_REQUEST:
325			if (no_port_forwarding_flag) {
326				debug("Port forwarding not permitted for this authentication.");
327				break;
328			}
329			if (!options.allow_tcp_forwarding) {
330				debug("Port forwarding not permitted.");
331				break;
332			}
333			debug("Received TCP/IP port forwarding request.");
334			channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
335			success = 1;
336			break;
337
338		case SSH_CMSG_MAX_PACKET_SIZE:
339			if (packet_set_maxsize(packet_get_int()) > 0)
340				success = 1;
341			break;
342
343#if defined(AFS) || defined(KRB5)
344		case SSH_CMSG_HAVE_KERBEROS_TGT:
345			if (!options.kerberos_tgt_passing) {
346				verbose("Kerberos TGT passing disabled.");
347			} else {
348				char *kdata = packet_get_string(&dlen);
349				packet_check_eom();
350
351				/* XXX - 0x41, see creds_to_radix version */
352				if (kdata[0] != 0x41) {
353#ifdef KRB5
354					krb5_data tgt;
355					tgt.data = kdata;
356					tgt.length = dlen;
357
358					if (auth_krb5_tgt(s->authctxt, &tgt))
359						success = 1;
360					else
361						verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
362#endif /* KRB5 */
363				} else {
364#ifdef AFS
365					if (auth_krb4_tgt(s->authctxt, kdata))
366						success = 1;
367					else
368						verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
369#endif /* AFS */
370				}
371				xfree(kdata);
372			}
373			break;
374#endif /* AFS || KRB5 */
375
376#ifdef AFS
377		case SSH_CMSG_HAVE_AFS_TOKEN:
378			if (!options.afs_token_passing || !k_hasafs()) {
379				verbose("AFS token passing disabled.");
380			} else {
381				/* Accept AFS token. */
382				char *token = packet_get_string(&dlen);
383				packet_check_eom();
384
385				if (auth_afs_token(s->authctxt, token))
386					success = 1;
387				else
388					verbose("AFS token refused for %.100s",
389					    s->authctxt->user);
390				xfree(token);
391			}
392			break;
393#endif /* AFS */
394
395		case SSH_CMSG_EXEC_SHELL:
396		case SSH_CMSG_EXEC_CMD:
397			if (type == SSH_CMSG_EXEC_CMD) {
398				command = packet_get_string(&dlen);
399				debug("Exec command '%.500s'", command);
400				do_exec(s, command);
401				xfree(command);
402			} else {
403				do_exec(s, NULL);
404			}
405			packet_check_eom();
406			session_close(s);
407			return;
408
409		default:
410			/*
411			 * Any unknown messages in this phase are ignored,
412			 * and a failure message is returned.
413			 */
414			log("Unknown packet type received after authentication: %d", type);
415		}
416		packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
417		packet_send();
418		packet_write_wait();
419
420		/* Enable compression now that we have replied if appropriate. */
421		if (enable_compression_after_reply) {
422			enable_compression_after_reply = 0;
423			packet_start_compression(compression_level);
424		}
425	}
426}
427
428/*
429 * This is called to fork and execute a command when we have no tty.  This
430 * will call do_child from the child, and server_loop from the parent after
431 * setting up file descriptors and such.
432 */
433void
434do_exec_no_pty(Session *s, const char *command)
435{
436	pid_t pid;
437
438#ifdef USE_PIPES
439	int pin[2], pout[2], perr[2];
440	/* Allocate pipes for communicating with the program. */
441	if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
442		packet_disconnect("Could not create pipes: %.100s",
443				  strerror(errno));
444#else /* USE_PIPES */
445	int inout[2], err[2];
446	/* Uses socket pairs to communicate with the program. */
447	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
448	    socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
449		packet_disconnect("Could not create socket pairs: %.100s",
450				  strerror(errno));
451#endif /* USE_PIPES */
452	if (s == NULL)
453		fatal("do_exec_no_pty: no session");
454
455	session_proctitle(s);
456
457#if defined(USE_PAM)
458	do_pam_session(s->pw->pw_name, NULL);
459	do_pam_setcred(1);
460	if (is_pam_password_change_required())
461		packet_disconnect("Password change required but no "
462		    "TTY available");
463#endif /* USE_PAM */
464
465	/* Fork the child. */
466	if ((pid = fork()) == 0) {
467		fatal_remove_all_cleanups();
468
469		/* Child.  Reinitialize the log since the pid has changed. */
470		log_init(__progname, options.log_level, options.log_facility, log_stderr);
471
472		/*
473		 * Create a new session and process group since the 4.4BSD
474		 * setlogin() affects the entire process group.
475		 */
476		if (setsid() < 0)
477			error("setsid failed: %.100s", strerror(errno));
478
479#ifdef USE_PIPES
480		/*
481		 * Redirect stdin.  We close the parent side of the socket
482		 * pair, and make the child side the standard input.
483		 */
484		close(pin[1]);
485		if (dup2(pin[0], 0) < 0)
486			perror("dup2 stdin");
487		close(pin[0]);
488
489		/* Redirect stdout. */
490		close(pout[0]);
491		if (dup2(pout[1], 1) < 0)
492			perror("dup2 stdout");
493		close(pout[1]);
494
495		/* Redirect stderr. */
496		close(perr[0]);
497		if (dup2(perr[1], 2) < 0)
498			perror("dup2 stderr");
499		close(perr[1]);
500#else /* USE_PIPES */
501		/*
502		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
503		 * use the same socket, as some programs (particularly rdist)
504		 * seem to depend on it.
505		 */
506		close(inout[1]);
507		close(err[1]);
508		if (dup2(inout[0], 0) < 0)	/* stdin */
509			perror("dup2 stdin");
510		if (dup2(inout[0], 1) < 0)	/* stdout.  Note: same socket as stdin. */
511			perror("dup2 stdout");
512		if (dup2(err[0], 2) < 0)	/* stderr */
513			perror("dup2 stderr");
514#endif /* USE_PIPES */
515
516#ifdef _UNICOS
517		cray_init_job(s->pw); /* set up cray jid and tmpdir */
518#endif
519
520		/* Do processing for the child (exec command etc). */
521		do_child(s, command);
522		/* NOTREACHED */
523	}
524#ifdef _UNICOS
525	signal(WJSIGNAL, cray_job_termination_handler);
526#endif /* _UNICOS */
527#ifdef HAVE_CYGWIN
528	if (is_winnt)
529		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
530#endif
531	if (pid < 0)
532		packet_disconnect("fork failed: %.100s", strerror(errno));
533	s->pid = pid;
534	/* Set interactive/non-interactive mode. */
535	packet_set_interactive(s->display != NULL);
536#ifdef USE_PIPES
537	/* We are the parent.  Close the child sides of the pipes. */
538	close(pin[0]);
539	close(pout[1]);
540	close(perr[1]);
541
542	if (compat20) {
543		session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
544	} else {
545		/* Enter the interactive session. */
546		server_loop(pid, pin[1], pout[0], perr[0]);
547		/* server_loop has closed pin[1], pout[0], and perr[0]. */
548	}
549#else /* USE_PIPES */
550	/* We are the parent.  Close the child sides of the socket pairs. */
551	close(inout[0]);
552	close(err[0]);
553
554	/*
555	 * Enter the interactive session.  Note: server_loop must be able to
556	 * handle the case that fdin and fdout are the same.
557	 */
558	if (compat20) {
559		session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
560	} else {
561		server_loop(pid, inout[1], inout[1], err[1]);
562		/* server_loop has closed inout[1] and err[1]. */
563	}
564#endif /* USE_PIPES */
565}
566
567/*
568 * This is called to fork and execute a command when we have a tty.  This
569 * will call do_child from the child, and server_loop from the parent after
570 * setting up file descriptors, controlling tty, updating wtmp, utmp,
571 * lastlog, and other such operations.
572 */
573void
574do_exec_pty(Session *s, const char *command)
575{
576	int fdout, ptyfd, ttyfd, ptymaster;
577	pid_t pid;
578
579	if (s == NULL)
580		fatal("do_exec_pty: no session");
581	ptyfd = s->ptyfd;
582	ttyfd = s->ttyfd;
583
584#if defined(USE_PAM)
585	do_pam_session(s->pw->pw_name, s->tty);
586	do_pam_setcred(1);
587#endif
588
589	/* Fork the child. */
590	if ((pid = fork()) == 0) {
591		fatal_remove_all_cleanups();
592
593		/* Child.  Reinitialize the log because the pid has changed. */
594		log_init(__progname, options.log_level, options.log_facility, log_stderr);
595		/* Close the master side of the pseudo tty. */
596		close(ptyfd);
597
598		/* Make the pseudo tty our controlling tty. */
599		pty_make_controlling_tty(&ttyfd, s->tty);
600
601		/* Redirect stdin/stdout/stderr from the pseudo tty. */
602		if (dup2(ttyfd, 0) < 0)
603			error("dup2 stdin: %s", strerror(errno));
604		if (dup2(ttyfd, 1) < 0)
605			error("dup2 stdout: %s", strerror(errno));
606		if (dup2(ttyfd, 2) < 0)
607			error("dup2 stderr: %s", strerror(errno));
608
609		/* Close the extra descriptor for the pseudo tty. */
610		close(ttyfd);
611
612		/* record login, etc. similar to login(1) */
613#ifndef HAVE_OSF_SIA
614		if (!(options.use_login && command == NULL)) {
615#ifdef _UNICOS
616			cray_init_job(s->pw); /* set up cray jid and tmpdir */
617#endif /* _UNICOS */
618			do_login(s, command);
619		}
620# ifdef LOGIN_NEEDS_UTMPX
621		else
622			do_pre_login(s);
623# endif
624#endif
625
626		/* Do common processing for the child, such as execing the command. */
627		do_child(s, command);
628		/* NOTREACHED */
629	}
630#ifdef _UNICOS
631	signal(WJSIGNAL, cray_job_termination_handler);
632#endif /* _UNICOS */
633#ifdef HAVE_CYGWIN
634	if (is_winnt)
635		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
636#endif
637	if (pid < 0)
638		packet_disconnect("fork failed: %.100s", strerror(errno));
639	s->pid = pid;
640
641	/* Parent.  Close the slave side of the pseudo tty. */
642	close(ttyfd);
643
644	/*
645	 * Create another descriptor of the pty master side for use as the
646	 * standard input.  We could use the original descriptor, but this
647	 * simplifies code in server_loop.  The descriptor is bidirectional.
648	 */
649	fdout = dup(ptyfd);
650	if (fdout < 0)
651		packet_disconnect("dup #1 failed: %.100s", strerror(errno));
652
653	/* we keep a reference to the pty master */
654	ptymaster = dup(ptyfd);
655	if (ptymaster < 0)
656		packet_disconnect("dup #2 failed: %.100s", strerror(errno));
657	s->ptymaster = ptymaster;
658
659	/* Enter interactive session. */
660	packet_set_interactive(1);
661	if (compat20) {
662		session_set_fds(s, ptyfd, fdout, -1);
663	} else {
664		server_loop(pid, ptyfd, fdout, -1);
665		/* server_loop _has_ closed ptyfd and fdout. */
666	}
667}
668
669#ifdef LOGIN_NEEDS_UTMPX
670static void
671do_pre_login(Session *s)
672{
673	socklen_t fromlen;
674	struct sockaddr_storage from;
675	pid_t pid = getpid();
676
677	/*
678	 * Get IP address of client. If the connection is not a socket, let
679	 * the address be 0.0.0.0.
680	 */
681	memset(&from, 0, sizeof(from));
682	fromlen = sizeof(from);
683	if (packet_connection_is_on_socket()) {
684		if (getpeername(packet_get_connection_in(),
685		    (struct sockaddr *) & from, &fromlen) < 0) {
686			debug("getpeername: %.100s", strerror(errno));
687			fatal_cleanup();
688		}
689	}
690
691	record_utmp_only(pid, s->tty, s->pw->pw_name,
692	    get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
693	    (struct sockaddr *)&from, fromlen);
694}
695#endif
696
697/*
698 * This is called to fork and execute a command.  If another command is
699 * to be forced, execute that instead.
700 */
701void
702do_exec(Session *s, const char *command)
703{
704	if (forced_command) {
705		original_command = command;
706		command = forced_command;
707		debug("Forced command '%.900s'", command);
708	}
709
710	if (s->ttyfd != -1)
711		do_exec_pty(s, command);
712	else
713		do_exec_no_pty(s, command);
714
715	original_command = NULL;
716}
717
718
719/* administrative, login(1)-like work */
720void
721do_login(Session *s, const char *command)
722{
723	char *time_string;
724	socklen_t fromlen;
725	struct sockaddr_storage from;
726	struct passwd * pw = s->pw;
727	pid_t pid = getpid();
728
729	/*
730	 * Get IP address of client. If the connection is not a socket, let
731	 * the address be 0.0.0.0.
732	 */
733	memset(&from, 0, sizeof(from));
734	fromlen = sizeof(from);
735	if (packet_connection_is_on_socket()) {
736		if (getpeername(packet_get_connection_in(),
737		    (struct sockaddr *) & from, &fromlen) < 0) {
738			debug("getpeername: %.100s", strerror(errno));
739			fatal_cleanup();
740		}
741	}
742
743	/* Record that there was a login on that tty from the remote host. */
744	if (!use_privsep)
745		record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
746		    get_remote_name_or_ip(utmp_len,
747		    options.verify_reverse_mapping),
748		    (struct sockaddr *)&from, fromlen);
749
750#ifdef USE_PAM
751	/*
752	 * If password change is needed, do it now.
753	 * This needs to occur before the ~/.hushlogin check.
754	 */
755	if (is_pam_password_change_required()) {
756		print_pam_messages();
757		do_pam_chauthtok();
758	}
759#endif
760
761	if (check_quietlogin(s, command))
762		return;
763
764#ifdef USE_PAM
765	if (!is_pam_password_change_required())
766		print_pam_messages();
767#endif /* USE_PAM */
768#ifdef WITH_AIXAUTHENTICATE
769	if (aixloginmsg && *aixloginmsg)
770		printf("%s\n", aixloginmsg);
771#endif /* WITH_AIXAUTHENTICATE */
772
773#ifndef NO_SSH_LASTLOG
774	if (options.print_lastlog && s->last_login_time != 0) {
775		time_string = ctime(&s->last_login_time);
776		if (strchr(time_string, '\n'))
777			*strchr(time_string, '\n') = 0;
778		if (strcmp(s->hostname, "") == 0)
779			printf("Last login: %s\r\n", time_string);
780		else
781			printf("Last login: %s from %s\r\n", time_string,
782			    s->hostname);
783	}
784#endif /* NO_SSH_LASTLOG */
785
786	do_motd();
787}
788
789/*
790 * Display the message of the day.
791 */
792void
793do_motd(void)
794{
795	FILE *f;
796	char buf[256];
797#ifdef HAVE_LOGIN_CAP
798	const char *fname;
799#endif
800
801#ifdef HAVE_LOGIN_CAP
802	fname = login_getcapstr(lc, "copyright", NULL, NULL);
803	if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
804		while (fgets(buf, sizeof(buf), f) != NULL)
805			fputs(buf, stdout);
806			fclose(f);
807	} else
808#endif /* HAVE_LOGIN_CAP */
809		(void)printf("%s\n\t%s %s\n",
810	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
811	"The Regents of the University of California. ",
812	"All rights reserved.");
813
814	(void)printf("\n");
815
816	if (options.print_motd) {
817#ifdef HAVE_LOGIN_CAP
818		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
819		    "/etc/motd"), "r");
820#else
821		f = fopen("/etc/motd", "r");
822#endif
823		if (f) {
824			while (fgets(buf, sizeof(buf), f))
825				fputs(buf, stdout);
826			fclose(f);
827		}
828	}
829}
830
831
832/*
833 * Check for quiet login, either .hushlogin or command given.
834 */
835int
836check_quietlogin(Session *s, const char *command)
837{
838	char buf[256];
839	struct passwd *pw = s->pw;
840	struct stat st;
841
842	/* Return 1 if .hushlogin exists or a command given. */
843	if (command != NULL)
844		return 1;
845	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
846#ifdef HAVE_LOGIN_CAP
847	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
848		return 1;
849#else
850	if (stat(buf, &st) >= 0)
851		return 1;
852#endif
853	return 0;
854}
855
856/*
857 * Sets the value of the given variable in the environment.  If the variable
858 * already exists, its value is overriden.
859 */
860static void
861child_set_env(char ***envp, u_int *envsizep, const char *name,
862	const char *value)
863{
864	u_int i, namelen;
865	char **env;
866
867	/*
868	 * Find the slot where the value should be stored.  If the variable
869	 * already exists, we reuse the slot; otherwise we append a new slot
870	 * at the end of the array, expanding if necessary.
871	 */
872	env = *envp;
873	namelen = strlen(name);
874	for (i = 0; env[i]; i++)
875		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
876			break;
877	if (env[i]) {
878		/* Reuse the slot. */
879		xfree(env[i]);
880	} else {
881		/* New variable.  Expand if necessary. */
882		if (i >= (*envsizep) - 1) {
883			if (*envsizep >= 1000)
884				fatal("child_set_env: too many env vars,"
885				    " skipping: %.100s", name);
886			(*envsizep) += 50;
887			env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
888		}
889		/* Need to set the NULL pointer at end of array beyond the new slot. */
890		env[i + 1] = NULL;
891	}
892
893	/* Allocate space and format the variable in the appropriate slot. */
894	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
895	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
896}
897
898/*
899 * Reads environment variables from the given file and adds/overrides them
900 * into the environment.  If the file does not exist, this does nothing.
901 * Otherwise, it must consist of empty lines, comments (line starts with '#')
902 * and assignments of the form name=value.  No other forms are allowed.
903 */
904static void
905read_environment_file(char ***env, u_int *envsize,
906	const char *filename)
907{
908	FILE *f;
909	char buf[4096];
910	char *cp, *value;
911	u_int lineno = 0;
912
913	f = fopen(filename, "r");
914	if (!f)
915		return;
916
917	while (fgets(buf, sizeof(buf), f)) {
918		if (++lineno > 1000)
919			fatal("Too many lines in environment file %s", filename);
920		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
921			;
922		if (!*cp || *cp == '#' || *cp == '\n')
923			continue;
924		if (strchr(cp, '\n'))
925			*strchr(cp, '\n') = '\0';
926		value = strchr(cp, '=');
927		if (value == NULL) {
928			fprintf(stderr, "Bad line %u in %.100s\n", lineno,
929			    filename);
930			continue;
931		}
932		/*
933		 * Replace the equals sign by nul, and advance value to
934		 * the value string.
935		 */
936		*value = '\0';
937		value++;
938		child_set_env(env, envsize, cp, value);
939	}
940	fclose(f);
941}
942
943void copy_environment(char **source, char ***env, u_int *envsize)
944{
945	char *var_name, *var_val;
946	int i;
947
948	if (source == NULL)
949		return;
950
951	for(i = 0; source[i] != NULL; i++) {
952		var_name = xstrdup(source[i]);
953		if ((var_val = strstr(var_name, "=")) == NULL) {
954			xfree(var_name);
955			continue;
956		}
957		*var_val++ = '\0';
958
959		debug3("Copy environment: %s=%s", var_name, var_val);
960		child_set_env(env, envsize, var_name, var_val);
961
962		xfree(var_name);
963	}
964}
965
966static char **
967do_setup_env(Session *s, const char *shell)
968{
969	char buf[256];
970	u_int i, envsize;
971	char **env;
972#ifdef HAVE_LOGIN_CAP
973	extern char **environ;
974	char **senv, **var;
975#endif
976	struct passwd *pw = s->pw;
977
978	/* Initialize the environment. */
979	envsize = 100;
980	env = xmalloc(envsize * sizeof(char *));
981	env[0] = NULL;
982
983#ifdef HAVE_CYGWIN
984	/*
985	 * The Windows environment contains some setting which are
986	 * important for a running system. They must not be dropped.
987	 */
988	copy_environment(environ, &env, &envsize);
989#endif
990
991	if (getenv("TZ"))
992		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
993	if (!options.use_login) {
994		/* Set basic environment. */
995		child_set_env(&env, &envsize, "USER", pw->pw_name);
996		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
997		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
998		snprintf(buf, sizeof buf, "%.200s/%.50s",
999			 _PATH_MAILDIR, pw->pw_name);
1000		child_set_env(&env, &envsize, "MAIL", buf);
1001#ifdef HAVE_LOGIN_CAP
1002		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1003		child_set_env(&env, &envsize, "TERM", "su");
1004		senv = environ;
1005		environ = xmalloc(sizeof(char *));
1006		*environ = NULL;
1007		(void) setusercontext(lc, pw, pw->pw_uid,
1008		    LOGIN_SETENV|LOGIN_SETPATH);
1009		copy_environment(environ, &env, &envsize);
1010		for (var = environ; *var != NULL; ++var)
1011			xfree(*var);
1012		xfree(environ);
1013		environ = senv;
1014#else /* HAVE_LOGIN_CAP */
1015# ifndef HAVE_CYGWIN
1016		/*
1017		 * There's no standard path on Windows. The path contains
1018		 * important components pointing to the system directories,
1019		 * needed for loading shared libraries. So the path better
1020		 * remains intact here.
1021		 */
1022#  ifdef SUPERUSER_PATH
1023		child_set_env(&env, &envsize, "PATH",
1024		    s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1025#  else
1026		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1027#  endif /* SUPERUSER_PATH */
1028# endif /* HAVE_CYGWIN */
1029#endif /* HAVE_LOGIN_CAP */
1030
1031		/* Normal systems set SHELL by default. */
1032		child_set_env(&env, &envsize, "SHELL", shell);
1033	}
1034
1035	/* Set custom environment options from RSA authentication. */
1036	if (!options.use_login) {
1037		while (custom_environment) {
1038			struct envstring *ce = custom_environment;
1039			char *str = ce->s;
1040
1041			for (i = 0; str[i] != '=' && str[i]; i++)
1042				;
1043			if (str[i] == '=') {
1044				str[i] = 0;
1045				child_set_env(&env, &envsize, str, str + i + 1);
1046			}
1047			custom_environment = ce->next;
1048			xfree(ce->s);
1049			xfree(ce);
1050		}
1051	}
1052
1053	/* SSH_CLIENT deprecated */
1054	snprintf(buf, sizeof buf, "%.50s %d %d",
1055	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1056	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1057
1058	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1059	    get_remote_ipaddr(), get_remote_port(),
1060	    get_local_ipaddr(packet_get_connection_in()), get_local_port());
1061	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1062
1063	if (s->ttyfd != -1)
1064		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1065	if (s->term)
1066		child_set_env(&env, &envsize, "TERM", s->term);
1067	if (s->display)
1068		child_set_env(&env, &envsize, "DISPLAY", s->display);
1069	if (original_command)
1070		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1071		    original_command);
1072
1073#ifdef _UNICOS
1074	if (cray_tmpdir[0] != '\0')
1075		child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1076#endif /* _UNICOS */
1077
1078#ifdef _AIX
1079	{
1080		char *cp;
1081
1082		if ((cp = getenv("AUTHSTATE")) != NULL)
1083			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1084		if ((cp = getenv("KRB5CCNAME")) != NULL)
1085			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1086		read_environment_file(&env, &envsize, "/etc/environment");
1087	}
1088#endif
1089#ifdef KRB4
1090	if (s->authctxt->krb4_ticket_file)
1091		child_set_env(&env, &envsize, "KRBTKFILE",
1092		    s->authctxt->krb4_ticket_file);
1093#endif
1094#ifdef KRB5
1095	if (s->authctxt->krb5_ticket_file)
1096		child_set_env(&env, &envsize, "KRB5CCNAME",
1097		    s->authctxt->krb5_ticket_file);
1098#endif
1099#ifdef USE_PAM
1100	/*
1101	 * Pull in any environment variables that may have
1102	 * been set by PAM.
1103	 */
1104	{
1105		char **p;
1106
1107		p = fetch_pam_environment();
1108		copy_environment(p, &env, &envsize);
1109		free_pam_environment(p);
1110	}
1111#endif /* USE_PAM */
1112
1113	if (auth_sock_name != NULL)
1114		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1115		    auth_sock_name);
1116
1117	/* read $HOME/.ssh/environment. */
1118	if (options.permit_user_env && !options.use_login) {
1119		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1120		    strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1121		read_environment_file(&env, &envsize, buf);
1122	}
1123	if (debug_flag) {
1124		/* dump the environment */
1125		fprintf(stderr, "Environment:\n");
1126		for (i = 0; env[i]; i++)
1127			fprintf(stderr, "  %.200s\n", env[i]);
1128	}
1129	return env;
1130}
1131
1132/*
1133 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1134 * first in this order).
1135 */
1136static void
1137do_rc_files(Session *s, const char *shell)
1138{
1139	FILE *f = NULL;
1140	char cmd[1024];
1141	int do_xauth;
1142	struct stat st;
1143
1144	do_xauth =
1145	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1146
1147	/* ignore _PATH_SSH_USER_RC for subsystems */
1148	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1149		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1150		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1151		if (debug_flag)
1152			fprintf(stderr, "Running %s\n", cmd);
1153		f = popen(cmd, "w");
1154		if (f) {
1155			if (do_xauth)
1156				fprintf(f, "%s %s\n", s->auth_proto,
1157				    s->auth_data);
1158			pclose(f);
1159		} else
1160			fprintf(stderr, "Could not run %s\n",
1161			    _PATH_SSH_USER_RC);
1162	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1163		if (debug_flag)
1164			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1165			    _PATH_SSH_SYSTEM_RC);
1166		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1167		if (f) {
1168			if (do_xauth)
1169				fprintf(f, "%s %s\n", s->auth_proto,
1170				    s->auth_data);
1171			pclose(f);
1172		} else
1173			fprintf(stderr, "Could not run %s\n",
1174			    _PATH_SSH_SYSTEM_RC);
1175	} else if (do_xauth && options.xauth_location != NULL) {
1176		/* Add authority data to .Xauthority if appropriate. */
1177		if (debug_flag) {
1178			fprintf(stderr,
1179			    "Running %.500s add "
1180			    "%.100s %.100s %.100s\n",
1181			    options.xauth_location, s->auth_display,
1182			    s->auth_proto, s->auth_data);
1183		}
1184		snprintf(cmd, sizeof cmd, "%s -q -",
1185		    options.xauth_location);
1186		f = popen(cmd, "w");
1187		if (f) {
1188			fprintf(f, "add %s %s %s\n",
1189			    s->auth_display, s->auth_proto,
1190			    s->auth_data);
1191			pclose(f);
1192		} else {
1193			fprintf(stderr, "Could not run %s\n",
1194			    cmd);
1195		}
1196	}
1197}
1198
1199static void
1200do_nologin(struct passwd *pw)
1201{
1202	FILE *f = NULL;
1203	char buf[1024];
1204
1205#ifdef HAVE_LOGIN_CAP
1206	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1207		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1208		    _PATH_NOLOGIN), "r");
1209#else
1210	if (pw->pw_uid)
1211		f = fopen(_PATH_NOLOGIN, "r");
1212#endif
1213	if (f) {
1214		/* /etc/nologin exists.  Print its contents and exit. */
1215		log("User %.100s not allowed because %s exists",
1216		    pw->pw_name, _PATH_NOLOGIN);
1217		while (fgets(buf, sizeof(buf), f))
1218			fputs(buf, stderr);
1219		fclose(f);
1220		exit(254);
1221	}
1222}
1223
1224/* Set login name, uid, gid, and groups. */
1225void
1226do_setusercontext(struct passwd *pw)
1227{
1228#ifdef HAVE_CYGWIN
1229	if (is_winnt) {
1230#else /* HAVE_CYGWIN */
1231	if (getuid() == 0 || geteuid() == 0) {
1232#endif /* HAVE_CYGWIN */
1233#ifdef HAVE_SETPCRED
1234		setpcred(pw->pw_name);
1235#endif /* HAVE_SETPCRED */
1236#ifdef HAVE_LOGIN_CAP
1237# ifdef __bsdi__
1238		setpgid(0, 0);
1239# endif
1240		if (setusercontext(lc, pw, pw->pw_uid,
1241		    (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1242			perror("unable to set user context");
1243			exit(1);
1244		}
1245#else
1246# if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1247		/* Sets login uid for accounting */
1248		if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1249			error("setluid: %s", strerror(errno));
1250# endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1251
1252		if (setlogin(pw->pw_name) < 0)
1253			error("setlogin failed: %s", strerror(errno));
1254		if (setgid(pw->pw_gid) < 0) {
1255			perror("setgid");
1256			exit(1);
1257		}
1258		/* Initialize the group list. */
1259		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1260			perror("initgroups");
1261			exit(1);
1262		}
1263		endgrent();
1264# ifdef USE_PAM
1265		/*
1266		 * PAM credentials may take the form of supplementary groups.
1267		 * These will have been wiped by the above initgroups() call.
1268		 * Reestablish them here.
1269		 */
1270		do_pam_setcred(0);
1271# endif /* USE_PAM */
1272# if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1273		irix_setusercontext(pw);
1274#  endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1275# ifdef _AIX
1276		aix_usrinfo(pw);
1277# endif /* _AIX */
1278		/* Permanently switch to the desired uid. */
1279		permanently_set_uid(pw);
1280#endif
1281	}
1282	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1283		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1284}
1285
1286static void
1287launch_login(struct passwd *pw, const char *hostname)
1288{
1289	/* Launch login(1). */
1290
1291	execl(LOGIN_PROGRAM, "login", "-h", hostname,
1292#ifdef xxxLOGIN_NEEDS_TERM
1293		    (s->term ? s->term : "unknown"),
1294#endif /* LOGIN_NEEDS_TERM */
1295#ifdef LOGIN_NO_ENDOPT
1296	    "-p", "-f", pw->pw_name, (char *)NULL);
1297#else
1298	    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1299#endif
1300
1301	/* Login couldn't be executed, die. */
1302
1303	perror("login");
1304	exit(1);
1305}
1306
1307/*
1308 * Performs common processing for the child, such as setting up the
1309 * environment, closing extra file descriptors, setting the user and group
1310 * ids, and executing the command or shell.
1311 */
1312void
1313do_child(Session *s, const char *command)
1314{
1315	extern char **environ;
1316	char **env;
1317	char *argv[10];
1318	const char *shell, *shell0, *hostname = NULL;
1319	struct passwd *pw = s->pw;
1320	u_int i;
1321#ifdef HAVE_LOGIN_CAP
1322	int lc_requirehome;
1323#endif
1324
1325	/* remove hostkey from the child's memory */
1326	destroy_sensitive_data();
1327
1328	/* login(1) is only called if we execute the login shell */
1329	if (options.use_login && command != NULL)
1330		options.use_login = 0;
1331
1332#ifdef _UNICOS
1333	cray_setup(pw->pw_uid, pw->pw_name, command);
1334#endif /* _UNICOS */
1335
1336	/*
1337	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1338	 * switch, so we let login(1) to this for us.
1339	 */
1340	if (!options.use_login) {
1341#ifdef HAVE_OSF_SIA
1342		session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1343		if (!check_quietlogin(s, command))
1344			do_motd();
1345#else /* HAVE_OSF_SIA */
1346		do_nologin(pw);
1347		do_setusercontext(pw);
1348#endif /* HAVE_OSF_SIA */
1349	}
1350
1351	/*
1352	 * Get the shell from the password data.  An empty shell field is
1353	 * legal, and means /bin/sh.
1354	 */
1355	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1356#ifdef HAVE_LOGIN_CAP
1357	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1358#endif
1359
1360	env = do_setup_env(s, shell);
1361
1362	/* we have to stash the hostname before we close our socket. */
1363	if (options.use_login)
1364		hostname = get_remote_name_or_ip(utmp_len,
1365		    options.verify_reverse_mapping);
1366	/*
1367	 * Close the connection descriptors; note that this is the child, and
1368	 * the server will still have the socket open, and it is important
1369	 * that we do not shutdown it.  Note that the descriptors cannot be
1370	 * closed before building the environment, as we call
1371	 * get_remote_ipaddr there.
1372	 */
1373	if (packet_get_connection_in() == packet_get_connection_out())
1374		close(packet_get_connection_in());
1375	else {
1376		close(packet_get_connection_in());
1377		close(packet_get_connection_out());
1378	}
1379	/*
1380	 * Close all descriptors related to channels.  They will still remain
1381	 * open in the parent.
1382	 */
1383	/* XXX better use close-on-exec? -markus */
1384	channel_close_all();
1385
1386#ifdef HAVE_LOGIN_CAP
1387	lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1388	login_close(lc);
1389#endif
1390	/*
1391	 * Close any extra file descriptors.  Note that there may still be
1392	 * descriptors left by system functions.  They will be closed later.
1393	 */
1394	endpwent();
1395
1396	/*
1397	 * Close any extra open file descriptors so that we don\'t have them
1398	 * hanging around in clients.  Note that we want to do this after
1399	 * initgroups, because at least on Solaris 2.3 it leaves file
1400	 * descriptors open.
1401	 */
1402	for (i = 3; i < 64; i++)
1403		close(i);
1404
1405	/*
1406	 * Must take new environment into use so that .ssh/rc,
1407	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1408	 */
1409	environ = env;
1410
1411#ifdef AFS
1412	/* Try to get AFS tokens for the local cell. */
1413	if (k_hasafs()) {
1414		char cell[64];
1415
1416		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1417			krb_afslog(cell, 0);
1418
1419		krb_afslog(0, 0);
1420	}
1421#endif /* AFS */
1422
1423	/* Change current directory to the user\'s home directory. */
1424	if (chdir(pw->pw_dir) < 0) {
1425		fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1426		    pw->pw_dir, strerror(errno));
1427#ifdef HAVE_LOGIN_CAP
1428		if (lc_requirehome)
1429			exit(1);
1430#endif
1431	}
1432
1433	if (!options.use_login)
1434		do_rc_files(s, shell);
1435
1436	/* restore SIGPIPE for child */
1437	signal(SIGPIPE,  SIG_DFL);
1438
1439	if (options.use_login) {
1440		launch_login(pw, hostname);
1441		/* NEVERREACHED */
1442	}
1443
1444	/* Get the last component of the shell name. */
1445	if ((shell0 = strrchr(shell, '/')) != NULL)
1446		shell0++;
1447	else
1448		shell0 = shell;
1449
1450	/*
1451	 * If we have no command, execute the shell.  In this case, the shell
1452	 * name to be passed in argv[0] is preceded by '-' to indicate that
1453	 * this is a login shell.
1454	 */
1455	if (!command) {
1456		char argv0[256];
1457
1458		/* Start the shell.  Set initial character to '-'. */
1459		argv0[0] = '-';
1460
1461		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1462		    >= sizeof(argv0) - 1) {
1463			errno = EINVAL;
1464			perror(shell);
1465			exit(1);
1466		}
1467
1468		/* Execute the shell. */
1469		argv[0] = argv0;
1470		argv[1] = NULL;
1471		execve(shell, argv, env);
1472
1473		/* Executing the shell failed. */
1474		perror(shell);
1475		exit(1);
1476	}
1477	/*
1478	 * Execute the command using the user's shell.  This uses the -c
1479	 * option to execute the command.
1480	 */
1481	argv[0] = (char *) shell0;
1482	argv[1] = "-c";
1483	argv[2] = (char *) command;
1484	argv[3] = NULL;
1485	execve(shell, argv, env);
1486	perror(shell);
1487	exit(1);
1488}
1489
1490Session *
1491session_new(void)
1492{
1493	int i;
1494	static int did_init = 0;
1495	if (!did_init) {
1496		debug("session_new: init");
1497		for (i = 0; i < MAX_SESSIONS; i++) {
1498			sessions[i].used = 0;
1499		}
1500		did_init = 1;
1501	}
1502	for (i = 0; i < MAX_SESSIONS; i++) {
1503		Session *s = &sessions[i];
1504		if (! s->used) {
1505			memset(s, 0, sizeof(*s));
1506			s->chanid = -1;
1507			s->ptyfd = -1;
1508			s->ttyfd = -1;
1509			s->used = 1;
1510			s->self = i;
1511			debug("session_new: session %d", i);
1512			return s;
1513		}
1514	}
1515	return NULL;
1516}
1517
1518static void
1519session_dump(void)
1520{
1521	int i;
1522	for (i = 0; i < MAX_SESSIONS; i++) {
1523		Session *s = &sessions[i];
1524		debug("dump: used %d session %d %p channel %d pid %ld",
1525		    s->used,
1526		    s->self,
1527		    s,
1528		    s->chanid,
1529		    (long)s->pid);
1530	}
1531}
1532
1533int
1534session_open(Authctxt *authctxt, int chanid)
1535{
1536	Session *s = session_new();
1537	debug("session_open: channel %d", chanid);
1538	if (s == NULL) {
1539		error("no more sessions");
1540		return 0;
1541	}
1542	s->authctxt = authctxt;
1543	s->pw = authctxt->pw;
1544	if (s->pw == NULL)
1545		fatal("no user for session %d", s->self);
1546	debug("session_open: session %d: link with channel %d", s->self, chanid);
1547	s->chanid = chanid;
1548	return 1;
1549}
1550
1551Session *
1552session_by_tty(char *tty)
1553{
1554	int i;
1555	for (i = 0; i < MAX_SESSIONS; i++) {
1556		Session *s = &sessions[i];
1557		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1558			debug("session_by_tty: session %d tty %s", i, tty);
1559			return s;
1560		}
1561	}
1562	debug("session_by_tty: unknown tty %.100s", tty);
1563	session_dump();
1564	return NULL;
1565}
1566
1567static Session *
1568session_by_channel(int id)
1569{
1570	int i;
1571	for (i = 0; i < MAX_SESSIONS; i++) {
1572		Session *s = &sessions[i];
1573		if (s->used && s->chanid == id) {
1574			debug("session_by_channel: session %d channel %d", i, id);
1575			return s;
1576		}
1577	}
1578	debug("session_by_channel: unknown channel %d", id);
1579	session_dump();
1580	return NULL;
1581}
1582
1583static Session *
1584session_by_pid(pid_t pid)
1585{
1586	int i;
1587	debug("session_by_pid: pid %ld", (long)pid);
1588	for (i = 0; i < MAX_SESSIONS; i++) {
1589		Session *s = &sessions[i];
1590		if (s->used && s->pid == pid)
1591			return s;
1592	}
1593	error("session_by_pid: unknown pid %ld", (long)pid);
1594	session_dump();
1595	return NULL;
1596}
1597
1598static int
1599session_window_change_req(Session *s)
1600{
1601	s->col = packet_get_int();
1602	s->row = packet_get_int();
1603	s->xpixel = packet_get_int();
1604	s->ypixel = packet_get_int();
1605	packet_check_eom();
1606	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1607	return 1;
1608}
1609
1610static int
1611session_pty_req(Session *s)
1612{
1613	u_int len;
1614	int n_bytes;
1615
1616	if (no_pty_flag) {
1617		debug("Allocating a pty not permitted for this authentication.");
1618		return 0;
1619	}
1620	if (s->ttyfd != -1) {
1621		packet_disconnect("Protocol error: you already have a pty.");
1622		return 0;
1623	}
1624	/* Get the time and hostname when the user last logged in. */
1625	if (options.print_lastlog) {
1626		s->hostname[0] = '\0';
1627		s->last_login_time = get_last_login_time(s->pw->pw_uid,
1628		    s->pw->pw_name, s->hostname, sizeof(s->hostname));
1629	}
1630
1631	s->term = packet_get_string(&len);
1632
1633	if (compat20) {
1634		s->col = packet_get_int();
1635		s->row = packet_get_int();
1636	} else {
1637		s->row = packet_get_int();
1638		s->col = packet_get_int();
1639	}
1640	s->xpixel = packet_get_int();
1641	s->ypixel = packet_get_int();
1642
1643	if (strcmp(s->term, "") == 0) {
1644		xfree(s->term);
1645		s->term = NULL;
1646	}
1647
1648	/* Allocate a pty and open it. */
1649	debug("Allocating pty.");
1650	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1651		if (s->term)
1652			xfree(s->term);
1653		s->term = NULL;
1654		s->ptyfd = -1;
1655		s->ttyfd = -1;
1656		error("session_pty_req: session %d alloc failed", s->self);
1657		return 0;
1658	}
1659	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1660
1661	/* for SSH1 the tty modes length is not given */
1662	if (!compat20)
1663		n_bytes = packet_remaining();
1664	tty_parse_modes(s->ttyfd, &n_bytes);
1665
1666	/*
1667	 * Add a cleanup function to clear the utmp entry and record logout
1668	 * time in case we call fatal() (e.g., the connection gets closed).
1669	 */
1670	fatal_add_cleanup(session_pty_cleanup, (void *)s);
1671	if (!use_privsep)
1672		pty_setowner(s->pw, s->tty);
1673
1674	/* Set window size from the packet. */
1675	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1676
1677	packet_check_eom();
1678	session_proctitle(s);
1679	return 1;
1680}
1681
1682static int
1683session_subsystem_req(Session *s)
1684{
1685	struct stat st;
1686	u_int len;
1687	int success = 0;
1688	char *cmd, *subsys = packet_get_string(&len);
1689	int i;
1690
1691	packet_check_eom();
1692	log("subsystem request for %.100s", subsys);
1693
1694	for (i = 0; i < options.num_subsystems; i++) {
1695		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1696			cmd = options.subsystem_command[i];
1697			if (stat(cmd, &st) < 0) {
1698				error("subsystem: cannot stat %s: %s", cmd,
1699				    strerror(errno));
1700				break;
1701			}
1702			debug("subsystem: exec() %s", cmd);
1703			s->is_subsystem = 1;
1704			do_exec(s, cmd);
1705			success = 1;
1706			break;
1707		}
1708	}
1709
1710	if (!success)
1711		log("subsystem request for %.100s failed, subsystem not found",
1712		    subsys);
1713
1714	xfree(subsys);
1715	return success;
1716}
1717
1718static int
1719session_x11_req(Session *s)
1720{
1721	int success;
1722
1723	s->single_connection = packet_get_char();
1724	s->auth_proto = packet_get_string(NULL);
1725	s->auth_data = packet_get_string(NULL);
1726	s->screen = packet_get_int();
1727	packet_check_eom();
1728
1729	success = session_setup_x11fwd(s);
1730	if (!success) {
1731		xfree(s->auth_proto);
1732		xfree(s->auth_data);
1733		s->auth_proto = NULL;
1734		s->auth_data = NULL;
1735	}
1736	return success;
1737}
1738
1739static int
1740session_shell_req(Session *s)
1741{
1742	packet_check_eom();
1743	do_exec(s, NULL);
1744	return 1;
1745}
1746
1747static int
1748session_exec_req(Session *s)
1749{
1750	u_int len;
1751	char *command = packet_get_string(&len);
1752	packet_check_eom();
1753	do_exec(s, command);
1754	xfree(command);
1755	return 1;
1756}
1757
1758static int
1759session_auth_agent_req(Session *s)
1760{
1761	static int called = 0;
1762	packet_check_eom();
1763	if (no_agent_forwarding_flag) {
1764		debug("session_auth_agent_req: no_agent_forwarding_flag");
1765		return 0;
1766	}
1767	if (called) {
1768		return 0;
1769	} else {
1770		called = 1;
1771		return auth_input_request_forwarding(s->pw);
1772	}
1773}
1774
1775int
1776session_input_channel_req(Channel *c, const char *rtype)
1777{
1778	int success = 0;
1779	Session *s;
1780
1781	if ((s = session_by_channel(c->self)) == NULL) {
1782		log("session_input_channel_req: no session %d req %.100s",
1783		    c->self, rtype);
1784		return 0;
1785	}
1786	debug("session_input_channel_req: session %d req %s", s->self, rtype);
1787
1788	/*
1789	 * a session is in LARVAL state until a shell, a command
1790	 * or a subsystem is executed
1791	 */
1792	if (c->type == SSH_CHANNEL_LARVAL) {
1793		if (strcmp(rtype, "shell") == 0) {
1794			success = session_shell_req(s);
1795		} else if (strcmp(rtype, "exec") == 0) {
1796			success = session_exec_req(s);
1797		} else if (strcmp(rtype, "pty-req") == 0) {
1798			success =  session_pty_req(s);
1799		} else if (strcmp(rtype, "x11-req") == 0) {
1800			success = session_x11_req(s);
1801		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1802			success = session_auth_agent_req(s);
1803		} else if (strcmp(rtype, "subsystem") == 0) {
1804			success = session_subsystem_req(s);
1805		}
1806	}
1807	if (strcmp(rtype, "window-change") == 0) {
1808		success = session_window_change_req(s);
1809	}
1810	return success;
1811}
1812
1813void
1814session_set_fds(Session *s, int fdin, int fdout, int fderr)
1815{
1816	if (!compat20)
1817		fatal("session_set_fds: called for proto != 2.0");
1818	/*
1819	 * now that have a child and a pipe to the child,
1820	 * we can activate our channel and register the fd's
1821	 */
1822	if (s->chanid == -1)
1823		fatal("no channel for session %d", s->self);
1824	channel_set_fds(s->chanid,
1825	    fdout, fdin, fderr,
1826	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1827	    1,
1828	    CHAN_SES_WINDOW_DEFAULT);
1829}
1830
1831/*
1832 * Function to perform pty cleanup. Also called if we get aborted abnormally
1833 * (e.g., due to a dropped connection).
1834 */
1835void
1836session_pty_cleanup2(void *session)
1837{
1838	Session *s = session;
1839
1840	if (s == NULL) {
1841		error("session_pty_cleanup: no session");
1842		return;
1843	}
1844	if (s->ttyfd == -1)
1845		return;
1846
1847	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1848
1849	/* Record that the user has logged out. */
1850	if (s->pid != 0)
1851		record_logout(s->pid, s->tty, s->pw->pw_name);
1852
1853	/* Release the pseudo-tty. */
1854	if (getuid() == 0)
1855		pty_release(s->tty);
1856
1857	/*
1858	 * Close the server side of the socket pairs.  We must do this after
1859	 * the pty cleanup, so that another process doesn't get this pty
1860	 * while we're still cleaning up.
1861	 */
1862	if (close(s->ptymaster) < 0)
1863		error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1864
1865	/* unlink pty from session */
1866	s->ttyfd = -1;
1867}
1868
1869void
1870session_pty_cleanup(void *session)
1871{
1872	PRIVSEP(session_pty_cleanup2(session));
1873}
1874
1875static char *
1876sig2name(int sig)
1877{
1878#define SSH_SIG(x) if (sig == SIG ## x) return #x
1879	SSH_SIG(ABRT);
1880	SSH_SIG(ALRM);
1881	SSH_SIG(FPE);
1882	SSH_SIG(HUP);
1883	SSH_SIG(ILL);
1884	SSH_SIG(INT);
1885	SSH_SIG(KILL);
1886	SSH_SIG(PIPE);
1887	SSH_SIG(QUIT);
1888	SSH_SIG(SEGV);
1889	SSH_SIG(TERM);
1890	SSH_SIG(USR1);
1891	SSH_SIG(USR2);
1892#undef	SSH_SIG
1893	return "SIG@openssh.com";
1894}
1895
1896static void
1897session_exit_message(Session *s, int status)
1898{
1899	Channel *c;
1900
1901	if ((c = channel_lookup(s->chanid)) == NULL)
1902		fatal("session_exit_message: session %d: no channel %d",
1903		    s->self, s->chanid);
1904	debug("session_exit_message: session %d channel %d pid %ld",
1905	    s->self, s->chanid, (long)s->pid);
1906
1907	if (WIFEXITED(status)) {
1908		channel_request_start(s->chanid, "exit-status", 0);
1909		packet_put_int(WEXITSTATUS(status));
1910		packet_send();
1911	} else if (WIFSIGNALED(status)) {
1912		channel_request_start(s->chanid, "exit-signal", 0);
1913		packet_put_cstring(sig2name(WTERMSIG(status)));
1914#ifdef WCOREDUMP
1915		packet_put_char(WCOREDUMP(status));
1916#else /* WCOREDUMP */
1917		packet_put_char(0);
1918#endif /* WCOREDUMP */
1919		packet_put_cstring("");
1920		packet_put_cstring("");
1921		packet_send();
1922	} else {
1923		/* Some weird exit cause.  Just exit. */
1924		packet_disconnect("wait returned status %04x.", status);
1925	}
1926
1927	/* disconnect channel */
1928	debug("session_exit_message: release channel %d", s->chanid);
1929	channel_cancel_cleanup(s->chanid);
1930	/*
1931	 * emulate a write failure with 'chan_write_failed', nobody will be
1932	 * interested in data we write.
1933	 * Note that we must not call 'chan_read_failed', since there could
1934	 * be some more data waiting in the pipe.
1935	 */
1936	if (c->ostate != CHAN_OUTPUT_CLOSED)
1937		chan_write_failed(c);
1938	s->chanid = -1;
1939}
1940
1941void
1942session_close(Session *s)
1943{
1944	debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1945	if (s->ttyfd != -1) {
1946		fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1947		session_pty_cleanup(s);
1948	}
1949	if (s->term)
1950		xfree(s->term);
1951	if (s->display)
1952		xfree(s->display);
1953	if (s->auth_display)
1954		xfree(s->auth_display);
1955	if (s->auth_data)
1956		xfree(s->auth_data);
1957	if (s->auth_proto)
1958		xfree(s->auth_proto);
1959	s->used = 0;
1960	session_proctitle(s);
1961}
1962
1963void
1964session_close_by_pid(pid_t pid, int status)
1965{
1966	Session *s = session_by_pid(pid);
1967	if (s == NULL) {
1968		debug("session_close_by_pid: no session for pid %ld",
1969		    (long)pid);
1970		return;
1971	}
1972	if (s->chanid != -1)
1973		session_exit_message(s, status);
1974	session_close(s);
1975}
1976
1977/*
1978 * this is called when a channel dies before
1979 * the session 'child' itself dies
1980 */
1981void
1982session_close_by_channel(int id, void *arg)
1983{
1984	Session *s = session_by_channel(id);
1985	if (s == NULL) {
1986		debug("session_close_by_channel: no session for id %d", id);
1987		return;
1988	}
1989	debug("session_close_by_channel: channel %d child %ld",
1990	    id, (long)s->pid);
1991	if (s->pid != 0) {
1992		debug("session_close_by_channel: channel %d: has child", id);
1993		/*
1994		 * delay detach of session, but release pty, since
1995		 * the fd's to the child are already closed
1996		 */
1997		if (s->ttyfd != -1) {
1998			fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1999			session_pty_cleanup(s);
2000		}
2001		return;
2002	}
2003	/* detach by removing callback */
2004	channel_cancel_cleanup(s->chanid);
2005	s->chanid = -1;
2006	session_close(s);
2007}
2008
2009void
2010session_destroy_all(void (*closefunc)(Session *))
2011{
2012	int i;
2013	for (i = 0; i < MAX_SESSIONS; i++) {
2014		Session *s = &sessions[i];
2015		if (s->used) {
2016			if (closefunc != NULL)
2017				closefunc(s);
2018			else
2019				session_close(s);
2020		}
2021	}
2022}
2023
2024static char *
2025session_tty_list(void)
2026{
2027	static char buf[1024];
2028	int i;
2029	buf[0] = '\0';
2030	for (i = 0; i < MAX_SESSIONS; i++) {
2031		Session *s = &sessions[i];
2032		if (s->used && s->ttyfd != -1) {
2033			if (buf[0] != '\0')
2034				strlcat(buf, ",", sizeof buf);
2035			strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2036		}
2037	}
2038	if (buf[0] == '\0')
2039		strlcpy(buf, "notty", sizeof buf);
2040	return buf;
2041}
2042
2043void
2044session_proctitle(Session *s)
2045{
2046	if (s->pw == NULL)
2047		error("no user for session %d", s->self);
2048	else
2049		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2050}
2051
2052int
2053session_setup_x11fwd(Session *s)
2054{
2055	struct stat st;
2056	char display[512], auth_display[512];
2057	char hostname[MAXHOSTNAMELEN];
2058
2059	if (no_x11_forwarding_flag) {
2060		packet_send_debug("X11 forwarding disabled in user configuration file.");
2061		return 0;
2062	}
2063	if (!options.x11_forwarding) {
2064		debug("X11 forwarding disabled in server configuration file.");
2065		return 0;
2066	}
2067	if (!options.xauth_location ||
2068	    (stat(options.xauth_location, &st) == -1)) {
2069		packet_send_debug("No xauth program; cannot forward with spoofing.");
2070		return 0;
2071	}
2072	if (options.use_login) {
2073		packet_send_debug("X11 forwarding disabled; "
2074		    "not compatible with UseLogin=yes.");
2075		return 0;
2076	}
2077	if (s->display != NULL) {
2078		debug("X11 display already set.");
2079		return 0;
2080	}
2081	if (x11_create_display_inet(options.x11_display_offset,
2082	    options.x11_use_localhost, s->single_connection,
2083	    &s->display_number) == -1) {
2084		debug("x11_create_display_inet failed.");
2085		return 0;
2086	}
2087
2088	/* Set up a suitable value for the DISPLAY variable. */
2089	if (gethostname(hostname, sizeof(hostname)) < 0)
2090		fatal("gethostname: %.100s", strerror(errno));
2091	/*
2092	 * auth_display must be used as the displayname when the
2093	 * authorization entry is added with xauth(1).  This will be
2094	 * different than the DISPLAY string for localhost displays.
2095	 */
2096	if (options.x11_use_localhost) {
2097		snprintf(display, sizeof display, "localhost:%u.%u",
2098		    s->display_number, s->screen);
2099		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2100		    s->display_number, s->screen);
2101		s->display = xstrdup(display);
2102		s->auth_display = xstrdup(auth_display);
2103	} else {
2104#ifdef IPADDR_IN_DISPLAY
2105		struct hostent *he;
2106		struct in_addr my_addr;
2107
2108		he = gethostbyname(hostname);
2109		if (he == NULL) {
2110			error("Can't get IP address for X11 DISPLAY.");
2111			packet_send_debug("Can't get IP address for X11 DISPLAY.");
2112			return 0;
2113		}
2114		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2115		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2116		    s->display_number, s->screen);
2117#else
2118		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2119		    s->display_number, s->screen);
2120#endif
2121		s->display = xstrdup(display);
2122		s->auth_display = xstrdup(display);
2123	}
2124
2125	return 1;
2126}
2127
2128static void
2129do_authenticated2(Authctxt *authctxt)
2130{
2131	server_loop2(authctxt);
2132}
2133