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