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