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