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