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