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