session.c revision 95242
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 95242 2002-04-22 06:26:29Z des $");
38
39#include "ssh.h"
40#include "ssh1.h"
41#include "ssh2.h"
42#include "xmalloc.h"
43#include "sshpty.h"
44#include "packet.h"
45#include "buffer.h"
46#include "mpaux.h"
47#include "uidswap.h"
48#include "compat.h"
49#include "channels.h"
50#include "bufaux.h"
51#include "auth.h"
52#include "auth-options.h"
53#include "pathnames.h"
54#include "log.h"
55#include "servconf.h"
56#include "sshlogin.h"
57#include "serverloop.h"
58#include "canohost.h"
59#include "session.h"
60
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#ifndef USE_PAM
608	char *time_string;
609	char *newcommand = NULL;
610#endif
611	char buf[256];
612#ifndef USE_PAM
613	char hostname[MAXHOSTNAMELEN];
614	socklen_t fromlen;
615	struct sockaddr_storage from;
616	time_t last_login_time;
617#endif
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#ifndef USE_PAM
651	/* Get the time and hostname when the user last logged in. */
652	if (options.print_lastlog) {
653		hostname[0] = '\0';
654		last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
655		    hostname, sizeof(hostname));
656	}
657
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#ifndef USE_PAM
740	/*
741	 * If the user has logged in before, display the time of last
742	 * login. However, don't display anything extra if a command
743	 * has been specified (so that ssh can be used to execute
744	 * commands on a remote machine without users knowing they
745	 * are going to another machine). Login(1) will do this for
746	 * us as well, so check if login(1) is used
747	 */
748
749	if (command == NULL && options.print_lastlog &&
750	    last_login_time != 0 && !check_quietlogin(s, command) &&
751	    !options.use_login) {
752		time_string = ctime(&last_login_time);
753		if (strchr(time_string, '\n'))
754			*strchr(time_string, '\n') = 0;
755		if (strcmp(hostname, "") == 0)
756			printf("Last login: %s\r\n", time_string);
757		else
758			printf("Last login: %s from %s\r\n", time_string, hostname);
759	}
760#endif /* !USE_PAM */
761
762#ifdef HAVE_LOGIN_CAP
763	if (command == NULL && !check_quietlogin(s, command) &&
764	    !options.use_login) {
765		fname = login_getcapstr(lc, "copyright", NULL, NULL);
766		if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
767			while (fgets(buf, sizeof(buf), f) != NULL)
768				fputs(buf, stdout);
769				fclose(f);
770		} else
771			(void)printf("%s\n\t%s %s\n",
772		"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
773		"The Regents of the University of California. ",
774		"All rights reserved.");
775	}
776#endif /* HAVE_LOGIN_CAP */
777
778	/*
779	 * Print /etc/motd unless a command was specified or printing
780	 * it was disabled in server options or login(1) will be
781	 * used.  Note that some machines appear to print it in
782	 * /etc/profile or similar.
783	 */
784	if (command == NULL && !check_quietlogin(s, command) && !options.use_login)
785		do_motd();
786}
787
788/*
789 * Display the message of the day.
790 */
791void
792do_motd(void)
793{
794	FILE *f;
795	char buf[256];
796
797	if (options.print_motd) {
798#ifdef HAVE_LOGIN_CAP
799		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
800		    "/etc/motd"), "r");
801#else
802		f = fopen("/etc/motd", "r");
803#endif
804		if (f) {
805			while (fgets(buf, sizeof(buf), f))
806				fputs(buf, stdout);
807			fclose(f);
808		}
809	}
810}
811
812
813/*
814 * Check for quiet login, either .hushlogin or command given.
815 */
816int
817check_quietlogin(Session *s, const char *command)
818{
819	char buf[256];
820	struct passwd *pw = s->pw;
821	struct stat st;
822
823	/* Return 1 if .hushlogin exists or a command given. */
824	if (command != NULL)
825		return 1;
826	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
827#ifdef HAVE_LOGIN_CAP
828	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
829		return 1;
830#else
831	if (stat(buf, &st) >= 0)
832		return 1;
833#endif
834	return 0;
835}
836
837/*
838 * Sets the value of the given variable in the environment.  If the variable
839 * already exists, its value is overriden.
840 */
841static void
842child_set_env(char ***envp, u_int *envsizep, const char *name,
843	const char *value)
844{
845	u_int i, namelen;
846	char **env;
847
848	/*
849	 * Find the slot where the value should be stored.  If the variable
850	 * already exists, we reuse the slot; otherwise we append a new slot
851	 * at the end of the array, expanding if necessary.
852	 */
853	env = *envp;
854	namelen = strlen(name);
855	for (i = 0; env[i]; i++)
856		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
857			break;
858	if (env[i]) {
859		/* Reuse the slot. */
860		xfree(env[i]);
861	} else {
862		/* New variable.  Expand if necessary. */
863		if (i >= (*envsizep) - 1) {
864			(*envsizep) += 50;
865			env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
866		}
867		/* Need to set the NULL pointer at end of array beyond the new slot. */
868		env[i + 1] = NULL;
869	}
870
871	/* Allocate space and format the variable in the appropriate slot. */
872	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
873	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
874}
875
876/*
877 * Reads environment variables from the given file and adds/overrides them
878 * into the environment.  If the file does not exist, this does nothing.
879 * Otherwise, it must consist of empty lines, comments (line starts with '#')
880 * and assignments of the form name=value.  No other forms are allowed.
881 */
882static void
883read_environment_file(char ***env, u_int *envsize,
884	const char *filename)
885{
886	FILE *f;
887	char buf[4096];
888	char *cp, *value;
889
890	f = fopen(filename, "r");
891	if (!f)
892		return;
893
894	while (fgets(buf, sizeof(buf), f)) {
895		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
896			;
897		if (!*cp || *cp == '#' || *cp == '\n')
898			continue;
899		if (strchr(cp, '\n'))
900			*strchr(cp, '\n') = '\0';
901		value = strchr(cp, '=');
902		if (value == NULL) {
903			fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
904			continue;
905		}
906		/*
907		 * Replace the equals sign by nul, and advance value to
908		 * the value string.
909		 */
910		*value = '\0';
911		value++;
912		child_set_env(env, envsize, cp, value);
913	}
914	fclose(f);
915}
916
917#ifdef USE_PAM
918/*
919 * Sets any environment variables which have been specified by PAM
920 */
921static void
922do_pam_environment(char ***env, u_int *envsize)
923{
924	char *equals, var_name[512], var_val[512];
925	char **pam_env;
926	int i;
927
928	if ((pam_env = fetch_pam_environment()) == NULL)
929		return;
930
931	for(i = 0; pam_env[i] != NULL; i++) {
932		if ((equals = strstr(pam_env[i], "=")) == NULL)
933			continue;
934
935		if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
936			memset(var_name, '\0', sizeof(var_name));
937			memset(var_val, '\0', sizeof(var_val));
938
939			strncpy(var_name, pam_env[i], equals - pam_env[i]);
940			strcpy(var_val, equals + 1);
941
942			child_set_env(env, envsize, var_name, var_val);
943		}
944	}
945}
946#endif /* USE_PAM */
947
948static char **
949do_setup_env(char **env, Session *s, const char *shell)
950{
951	char buf[256];
952	u_int i, envsize;
953	struct passwd *pw = s->pw;
954
955	if (env == NULL) {
956		/* Initialize the environment. */
957		envsize = 100;
958		env = xmalloc(envsize * sizeof(char *));
959		env[0] = NULL;
960	} else {
961		for (envsize = 0; env[envsize] != NULL; ++envsize)
962			;
963		envsize = (envsize < 100) ? 100 : envsize + 50;
964		env = xrealloc(env, envsize * sizeof(char *));
965	}
966
967	if (!options.use_login) {
968		/* Set basic environment. */
969		child_set_env(&env, &envsize, "USER", pw->pw_name);
970		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
971		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
972#ifndef HAVE_LOGIN_CAP
973		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
974
975		snprintf(buf, sizeof buf, "%.200s/%.50s",
976			 _PATH_MAILDIR, pw->pw_name);
977		child_set_env(&env, &envsize, "MAIL", buf);
978#endif /* !HAVE_LOGIN_CAP */
979
980		/* Normal systems set SHELL by default. */
981		child_set_env(&env, &envsize, "SHELL", shell);
982	}
983	if (getenv("TZ"))
984#ifdef HAVE_LOGIN_CAP
985	    if (options.use_login)
986#endif /* HAVE_LOGIN_CAP */
987		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
988
989	/* Set custom environment options from RSA authentication. */
990	if (!options.use_login) {
991		while (custom_environment) {
992			struct envstring *ce = custom_environment;
993			char *s = ce->s;
994
995			for (i = 0; s[i] != '=' && s[i]; i++)
996				;
997			if (s[i] == '=') {
998				s[i] = 0;
999				child_set_env(&env, &envsize, s, s + i + 1);
1000			}
1001			custom_environment = ce->next;
1002			xfree(ce->s);
1003			xfree(ce);
1004		}
1005	}
1006
1007	snprintf(buf, sizeof buf, "%.50s %d %d",
1008	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1009	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1010
1011	if (s->ttyfd != -1)
1012		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1013	if (s->term)
1014#ifdef HAVE_LOGIN_CAP
1015	    if (options.use_login)
1016#endif /* HAVE_LOGIN_CAP */
1017		child_set_env(&env, &envsize, "TERM", s->term);
1018	if (s->display)
1019		child_set_env(&env, &envsize, "DISPLAY", s->display);
1020	if (original_command)
1021		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1022		    original_command);
1023#ifdef KRB4
1024	if (s->authctxt->krb4_ticket_file)
1025		child_set_env(&env, &envsize, "KRBTKFILE",
1026		    s->authctxt->krb4_ticket_file);
1027#endif
1028#ifdef KRB5
1029	if (s->authctxt->krb5_ticket_file)
1030		child_set_env(&env, &envsize, "KRB5CCNAME",
1031		    s->authctxt->krb5_ticket_file);
1032#endif
1033
1034#ifdef USE_PAM
1035	/* Pull in any environment variables that may have been set by PAM. */
1036	do_pam_environment(&env, &envsize);
1037#endif /* USE_PAM */
1038
1039	if (auth_get_socket_name() != NULL)
1040		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1041		    auth_get_socket_name());
1042
1043	/* read $HOME/.ssh/environment. */
1044	if (!options.use_login) {
1045		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1046		    pw->pw_dir);
1047		read_environment_file(&env, &envsize, buf);
1048	}
1049	if (debug_flag) {
1050		/* dump the environment */
1051		fprintf(stderr, "Environment:\n");
1052		for (i = 0; env[i]; i++)
1053			fprintf(stderr, "  %.200s\n", env[i]);
1054	}
1055	return env;
1056}
1057
1058/*
1059 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1060 * first in this order).
1061 */
1062static void
1063do_rc_files(Session *s, const char *shell)
1064{
1065	FILE *f = NULL;
1066	char cmd[1024];
1067	int do_xauth;
1068	struct stat st;
1069
1070	do_xauth =
1071	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1072
1073	/* ignore _PATH_SSH_USER_RC for subsystems */
1074	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1075		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1076		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1077		if (debug_flag)
1078			fprintf(stderr, "Running %s\n", cmd);
1079		f = popen(cmd, "w");
1080		if (f) {
1081			if (do_xauth)
1082				fprintf(f, "%s %s\n", s->auth_proto,
1083				    s->auth_data);
1084			pclose(f);
1085		} else
1086			fprintf(stderr, "Could not run %s\n",
1087			    _PATH_SSH_USER_RC);
1088	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1089		if (debug_flag)
1090			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1091			    _PATH_SSH_SYSTEM_RC);
1092		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1093		if (f) {
1094			if (do_xauth)
1095				fprintf(f, "%s %s\n", s->auth_proto,
1096				    s->auth_data);
1097			pclose(f);
1098		} else
1099			fprintf(stderr, "Could not run %s\n",
1100			    _PATH_SSH_SYSTEM_RC);
1101	} else if (do_xauth && options.xauth_location != NULL) {
1102		/* Add authority data to .Xauthority if appropriate. */
1103		if (debug_flag) {
1104			fprintf(stderr,
1105			    "Running %.100s add "
1106			    "%.100s %.100s %.100s\n",
1107			    options.xauth_location, s->auth_display,
1108			    s->auth_proto, s->auth_data);
1109		}
1110		snprintf(cmd, sizeof cmd, "%s -q -",
1111		    options.xauth_location);
1112		f = popen(cmd, "w");
1113		if (f) {
1114			fprintf(f, "add %s %s %s\n",
1115			    s->auth_display, s->auth_proto,
1116			    s->auth_data);
1117			pclose(f);
1118		} else {
1119			fprintf(stderr, "Could not run %s\n",
1120			    cmd);
1121		}
1122	}
1123}
1124
1125static void
1126do_nologin(struct passwd *pw)
1127{
1128	FILE *f = NULL;
1129	char buf[1024];
1130
1131#ifdef HAVE_LOGIN_CAP
1132	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1133		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1134		    _PATH_NOLOGIN), "r");
1135#else
1136	if (pw->pw_uid)
1137		f = fopen(_PATH_NOLOGIN, "r");
1138#endif
1139	if (f) {
1140		/* /etc/nologin exists.  Print its contents and exit. */
1141		while (fgets(buf, sizeof(buf), f))
1142			fputs(buf, stderr);
1143		fclose(f);
1144		exit(254);
1145	}
1146}
1147
1148/* Set login name, uid, gid, and groups. */
1149static char **
1150do_setusercontext(Session *s)
1151{
1152	char **env = NULL;
1153	struct passwd *pw = s->pw;
1154#ifdef HAVE_LOGIN_CAP
1155	char buf[256];
1156	char **tmpenv;
1157	u_int envsize;
1158	extern char **environ;
1159
1160	/* Initialize the environment. */
1161	envsize = 100;
1162	env = xmalloc(envsize * sizeof(char *));
1163	env[0] = NULL;
1164
1165	child_set_env(&env, &envsize, "PATH",
1166		      (pw->pw_uid == 0) ?
1167		      _PATH_STDPATH : _PATH_DEFPATH);
1168
1169	snprintf(buf, sizeof buf, "%.200s/%.50s",
1170		 _PATH_MAILDIR, pw->pw_name);
1171	child_set_env(&env, &envsize, "MAIL", buf);
1172
1173	if (getenv("TZ"))
1174		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1175
1176	if (s->term)
1177		child_set_env(&env, &envsize, "TERM", s->term);
1178
1179	/* Save parent environment */
1180	tmpenv = environ;
1181	/* Switch to env */
1182	environ = env;
1183
1184	if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETALL) < 0)
1185		fatal("setusercontext failed: %s", strerror(errno));
1186
1187	/* NOTE: Modified environment now passed to env! */
1188	env = environ;
1189	/* Restore parent environment */
1190	environ = tmpenv;
1191
1192#else   /* !HAVE_LOGIN_CAP */
1193	if (getuid() == 0 || geteuid() == 0) {
1194		if (setlogin(pw->pw_name) < 0)
1195			error("setlogin failed: %s", strerror(errno));
1196		if (setgid(pw->pw_gid) < 0) {
1197			perror("setgid");
1198			exit(1);
1199		}
1200		/* Initialize the group list. */
1201		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1202			perror("initgroups");
1203			exit(1);
1204		}
1205		endgrent();
1206
1207		/* Permanently switch to the desired uid. */
1208		permanently_set_uid(pw);
1209	}
1210	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1211		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1212#endif  /* HAVE_LOGIN_CAP */
1213	return env;
1214}
1215
1216/*
1217 * Performs common processing for the child, such as setting up the
1218 * environment, closing extra file descriptors, setting the user and group
1219 * ids, and executing the command or shell.
1220 */
1221void
1222do_child(Session *s, const char *command)
1223{
1224	extern char **environ;
1225	char **env = NULL;
1226	char *argv[10];
1227	const char *shell, *shell0, *hostname = NULL;
1228	struct passwd *pw = s->pw;
1229	u_int i;
1230	int ttyfd = s->ttyfd;
1231#ifdef HAVE_LOGIN_CAP
1232	int lc_requirehome, lc_nocheckmail;
1233#endif
1234
1235	/* remove hostkey from the child's memory */
1236	destroy_sensitive_data();
1237
1238	/* login(1) is only called if we execute the login shell */
1239	if (options.use_login && command != NULL)
1240		options.use_login = 0;
1241
1242	/*
1243	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1244	 * switch, so we let login(1) to this for us.
1245	 */
1246	if (!options.use_login) {
1247		do_nologin(pw);
1248		env = do_setusercontext(s);
1249	}
1250
1251	/*
1252	 * Get the shell from the password data.  An empty shell field is
1253	 * legal, and means /bin/sh.
1254	 */
1255	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1256#ifdef HAVE_LOGIN_CAP
1257	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1258#endif
1259
1260	env = do_setup_env(env, s, shell);
1261
1262	/* we have to stash the hostname before we close our socket. */
1263	if (options.use_login)
1264		hostname = get_remote_name_or_ip(utmp_len,
1265		    options.verify_reverse_mapping);
1266	/*
1267	 * Close the connection descriptors; note that this is the child, and
1268	 * the server will still have the socket open, and it is important
1269	 * that we do not shutdown it.  Note that the descriptors cannot be
1270	 * closed before building the environment, as we call
1271	 * get_remote_ipaddr there.
1272	 */
1273	if (packet_get_connection_in() == packet_get_connection_out())
1274		close(packet_get_connection_in());
1275	else {
1276		close(packet_get_connection_in());
1277		close(packet_get_connection_out());
1278	}
1279	/*
1280	 * Close all descriptors related to channels.  They will still remain
1281	 * open in the parent.
1282	 */
1283	/* XXX better use close-on-exec? -markus */
1284	channel_close_all();
1285
1286	/*
1287	 * Close any extra file descriptors.  Note that there may still be
1288	 * descriptors left by system functions.  They will be closed later.
1289	 */
1290	endpwent();
1291
1292#ifdef HAVE_LOGIN_CAP
1293	lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1294	lc_nocheckmail = login_getcapbool(lc, "nocheckmail", 0);
1295	login_close(lc);
1296#endif
1297
1298	/*
1299	 * Close any extra open file descriptors so that we don\'t have them
1300	 * hanging around in clients.  Note that we want to do this after
1301	 * initgroups, because at least on Solaris 2.3 it leaves file
1302	 * descriptors open.
1303	 */
1304	for (i = 3; i < getdtablesize(); i++)
1305		close(i);
1306
1307	/*
1308	 * Must take new environment into use so that .ssh/rc,
1309	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1310	 */
1311	environ = env;
1312
1313#ifdef AFS
1314	/* Try to get AFS tokens for the local cell. */
1315	if (k_hasafs()) {
1316		char cell[64];
1317
1318		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1319			krb_afslog(cell, 0);
1320
1321		krb_afslog(0, 0);
1322	}
1323#endif /* AFS */
1324
1325	/* Change current directory to the user\'s home directory. */
1326	if (chdir(pw->pw_dir) < 0) {
1327		fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1328		    pw->pw_dir, strerror(errno));
1329#ifdef HAVE_LOGIN_CAP
1330		if (lc_requirehome)
1331			exit(1);
1332#endif
1333	}
1334
1335	if (!options.use_login)
1336		do_rc_files(s, shell);
1337
1338	/* restore SIGPIPE for child */
1339	signal(SIGPIPE,  SIG_DFL);
1340
1341	if (options.use_login) {
1342		/* Launch login(1). */
1343
1344		execl("/usr/bin/login", "login", "-h", hostname,
1345		    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1346
1347		/* Login couldn't be executed, die. */
1348
1349		perror("login");
1350		exit(1);
1351	}
1352
1353	/* Get the last component of the shell name. */
1354	if ((shell0 = strrchr(shell, '/')) != NULL)
1355		shell0++;
1356	else
1357		shell0 = shell;
1358
1359	/*
1360	 * If we have no command, execute the shell.  In this case, the shell
1361	 * name to be passed in argv[0] is preceded by '-' to indicate that
1362	 * this is a login shell.
1363	 */
1364	if (!command) {
1365		char argv0[256];
1366
1367		/* Start the shell.  Set initial character to '-'. */
1368		argv0[0] = '-';
1369
1370		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1371		    >= sizeof(argv0) - 1) {
1372			errno = EINVAL;
1373			perror(shell);
1374			exit(1);
1375		}
1376
1377		/*
1378		 * Check for mail if we have a tty and it was enabled
1379		 * in server options.
1380		 */
1381		if (ttyfd != -1 && options.check_mail
1382#ifdef HAVE_LOGIN_CAP
1383		    && !lc_nocheckmail
1384#endif
1385		   ) {
1386			char *mailbox;
1387			struct stat mailstat;
1388
1389			mailbox = getenv("MAIL");
1390			if (mailbox != NULL) {
1391				if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
1392					;
1393				else if (mailstat.st_mtime < mailstat.st_atime)
1394					printf("You have mail.\n");
1395				else
1396					printf("You have new mail.\n");
1397			}
1398		}
1399
1400		/* Execute the shell. */
1401		argv[0] = argv0;
1402		argv[1] = NULL;
1403		execve(shell, argv, env);
1404
1405		/* Executing the shell failed. */
1406		perror(shell);
1407		exit(1);
1408	}
1409	/*
1410	 * Execute the command using the user's shell.  This uses the -c
1411	 * option to execute the command.
1412	 */
1413	argv[0] = (char *) shell0;
1414	argv[1] = "-c";
1415	argv[2] = (char *) command;
1416	argv[3] = NULL;
1417	execve(shell, argv, env);
1418	perror(shell);
1419	exit(1);
1420}
1421
1422Session *
1423session_new(void)
1424{
1425	int i;
1426	static int did_init = 0;
1427	if (!did_init) {
1428		debug("session_new: init");
1429		for (i = 0; i < MAX_SESSIONS; i++) {
1430			sessions[i].used = 0;
1431		}
1432		did_init = 1;
1433	}
1434	for (i = 0; i < MAX_SESSIONS; i++) {
1435		Session *s = &sessions[i];
1436		if (! s->used) {
1437			memset(s, 0, sizeof(*s));
1438			s->chanid = -1;
1439			s->ptyfd = -1;
1440			s->ttyfd = -1;
1441			s->used = 1;
1442			s->self = i;
1443			debug("session_new: session %d", i);
1444			return s;
1445		}
1446	}
1447	return NULL;
1448}
1449
1450static void
1451session_dump(void)
1452{
1453	int i;
1454	for (i = 0; i < MAX_SESSIONS; i++) {
1455		Session *s = &sessions[i];
1456		debug("dump: used %d session %d %p channel %d pid %d",
1457		    s->used,
1458		    s->self,
1459		    s,
1460		    s->chanid,
1461		    s->pid);
1462	}
1463}
1464
1465int
1466session_open(Authctxt *authctxt, int chanid)
1467{
1468	Session *s = session_new();
1469	debug("session_open: channel %d", chanid);
1470	if (s == NULL) {
1471		error("no more sessions");
1472		return 0;
1473	}
1474	s->authctxt = authctxt;
1475	s->pw = authctxt->pw;
1476	if (s->pw == NULL)
1477		fatal("no user for session %d", s->self);
1478	debug("session_open: session %d: link with channel %d", s->self, chanid);
1479	s->chanid = chanid;
1480	return 1;
1481}
1482
1483static Session *
1484session_by_channel(int id)
1485{
1486	int i;
1487	for (i = 0; i < MAX_SESSIONS; i++) {
1488		Session *s = &sessions[i];
1489		if (s->used && s->chanid == id) {
1490			debug("session_by_channel: session %d channel %d", i, id);
1491			return s;
1492		}
1493	}
1494	debug("session_by_channel: unknown channel %d", id);
1495	session_dump();
1496	return NULL;
1497}
1498
1499static Session *
1500session_by_pid(pid_t pid)
1501{
1502	int i;
1503	debug("session_by_pid: pid %d", pid);
1504	for (i = 0; i < MAX_SESSIONS; i++) {
1505		Session *s = &sessions[i];
1506		if (s->used && s->pid == pid)
1507			return s;
1508	}
1509	error("session_by_pid: unknown pid %d", pid);
1510	session_dump();
1511	return NULL;
1512}
1513
1514static int
1515session_window_change_req(Session *s)
1516{
1517	s->col = packet_get_int();
1518	s->row = packet_get_int();
1519	s->xpixel = packet_get_int();
1520	s->ypixel = packet_get_int();
1521	packet_check_eom();
1522	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1523	return 1;
1524}
1525
1526static int
1527session_pty_req(Session *s)
1528{
1529	u_int len;
1530	int n_bytes;
1531
1532	if (no_pty_flag) {
1533		debug("Allocating a pty not permitted for this authentication.");
1534		return 0;
1535	}
1536	if (s->ttyfd != -1) {
1537		packet_disconnect("Protocol error: you already have a pty.");
1538		return 0;
1539	}
1540
1541	s->term = packet_get_string(&len);
1542
1543	if (compat20) {
1544		s->col = packet_get_int();
1545		s->row = packet_get_int();
1546	} else {
1547		s->row = packet_get_int();
1548		s->col = packet_get_int();
1549	}
1550	s->xpixel = packet_get_int();
1551	s->ypixel = packet_get_int();
1552
1553	if (strcmp(s->term, "") == 0) {
1554		xfree(s->term);
1555		s->term = NULL;
1556	}
1557
1558	/* Allocate a pty and open it. */
1559	debug("Allocating pty.");
1560	if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1561		if (s->term)
1562			xfree(s->term);
1563		s->term = NULL;
1564		s->ptyfd = -1;
1565		s->ttyfd = -1;
1566		error("session_pty_req: session %d alloc failed", s->self);
1567		return 0;
1568	}
1569	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1570
1571	/* for SSH1 the tty modes length is not given */
1572	if (!compat20)
1573		n_bytes = packet_remaining();
1574	tty_parse_modes(s->ttyfd, &n_bytes);
1575
1576	/*
1577	 * Add a cleanup function to clear the utmp entry and record logout
1578	 * time in case we call fatal() (e.g., the connection gets closed).
1579	 */
1580	fatal_add_cleanup(session_pty_cleanup, (void *)s);
1581	pty_setowner(s->pw, s->tty);
1582
1583	/* Set window size from the packet. */
1584	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1585
1586	packet_check_eom();
1587	session_proctitle(s);
1588	return 1;
1589}
1590
1591static int
1592session_subsystem_req(Session *s)
1593{
1594	struct stat st;
1595	u_int len;
1596	int success = 0;
1597	char *cmd, *subsys = packet_get_string(&len);
1598	int i;
1599
1600	packet_check_eom();
1601	log("subsystem request for %.100s", subsys);
1602
1603	for (i = 0; i < options.num_subsystems; i++) {
1604		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1605			cmd = options.subsystem_command[i];
1606			if (stat(cmd, &st) < 0) {
1607				error("subsystem: cannot stat %s: %s", cmd,
1608				    strerror(errno));
1609				break;
1610			}
1611			debug("subsystem: exec() %s", cmd);
1612			s->is_subsystem = 1;
1613			do_exec(s, cmd);
1614			success = 1;
1615			break;
1616		}
1617	}
1618
1619	if (!success)
1620		log("subsystem request for %.100s failed, subsystem not found",
1621		    subsys);
1622
1623	xfree(subsys);
1624	return success;
1625}
1626
1627static int
1628session_x11_req(Session *s)
1629{
1630	int success;
1631
1632	s->single_connection = packet_get_char();
1633	s->auth_proto = packet_get_string(NULL);
1634	s->auth_data = packet_get_string(NULL);
1635	s->screen = packet_get_int();
1636	packet_check_eom();
1637
1638	success = session_setup_x11fwd(s);
1639	if (!success) {
1640		xfree(s->auth_proto);
1641		xfree(s->auth_data);
1642		s->auth_proto = NULL;
1643		s->auth_data = NULL;
1644	}
1645	return success;
1646}
1647
1648static int
1649session_shell_req(Session *s)
1650{
1651	packet_check_eom();
1652	do_exec(s, NULL);
1653	return 1;
1654}
1655
1656static int
1657session_exec_req(Session *s)
1658{
1659	u_int len;
1660	char *command = packet_get_string(&len);
1661	packet_check_eom();
1662	do_exec(s, command);
1663	xfree(command);
1664	return 1;
1665}
1666
1667static int
1668session_auth_agent_req(Session *s)
1669{
1670	static int called = 0;
1671	packet_check_eom();
1672	if (no_agent_forwarding_flag) {
1673		debug("session_auth_agent_req: no_agent_forwarding_flag");
1674		return 0;
1675	}
1676	if (called) {
1677		return 0;
1678	} else {
1679		called = 1;
1680		return auth_input_request_forwarding(s->pw);
1681	}
1682}
1683
1684int
1685session_input_channel_req(Channel *c, const char *rtype)
1686{
1687	int success = 0;
1688	Session *s;
1689
1690	if ((s = session_by_channel(c->self)) == NULL) {
1691		log("session_input_channel_req: no session %d req %.100s",
1692		    c->self, rtype);
1693		return 0;
1694	}
1695	debug("session_input_channel_req: session %d req %s", s->self, rtype);
1696
1697	/*
1698	 * a session is in LARVAL state until a shell, a command
1699	 * or a subsystem is executed
1700	 */
1701	if (c->type == SSH_CHANNEL_LARVAL) {
1702		if (strcmp(rtype, "shell") == 0) {
1703			success = session_shell_req(s);
1704		} else if (strcmp(rtype, "exec") == 0) {
1705			success = session_exec_req(s);
1706		} else if (strcmp(rtype, "pty-req") == 0) {
1707			success =  session_pty_req(s);
1708		} else if (strcmp(rtype, "x11-req") == 0) {
1709			success = session_x11_req(s);
1710		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1711			success = session_auth_agent_req(s);
1712		} else if (strcmp(rtype, "subsystem") == 0) {
1713			success = session_subsystem_req(s);
1714		}
1715	}
1716	if (strcmp(rtype, "window-change") == 0) {
1717		success = session_window_change_req(s);
1718	}
1719	return success;
1720}
1721
1722void
1723session_set_fds(Session *s, int fdin, int fdout, int fderr)
1724{
1725	if (!compat20)
1726		fatal("session_set_fds: called for proto != 2.0");
1727	/*
1728	 * now that have a child and a pipe to the child,
1729	 * we can activate our channel and register the fd's
1730	 */
1731	if (s->chanid == -1)
1732		fatal("no channel for session %d", s->self);
1733	channel_set_fds(s->chanid,
1734	    fdout, fdin, fderr,
1735	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1736	    1,
1737	    CHAN_SES_WINDOW_DEFAULT);
1738}
1739
1740/*
1741 * Function to perform pty cleanup. Also called if we get aborted abnormally
1742 * (e.g., due to a dropped connection).
1743 */
1744static void
1745session_pty_cleanup(void *session)
1746{
1747	Session *s = session;
1748
1749	if (s == NULL) {
1750		error("session_pty_cleanup: no session");
1751		return;
1752	}
1753	if (s->ttyfd == -1)
1754		return;
1755
1756	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1757
1758	/* Record that the user has logged out. */
1759	if (s->pid != 0)
1760		record_logout(s->pid, s->tty);
1761
1762	/* Release the pseudo-tty. */
1763	pty_release(s->tty);
1764
1765	/*
1766	 * Close the server side of the socket pairs.  We must do this after
1767	 * the pty cleanup, so that another process doesn't get this pty
1768	 * while we're still cleaning up.
1769	 */
1770	if (close(s->ptymaster) < 0)
1771		error("close(s->ptymaster): %s", strerror(errno));
1772
1773	/* unlink pty from session */
1774	s->ttyfd = -1;
1775}
1776
1777static void
1778session_exit_message(Session *s, int status)
1779{
1780	Channel *c;
1781
1782	if ((c = channel_lookup(s->chanid)) == NULL)
1783		fatal("session_exit_message: session %d: no channel %d",
1784		    s->self, s->chanid);
1785	debug("session_exit_message: session %d channel %d pid %d",
1786	    s->self, s->chanid, s->pid);
1787
1788	if (WIFEXITED(status)) {
1789		channel_request_start(s->chanid, "exit-status", 0);
1790		packet_put_int(WEXITSTATUS(status));
1791		packet_send();
1792	} else if (WIFSIGNALED(status)) {
1793		channel_request_start(s->chanid, "exit-signal", 0);
1794		packet_put_int(WTERMSIG(status));
1795		packet_put_char(WCOREDUMP(status));
1796		packet_put_cstring("");
1797		packet_put_cstring("");
1798		packet_send();
1799	} else {
1800		/* Some weird exit cause.  Just exit. */
1801		packet_disconnect("wait returned status %04x.", status);
1802	}
1803
1804	/* disconnect channel */
1805	debug("session_exit_message: release channel %d", s->chanid);
1806	channel_cancel_cleanup(s->chanid);
1807	/*
1808	 * emulate a write failure with 'chan_write_failed', nobody will be
1809	 * interested in data we write.
1810	 * Note that we must not call 'chan_read_failed', since there could
1811	 * be some more data waiting in the pipe.
1812	 */
1813	if (c->ostate != CHAN_OUTPUT_CLOSED)
1814		chan_write_failed(c);
1815	s->chanid = -1;
1816}
1817
1818static void
1819session_close(Session *s)
1820{
1821	debug("session_close: session %d pid %d", s->self, s->pid);
1822	if (s->ttyfd != -1) {
1823		fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1824		session_pty_cleanup(s);
1825	}
1826	if (s->term)
1827		xfree(s->term);
1828	if (s->display)
1829		xfree(s->display);
1830	if (s->auth_display)
1831		xfree(s->auth_display);
1832	if (s->auth_data)
1833		xfree(s->auth_data);
1834	if (s->auth_proto)
1835		xfree(s->auth_proto);
1836	s->used = 0;
1837	session_proctitle(s);
1838}
1839
1840void
1841session_close_by_pid(pid_t pid, int status)
1842{
1843	Session *s = session_by_pid(pid);
1844	if (s == NULL) {
1845		debug("session_close_by_pid: no session for pid %d", pid);
1846		return;
1847	}
1848	if (s->chanid != -1)
1849		session_exit_message(s, status);
1850	session_close(s);
1851}
1852
1853/*
1854 * this is called when a channel dies before
1855 * the session 'child' itself dies
1856 */
1857void
1858session_close_by_channel(int id, void *arg)
1859{
1860	Session *s = session_by_channel(id);
1861	if (s == NULL) {
1862		debug("session_close_by_channel: no session for id %d", id);
1863		return;
1864	}
1865	debug("session_close_by_channel: channel %d child %d", id, s->pid);
1866	if (s->pid != 0) {
1867		debug("session_close_by_channel: channel %d: has child", id);
1868		/*
1869		 * delay detach of session, but release pty, since
1870		 * the fd's to the child are already closed
1871		 */
1872		if (s->ttyfd != -1) {
1873			fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1874			session_pty_cleanup(s);
1875		}
1876		return;
1877	}
1878	/* detach by removing callback */
1879	channel_cancel_cleanup(s->chanid);
1880	s->chanid = -1;
1881	session_close(s);
1882}
1883
1884void
1885session_destroy_all(void)
1886{
1887	int i;
1888	for (i = 0; i < MAX_SESSIONS; i++) {
1889		Session *s = &sessions[i];
1890		if (s->used)
1891			session_close(s);
1892	}
1893}
1894
1895static char *
1896session_tty_list(void)
1897{
1898	static char buf[1024];
1899	int i;
1900	buf[0] = '\0';
1901	for (i = 0; i < MAX_SESSIONS; i++) {
1902		Session *s = &sessions[i];
1903		if (s->used && s->ttyfd != -1) {
1904			if (buf[0] != '\0')
1905				strlcat(buf, ",", sizeof buf);
1906			strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1907		}
1908	}
1909	if (buf[0] == '\0')
1910		strlcpy(buf, "notty", sizeof buf);
1911	return buf;
1912}
1913
1914void
1915session_proctitle(Session *s)
1916{
1917	if (s->pw == NULL)
1918		error("no user for session %d", s->self);
1919	else
1920		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1921}
1922
1923int
1924session_setup_x11fwd(Session *s)
1925{
1926	struct stat st;
1927	char display[512], auth_display[512];
1928	char hostname[MAXHOSTNAMELEN];
1929
1930	if (no_x11_forwarding_flag) {
1931		packet_send_debug("X11 forwarding disabled in user configuration file.");
1932		return 0;
1933	}
1934	if (!options.x11_forwarding) {
1935		debug("X11 forwarding disabled in server configuration file.");
1936		return 0;
1937	}
1938	if (!options.xauth_location ||
1939	    (stat(options.xauth_location, &st) == -1)) {
1940		packet_send_debug("No xauth program; cannot forward with spoofing.");
1941		return 0;
1942	}
1943	if (options.use_login) {
1944		packet_send_debug("X11 forwarding disabled; "
1945		    "not compatible with UseLogin=yes.");
1946		return 0;
1947	}
1948	if (s->display != NULL) {
1949		debug("X11 display already set.");
1950		return 0;
1951	}
1952	s->display_number = x11_create_display_inet(options.x11_display_offset,
1953	    options.x11_use_localhost, s->single_connection);
1954	if (s->display_number == -1) {
1955		debug("x11_create_display_inet failed.");
1956		return 0;
1957	}
1958
1959	/* Set up a suitable value for the DISPLAY variable. */
1960	if (gethostname(hostname, sizeof(hostname)) < 0)
1961		fatal("gethostname: %.100s", strerror(errno));
1962	/*
1963	 * auth_display must be used as the displayname when the
1964	 * authorization entry is added with xauth(1).  This will be
1965	 * different than the DISPLAY string for localhost displays.
1966	 */
1967	if (options.x11_use_localhost) {
1968		snprintf(display, sizeof display, "localhost:%d.%d",
1969		    s->display_number, s->screen);
1970		snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1971		    s->display_number, s->screen);
1972		s->display = xstrdup(display);
1973		s->auth_display = xstrdup(auth_display);
1974	} else {
1975		snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1976		    s->display_number, s->screen);
1977		s->display = xstrdup(display);
1978		s->auth_display = xstrdup(display);
1979	}
1980
1981	return 1;
1982}
1983
1984static void
1985do_authenticated2(Authctxt *authctxt)
1986{
1987	server_loop2(authctxt);
1988}
1989