xref: /freebsd/crypto/openssh/session.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
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.180 2004/07/28 09:40:29 markus Exp $");
37 RCSID("$FreeBSD$");
38 
39 #include "ssh.h"
40 #include "ssh1.h"
41 #include "ssh2.h"
42 #include "xmalloc.h"
43 #include "sshpty.h"
44 #include "packet.h"
45 #include "buffer.h"
46 #include "match.h"
47 #include "uidswap.h"
48 #include "compat.h"
49 #include "channels.h"
50 #include "bufaux.h"
51 #include "auth.h"
52 #include "auth-options.h"
53 #include "pathnames.h"
54 #include "log.h"
55 #include "servconf.h"
56 #include "sshlogin.h"
57 #include "serverloop.h"
58 #include "canohost.h"
59 #include "session.h"
60 #include "monitor_wrap.h"
61 
62 #if defined(KRB5) && defined(USE_AFS)
63 #include <kafs.h>
64 #endif
65 
66 #ifdef GSSAPI
67 #include "ssh-gss.h"
68 #endif
69 
70 /* func */
71 
72 Session *session_new(void);
73 void	session_set_fds(Session *, int, int, int);
74 void	session_pty_cleanup(Session *);
75 void	session_proctitle(Session *);
76 int	session_setup_x11fwd(Session *);
77 void	do_exec_pty(Session *, const char *);
78 void	do_exec_no_pty(Session *, const char *);
79 void	do_exec(Session *, const char *);
80 void	do_login(Session *, const char *);
81 #ifdef LOGIN_NEEDS_UTMPX
82 static void	do_pre_login(Session *s);
83 #endif
84 void	do_child(Session *, const char *);
85 void	do_motd(void);
86 int	check_quietlogin(Session *, const char *);
87 
88 static void do_authenticated1(Authctxt *);
89 static void do_authenticated2(Authctxt *);
90 
91 static int session_pty_req(Session *);
92 
93 /* import */
94 extern ServerOptions options;
95 extern char *__progname;
96 extern int log_stderr;
97 extern int debug_flag;
98 extern u_int utmp_len;
99 extern int startup_pipe;
100 extern void destroy_sensitive_data(void);
101 extern Buffer loginmsg;
102 
103 /* original command from peer. */
104 const char *original_command = NULL;
105 
106 /* data */
107 #define MAX_SESSIONS 10
108 Session	sessions[MAX_SESSIONS];
109 
110 #ifdef HAVE_LOGIN_CAP
111 login_cap_t *lc;
112 #endif
113 
114 static int is_child = 0;
115 
116 /* Name and directory of socket for authentication agent forwarding. */
117 static char *auth_sock_name = NULL;
118 static char *auth_sock_dir = NULL;
119 
120 /* removes the agent forwarding socket */
121 
122 static void
123 auth_sock_cleanup_proc(struct passwd *pw)
124 {
125 	if (auth_sock_name != NULL) {
126 		temporarily_use_uid(pw);
127 		unlink(auth_sock_name);
128 		rmdir(auth_sock_dir);
129 		auth_sock_name = NULL;
130 		restore_uid();
131 	}
132 }
133 
134 static int
135 auth_input_request_forwarding(struct passwd * pw)
136 {
137 	Channel *nc;
138 	int sock;
139 	struct sockaddr_un sunaddr;
140 
141 	if (auth_sock_name != NULL) {
142 		error("authentication forwarding requested twice.");
143 		return 0;
144 	}
145 
146 	/* Temporarily drop privileged uid for mkdir/bind. */
147 	temporarily_use_uid(pw);
148 
149 	/* Allocate a buffer for the socket name, and format the name. */
150 	auth_sock_name = xmalloc(MAXPATHLEN);
151 	auth_sock_dir = xmalloc(MAXPATHLEN);
152 	strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
153 
154 	/* Create private directory for socket */
155 	if (mkdtemp(auth_sock_dir) == NULL) {
156 		packet_send_debug("Agent forwarding disabled: "
157 		    "mkdtemp() failed: %.100s", strerror(errno));
158 		restore_uid();
159 		xfree(auth_sock_name);
160 		xfree(auth_sock_dir);
161 		auth_sock_name = NULL;
162 		auth_sock_dir = NULL;
163 		return 0;
164 	}
165 	snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
166 		 auth_sock_dir, (long) getpid());
167 
168 	/* Create the socket. */
169 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
170 	if (sock < 0)
171 		packet_disconnect("socket: %.100s", strerror(errno));
172 
173 	/* Bind it to the name. */
174 	memset(&sunaddr, 0, sizeof(sunaddr));
175 	sunaddr.sun_family = AF_UNIX;
176 	strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
177 
178 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
179 		packet_disconnect("bind: %.100s", strerror(errno));
180 
181 	/* Restore the privileged uid. */
182 	restore_uid();
183 
184 	/* Start listening on the socket. */
185 	if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
186 		packet_disconnect("listen: %.100s", strerror(errno));
187 
188 	/* Allocate a channel for the authentication agent socket. */
189 	nc = channel_new("auth socket",
190 	    SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
191 	    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
192 	    0, "auth socket", 1);
193 	strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
194 	return 1;
195 }
196 
197 static void
198 display_loginmsg(void)
199 {
200         if (buffer_len(&loginmsg) > 0) {
201                 buffer_append(&loginmsg, "\0", 1);
202                 printf("%s", (char *)buffer_ptr(&loginmsg));
203                 buffer_clear(&loginmsg);
204         }
205 }
206 
207 void
208 do_authenticated(Authctxt *authctxt)
209 {
210 	setproctitle("%s", authctxt->pw->pw_name);
211 
212 	/*
213 	 * Cancel the alarm we set to limit the time taken for
214 	 * authentication.
215 	 */
216 	alarm(0);
217 	if (startup_pipe != -1) {
218 		close(startup_pipe);
219 		startup_pipe = -1;
220 	}
221 	/* setup the channel layer */
222 	if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
223 		channel_permit_all_opens();
224 
225 	if (compat20)
226 		do_authenticated2(authctxt);
227 	else
228 		do_authenticated1(authctxt);
229 
230 	do_cleanup(authctxt);
231 }
232 
233 /*
234  * Prepares for an interactive session.  This is called after the user has
235  * been successfully authenticated.  During this message exchange, pseudo
236  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
237  * are requested, etc.
238  */
239 static void
240 do_authenticated1(Authctxt *authctxt)
241 {
242 	Session *s;
243 	char *command;
244 	int success, type, screen_flag;
245 	int enable_compression_after_reply = 0;
246 	u_int proto_len, data_len, dlen, compression_level = 0;
247 
248 	s = session_new();
249 	s->authctxt = authctxt;
250 	s->pw = authctxt->pw;
251 
252 	/*
253 	 * We stay in this loop until the client requests to execute a shell
254 	 * or a command.
255 	 */
256 	for (;;) {
257 		success = 0;
258 
259 		/* Get a packet from the client. */
260 		type = packet_read();
261 
262 		/* Process the packet. */
263 		switch (type) {
264 		case SSH_CMSG_REQUEST_COMPRESSION:
265 			compression_level = packet_get_int();
266 			packet_check_eom();
267 			if (compression_level < 1 || compression_level > 9) {
268 				packet_send_debug("Received invalid compression level %d.",
269 				    compression_level);
270 				break;
271 			}
272 			if (!options.compression) {
273 				debug2("compression disabled");
274 				break;
275 			}
276 			/* Enable compression after we have responded with SUCCESS. */
277 			enable_compression_after_reply = 1;
278 			success = 1;
279 			break;
280 
281 		case SSH_CMSG_REQUEST_PTY:
282 			success = session_pty_req(s);
283 			break;
284 
285 		case SSH_CMSG_X11_REQUEST_FORWARDING:
286 			s->auth_proto = packet_get_string(&proto_len);
287 			s->auth_data = packet_get_string(&data_len);
288 
289 			screen_flag = packet_get_protocol_flags() &
290 			    SSH_PROTOFLAG_SCREEN_NUMBER;
291 			debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
292 
293 			if (packet_remaining() == 4) {
294 				if (!screen_flag)
295 					debug2("Buggy client: "
296 					    "X11 screen flag missing");
297 				s->screen = packet_get_int();
298 			} else {
299 				s->screen = 0;
300 			}
301 			packet_check_eom();
302 			success = session_setup_x11fwd(s);
303 			if (!success) {
304 				xfree(s->auth_proto);
305 				xfree(s->auth_data);
306 				s->auth_proto = NULL;
307 				s->auth_data = NULL;
308 			}
309 			break;
310 
311 		case SSH_CMSG_AGENT_REQUEST_FORWARDING:
312 			if (no_agent_forwarding_flag || compat13) {
313 				debug("Authentication agent forwarding not permitted for this authentication.");
314 				break;
315 			}
316 			debug("Received authentication agent forwarding request.");
317 			success = auth_input_request_forwarding(s->pw);
318 			break;
319 
320 		case SSH_CMSG_PORT_FORWARD_REQUEST:
321 			if (no_port_forwarding_flag) {
322 				debug("Port forwarding not permitted for this authentication.");
323 				break;
324 			}
325 			if (!options.allow_tcp_forwarding) {
326 				debug("Port forwarding not permitted.");
327 				break;
328 			}
329 			debug("Received TCP/IP port forwarding request.");
330 			channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
331 			success = 1;
332 			break;
333 
334 		case SSH_CMSG_MAX_PACKET_SIZE:
335 			if (packet_set_maxsize(packet_get_int()) > 0)
336 				success = 1;
337 			break;
338 
339 		case SSH_CMSG_EXEC_SHELL:
340 		case SSH_CMSG_EXEC_CMD:
341 			if (type == SSH_CMSG_EXEC_CMD) {
342 				command = packet_get_string(&dlen);
343 				debug("Exec command '%.500s'", command);
344 				do_exec(s, command);
345 				xfree(command);
346 			} else {
347 				do_exec(s, NULL);
348 			}
349 			packet_check_eom();
350 			session_close(s);
351 			return;
352 
353 		default:
354 			/*
355 			 * Any unknown messages in this phase are ignored,
356 			 * and a failure message is returned.
357 			 */
358 			logit("Unknown packet type received after authentication: %d", type);
359 		}
360 		packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
361 		packet_send();
362 		packet_write_wait();
363 
364 		/* Enable compression now that we have replied if appropriate. */
365 		if (enable_compression_after_reply) {
366 			enable_compression_after_reply = 0;
367 			packet_start_compression(compression_level);
368 		}
369 	}
370 }
371 
372 /*
373  * This is called to fork and execute a command when we have no tty.  This
374  * will call do_child from the child, and server_loop from the parent after
375  * setting up file descriptors and such.
376  */
377 void
378 do_exec_no_pty(Session *s, const char *command)
379 {
380 	pid_t pid;
381 
382 #ifdef USE_PIPES
383 	int pin[2], pout[2], perr[2];
384 	/* Allocate pipes for communicating with the program. */
385 	if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
386 		packet_disconnect("Could not create pipes: %.100s",
387 				  strerror(errno));
388 #else /* USE_PIPES */
389 	int inout[2], err[2];
390 	/* Uses socket pairs to communicate with the program. */
391 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
392 	    socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
393 		packet_disconnect("Could not create socket pairs: %.100s",
394 				  strerror(errno));
395 #endif /* USE_PIPES */
396 	if (s == NULL)
397 		fatal("do_exec_no_pty: no session");
398 
399 	session_proctitle(s);
400 
401 #if defined(USE_PAM)
402 	if (options.use_pam && !use_privsep)
403 		do_pam_setcred(1);
404 #endif /* USE_PAM */
405 
406 	/* Fork the child. */
407 	if ((pid = fork()) == 0) {
408 		is_child = 1;
409 
410 		/* Child.  Reinitialize the log since the pid has changed. */
411 		log_init(__progname, options.log_level, options.log_facility, log_stderr);
412 
413 		/*
414 		 * Create a new session and process group since the 4.4BSD
415 		 * setlogin() affects the entire process group.
416 		 */
417 		if (setsid() < 0)
418 			error("setsid failed: %.100s", strerror(errno));
419 
420 #ifdef USE_PIPES
421 		/*
422 		 * Redirect stdin.  We close the parent side of the socket
423 		 * pair, and make the child side the standard input.
424 		 */
425 		close(pin[1]);
426 		if (dup2(pin[0], 0) < 0)
427 			perror("dup2 stdin");
428 		close(pin[0]);
429 
430 		/* Redirect stdout. */
431 		close(pout[0]);
432 		if (dup2(pout[1], 1) < 0)
433 			perror("dup2 stdout");
434 		close(pout[1]);
435 
436 		/* Redirect stderr. */
437 		close(perr[0]);
438 		if (dup2(perr[1], 2) < 0)
439 			perror("dup2 stderr");
440 		close(perr[1]);
441 #else /* USE_PIPES */
442 		/*
443 		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
444 		 * use the same socket, as some programs (particularly rdist)
445 		 * seem to depend on it.
446 		 */
447 		close(inout[1]);
448 		close(err[1]);
449 		if (dup2(inout[0], 0) < 0)	/* stdin */
450 			perror("dup2 stdin");
451 		if (dup2(inout[0], 1) < 0)	/* stdout.  Note: same socket as stdin. */
452 			perror("dup2 stdout");
453 		if (dup2(err[0], 2) < 0)	/* stderr */
454 			perror("dup2 stderr");
455 #endif /* USE_PIPES */
456 
457 #ifdef _UNICOS
458 		cray_init_job(s->pw); /* set up cray jid and tmpdir */
459 #endif
460 
461 		/* Do processing for the child (exec command etc). */
462 		do_child(s, command);
463 		/* NOTREACHED */
464 	}
465 #ifdef _UNICOS
466 	signal(WJSIGNAL, cray_job_termination_handler);
467 #endif /* _UNICOS */
468 #ifdef HAVE_CYGWIN
469 	if (is_winnt)
470 		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
471 #endif
472 	if (pid < 0)
473 		packet_disconnect("fork failed: %.100s", strerror(errno));
474 	s->pid = pid;
475 	/* Set interactive/non-interactive mode. */
476 	packet_set_interactive(s->display != NULL);
477 #ifdef USE_PIPES
478 	/* We are the parent.  Close the child sides of the pipes. */
479 	close(pin[0]);
480 	close(pout[1]);
481 	close(perr[1]);
482 
483 	if (compat20) {
484 		if (s->is_subsystem) {
485 			close(perr[0]);
486 			perr[0] = -1;
487 		}
488 		session_set_fds(s, pin[1], pout[0], perr[0]);
489 	} else {
490 		/* Enter the interactive session. */
491 		server_loop(pid, pin[1], pout[0], perr[0]);
492 		/* server_loop has closed pin[1], pout[0], and perr[0]. */
493 	}
494 #else /* USE_PIPES */
495 	/* We are the parent.  Close the child sides of the socket pairs. */
496 	close(inout[0]);
497 	close(err[0]);
498 
499 	/*
500 	 * Clear loginmsg, since it's the child's responsibility to display
501 	 * it to the user, otherwise multiple sessions may accumulate
502 	 * multiple copies of the login messages.
503 	 */
504 	buffer_clear(&loginmsg);
505 
506 	/*
507 	 * Enter the interactive session.  Note: server_loop must be able to
508 	 * handle the case that fdin and fdout are the same.
509 	 */
510 	if (compat20) {
511 		session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
512 	} else {
513 		server_loop(pid, inout[1], inout[1], err[1]);
514 		/* server_loop has closed inout[1] and err[1]. */
515 	}
516 #endif /* USE_PIPES */
517 }
518 
519 /*
520  * This is called to fork and execute a command when we have a tty.  This
521  * will call do_child from the child, and server_loop from the parent after
522  * setting up file descriptors, controlling tty, updating wtmp, utmp,
523  * lastlog, and other such operations.
524  */
525 void
526 do_exec_pty(Session *s, const char *command)
527 {
528 	int fdout, ptyfd, ttyfd, ptymaster;
529 	pid_t pid;
530 
531 	if (s == NULL)
532 		fatal("do_exec_pty: no session");
533 	ptyfd = s->ptyfd;
534 	ttyfd = s->ttyfd;
535 
536 #if defined(USE_PAM)
537 	if (options.use_pam) {
538 		do_pam_set_tty(s->tty);
539 		if (!use_privsep)
540 			do_pam_setcred(1);
541 	}
542 #endif
543 
544 	/* Fork the child. */
545 	if ((pid = fork()) == 0) {
546 		is_child = 1;
547 
548 		/* Child.  Reinitialize the log because the pid has changed. */
549 		log_init(__progname, options.log_level, options.log_facility, log_stderr);
550 		/* Close the master side of the pseudo tty. */
551 		close(ptyfd);
552 
553 		/* Make the pseudo tty our controlling tty. */
554 		pty_make_controlling_tty(&ttyfd, s->tty);
555 
556 		/* Redirect stdin/stdout/stderr from the pseudo tty. */
557 		if (dup2(ttyfd, 0) < 0)
558 			error("dup2 stdin: %s", strerror(errno));
559 		if (dup2(ttyfd, 1) < 0)
560 			error("dup2 stdout: %s", strerror(errno));
561 		if (dup2(ttyfd, 2) < 0)
562 			error("dup2 stderr: %s", strerror(errno));
563 
564 		/* Close the extra descriptor for the pseudo tty. */
565 		close(ttyfd);
566 
567 		/* record login, etc. similar to login(1) */
568 #ifndef HAVE_OSF_SIA
569 		if (!(options.use_login && command == NULL)) {
570 #ifdef _UNICOS
571 			cray_init_job(s->pw); /* set up cray jid and tmpdir */
572 #endif /* _UNICOS */
573 			do_login(s, command);
574 		}
575 # ifdef LOGIN_NEEDS_UTMPX
576 		else
577 			do_pre_login(s);
578 # endif
579 #endif
580 
581 		/* Do common processing for the child, such as execing the command. */
582 		do_child(s, command);
583 		/* NOTREACHED */
584 	}
585 #ifdef _UNICOS
586 	signal(WJSIGNAL, cray_job_termination_handler);
587 #endif /* _UNICOS */
588 #ifdef HAVE_CYGWIN
589 	if (is_winnt)
590 		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
591 #endif
592 	if (pid < 0)
593 		packet_disconnect("fork failed: %.100s", strerror(errno));
594 	s->pid = pid;
595 
596 	/* Parent.  Close the slave side of the pseudo tty. */
597 	close(ttyfd);
598 
599 	/*
600 	 * Create another descriptor of the pty master side for use as the
601 	 * standard input.  We could use the original descriptor, but this
602 	 * simplifies code in server_loop.  The descriptor is bidirectional.
603 	 */
604 	fdout = dup(ptyfd);
605 	if (fdout < 0)
606 		packet_disconnect("dup #1 failed: %.100s", strerror(errno));
607 
608 	/* we keep a reference to the pty master */
609 	ptymaster = dup(ptyfd);
610 	if (ptymaster < 0)
611 		packet_disconnect("dup #2 failed: %.100s", strerror(errno));
612 	s->ptymaster = ptymaster;
613 
614 	/* Enter interactive session. */
615 	packet_set_interactive(1);
616 	if (compat20) {
617 		session_set_fds(s, ptyfd, fdout, -1);
618 	} else {
619 		server_loop(pid, ptyfd, fdout, -1);
620 		/* server_loop _has_ closed ptyfd and fdout. */
621 	}
622 }
623 
624 #ifdef LOGIN_NEEDS_UTMPX
625 static void
626 do_pre_login(Session *s)
627 {
628 	socklen_t fromlen;
629 	struct sockaddr_storage from;
630 	pid_t pid = getpid();
631 
632 	/*
633 	 * Get IP address of client. If the connection is not a socket, let
634 	 * the address be 0.0.0.0.
635 	 */
636 	memset(&from, 0, sizeof(from));
637 	fromlen = sizeof(from);
638 	if (packet_connection_is_on_socket()) {
639 		if (getpeername(packet_get_connection_in(),
640 		    (struct sockaddr *) & from, &fromlen) < 0) {
641 			debug("getpeername: %.100s", strerror(errno));
642 			cleanup_exit(255);
643 		}
644 	}
645 
646 	record_utmp_only(pid, s->tty, s->pw->pw_name,
647 	    get_remote_name_or_ip(utmp_len, options.use_dns),
648 	    (struct sockaddr *)&from, fromlen);
649 }
650 #endif
651 
652 /*
653  * This is called to fork and execute a command.  If another command is
654  * to be forced, execute that instead.
655  */
656 void
657 do_exec(Session *s, const char *command)
658 {
659 	if (forced_command) {
660 		original_command = command;
661 		command = forced_command;
662 		debug("Forced command '%.900s'", command);
663 	}
664 
665 #ifdef GSSAPI
666 	if (options.gss_authentication) {
667 		temporarily_use_uid(s->pw);
668 		ssh_gssapi_storecreds();
669 		restore_uid();
670 	}
671 #endif
672 
673 	if (s->ttyfd != -1)
674 		do_exec_pty(s, command);
675 	else
676 		do_exec_no_pty(s, command);
677 
678 	original_command = NULL;
679 
680 	/*
681 	 * Clear loginmsg: it's the child's responsibility to display
682 	 * it to the user, otherwise multiple sessions may accumulate
683 	 * multiple copies of the login messages.
684 	 */
685 	buffer_clear(&loginmsg);
686 }
687 
688 /* administrative, login(1)-like work */
689 void
690 do_login(Session *s, const char *command)
691 {
692 	socklen_t fromlen;
693 	struct sockaddr_storage from;
694 	struct passwd * pw = s->pw;
695 	pid_t pid = getpid();
696 
697 	/*
698 	 * Get IP address of client. If the connection is not a socket, let
699 	 * the address be 0.0.0.0.
700 	 */
701 	memset(&from, 0, sizeof(from));
702 	fromlen = sizeof(from);
703 	if (packet_connection_is_on_socket()) {
704 		if (getpeername(packet_get_connection_in(),
705 		    (struct sockaddr *) & from, &fromlen) < 0) {
706 			debug("getpeername: %.100s", strerror(errno));
707 			cleanup_exit(255);
708 		}
709 	}
710 
711 	/* Record that there was a login on that tty from the remote host. */
712 	if (!use_privsep)
713 		record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
714 		    get_remote_name_or_ip(utmp_len,
715 		    options.use_dns),
716 		    (struct sockaddr *)&from, fromlen);
717 
718 #ifdef USE_PAM
719 	/*
720 	 * If password change is needed, do it now.
721 	 * This needs to occur before the ~/.hushlogin check.
722 	 */
723 	if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
724 		display_loginmsg();
725 		do_pam_chauthtok();
726 		s->authctxt->force_pwchange = 0;
727 		/* XXX - signal [net] parent to enable forwardings */
728 	}
729 #endif
730 
731 	if (check_quietlogin(s, command))
732 		return;
733 
734 	display_loginmsg();
735 
736 	do_motd();
737 }
738 
739 /*
740  * Display the message of the day.
741  */
742 void
743 do_motd(void)
744 {
745 	FILE *f;
746 	char buf[256];
747 #ifdef HAVE_LOGIN_CAP
748 	const char *fname;
749 #endif
750 
751 #ifdef HAVE_LOGIN_CAP
752 	fname = login_getcapstr(lc, "copyright", NULL, NULL);
753 	if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
754 		while (fgets(buf, sizeof(buf), f) != NULL)
755 			fputs(buf, stdout);
756 			fclose(f);
757 	} else
758 #endif /* HAVE_LOGIN_CAP */
759 		(void)printf("%s\n\t%s %s\n",
760 	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
761 	"The Regents of the University of California. ",
762 	"All rights reserved.");
763 
764 	(void)printf("\n");
765 
766 	if (options.print_motd) {
767 #ifdef HAVE_LOGIN_CAP
768 		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
769 		    "/etc/motd"), "r");
770 #else
771 		f = fopen("/etc/motd", "r");
772 #endif
773 		if (f) {
774 			while (fgets(buf, sizeof(buf), f))
775 				fputs(buf, stdout);
776 			fclose(f);
777 		}
778 	}
779 }
780 
781 
782 /*
783  * Check for quiet login, either .hushlogin or command given.
784  */
785 int
786 check_quietlogin(Session *s, const char *command)
787 {
788 	char buf[256];
789 	struct passwd *pw = s->pw;
790 	struct stat st;
791 
792 	/* Return 1 if .hushlogin exists or a command given. */
793 	if (command != NULL)
794 		return 1;
795 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
796 #ifdef HAVE_LOGIN_CAP
797 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
798 		return 1;
799 #else
800 	if (stat(buf, &st) >= 0)
801 		return 1;
802 #endif
803 	return 0;
804 }
805 
806 /*
807  * Sets the value of the given variable in the environment.  If the variable
808  * already exists, its value is overriden.
809  */
810 void
811 child_set_env(char ***envp, u_int *envsizep, const char *name,
812 	const char *value)
813 {
814 	char **env;
815 	u_int envsize;
816 	u_int i, namelen;
817 
818 	/*
819 	 * If we're passed an uninitialized list, allocate a single null
820 	 * entry before continuing.
821 	 */
822 	if (*envp == NULL && *envsizep == 0) {
823 		*envp = xmalloc(sizeof(char *));
824 		*envp[0] = NULL;
825 		*envsizep = 1;
826 	}
827 
828 	/*
829 	 * Find the slot where the value should be stored.  If the variable
830 	 * already exists, we reuse the slot; otherwise we append a new slot
831 	 * at the end of the array, expanding if necessary.
832 	 */
833 	env = *envp;
834 	namelen = strlen(name);
835 	for (i = 0; env[i]; i++)
836 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
837 			break;
838 	if (env[i]) {
839 		/* Reuse the slot. */
840 		xfree(env[i]);
841 	} else {
842 		/* New variable.  Expand if necessary. */
843 		envsize = *envsizep;
844 		if (i >= envsize - 1) {
845 			if (envsize >= 1000)
846 				fatal("child_set_env: too many env vars");
847 			envsize += 50;
848 			env = (*envp) = xrealloc(env, envsize * sizeof(char *));
849 			*envsizep = envsize;
850 		}
851 		/* Need to set the NULL pointer at end of array beyond the new slot. */
852 		env[i + 1] = NULL;
853 	}
854 
855 	/* Allocate space and format the variable in the appropriate slot. */
856 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
857 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
858 }
859 
860 /*
861  * Reads environment variables from the given file and adds/overrides them
862  * into the environment.  If the file does not exist, this does nothing.
863  * Otherwise, it must consist of empty lines, comments (line starts with '#')
864  * and assignments of the form name=value.  No other forms are allowed.
865  */
866 static void
867 read_environment_file(char ***env, u_int *envsize,
868 	const char *filename)
869 {
870 	FILE *f;
871 	char buf[4096];
872 	char *cp, *value;
873 	u_int lineno = 0;
874 
875 	f = fopen(filename, "r");
876 	if (!f)
877 		return;
878 
879 	while (fgets(buf, sizeof(buf), f)) {
880 		if (++lineno > 1000)
881 			fatal("Too many lines in environment file %s", filename);
882 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
883 			;
884 		if (!*cp || *cp == '#' || *cp == '\n')
885 			continue;
886 		if (strchr(cp, '\n'))
887 			*strchr(cp, '\n') = '\0';
888 		value = strchr(cp, '=');
889 		if (value == NULL) {
890 			fprintf(stderr, "Bad line %u in %.100s\n", lineno,
891 			    filename);
892 			continue;
893 		}
894 		/*
895 		 * Replace the equals sign by nul, and advance value to
896 		 * the value string.
897 		 */
898 		*value = '\0';
899 		value++;
900 		child_set_env(env, envsize, cp, value);
901 	}
902 	fclose(f);
903 }
904 
905 #ifdef HAVE_ETC_DEFAULT_LOGIN
906 /*
907  * Return named variable from specified environment, or NULL if not present.
908  */
909 static char *
910 child_get_env(char **env, const char *name)
911 {
912 	int i;
913 	size_t len;
914 
915 	len = strlen(name);
916 	for (i=0; env[i] != NULL; i++)
917 		if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
918 			return(env[i] + len + 1);
919 	return NULL;
920 }
921 
922 /*
923  * Read /etc/default/login.
924  * We pick up the PATH (or SUPATH for root) and UMASK.
925  */
926 static void
927 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
928 {
929 	char **tmpenv = NULL, *var;
930 	u_int i, tmpenvsize = 0;
931 	u_long mask;
932 
933 	/*
934 	 * We don't want to copy the whole file to the child's environment,
935 	 * so we use a temporary environment and copy the variables we're
936 	 * interested in.
937 	 */
938 	read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
939 
940 	if (tmpenv == NULL)
941 		return;
942 
943 	if (uid == 0)
944 		var = child_get_env(tmpenv, "SUPATH");
945 	else
946 		var = child_get_env(tmpenv, "PATH");
947 	if (var != NULL)
948 		child_set_env(env, envsize, "PATH", var);
949 
950 	if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
951 		if (sscanf(var, "%5lo", &mask) == 1)
952 			umask((mode_t)mask);
953 
954 	for (i = 0; tmpenv[i] != NULL; i++)
955 		xfree(tmpenv[i]);
956 	xfree(tmpenv);
957 }
958 #endif /* HAVE_ETC_DEFAULT_LOGIN */
959 
960 void copy_environment(char **source, char ***env, u_int *envsize)
961 {
962 	char *var_name, *var_val;
963 	int i;
964 
965 	if (source == NULL)
966 		return;
967 
968 	for(i = 0; source[i] != NULL; i++) {
969 		var_name = xstrdup(source[i]);
970 		if ((var_val = strstr(var_name, "=")) == NULL) {
971 			xfree(var_name);
972 			continue;
973 		}
974 		*var_val++ = '\0';
975 
976 		debug3("Copy environment: %s=%s", var_name, var_val);
977 		child_set_env(env, envsize, var_name, var_val);
978 
979 		xfree(var_name);
980 	}
981 }
982 
983 static char **
984 do_setup_env(Session *s, const char *shell)
985 {
986 	char buf[256];
987 	u_int i, envsize;
988 	char **env, *laddr, *path = NULL;
989 #ifdef HAVE_LOGIN_CAP
990 	extern char **environ;
991 	char **senv, **var;
992 #endif
993 	struct passwd *pw = s->pw;
994 
995 	/* Initialize the environment. */
996 	envsize = 100;
997 	env = xmalloc(envsize * sizeof(char *));
998 	env[0] = NULL;
999 
1000 #ifdef HAVE_CYGWIN
1001 	/*
1002 	 * The Windows environment contains some setting which are
1003 	 * important for a running system. They must not be dropped.
1004 	 */
1005 	copy_environment(environ, &env, &envsize);
1006 #endif
1007 
1008 	if (getenv("TZ"))
1009 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1010 
1011 #ifdef GSSAPI
1012 	/* Allow any GSSAPI methods that we've used to alter
1013 	 * the childs environment as they see fit
1014 	 */
1015 	ssh_gssapi_do_child(&env, &envsize);
1016 #endif
1017 
1018 	if (!options.use_login) {
1019 		/* Set basic environment. */
1020 		for (i = 0; i < s->num_env; i++)
1021 			child_set_env(&env, &envsize, s->env[i].name,
1022 			    s->env[i].val);
1023 
1024 		child_set_env(&env, &envsize, "USER", pw->pw_name);
1025 		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1026 #ifdef _AIX
1027 		child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1028 #endif
1029 		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1030 		snprintf(buf, sizeof buf, "%.200s/%.50s",
1031 			 _PATH_MAILDIR, pw->pw_name);
1032 		child_set_env(&env, &envsize, "MAIL", buf);
1033 #ifdef HAVE_LOGIN_CAP
1034 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1035 		child_set_env(&env, &envsize, "TERM", "su");
1036 		senv = environ;
1037 		environ = xmalloc(sizeof(char *));
1038 		*environ = NULL;
1039 		(void) setusercontext(lc, pw, pw->pw_uid,
1040 		    LOGIN_SETENV|LOGIN_SETPATH);
1041 		copy_environment(environ, &env, &envsize);
1042 		for (var = environ; *var != NULL; ++var)
1043 			xfree(*var);
1044 		xfree(environ);
1045 		environ = senv;
1046 #else /* HAVE_LOGIN_CAP */
1047 # ifndef HAVE_CYGWIN
1048 		/*
1049 		 * There's no standard path on Windows. The path contains
1050 		 * important components pointing to the system directories,
1051 		 * needed for loading shared libraries. So the path better
1052 		 * remains intact here.
1053 		 */
1054 #  ifdef HAVE_ETC_DEFAULT_LOGIN
1055 		read_etc_default_login(&env, &envsize, pw->pw_uid);
1056 		path = child_get_env(env, "PATH");
1057 #  endif /* HAVE_ETC_DEFAULT_LOGIN */
1058 		if (path == NULL || *path == '\0') {
1059 			child_set_env(&env, &envsize, "PATH",
1060 			    s->pw->pw_uid == 0 ?
1061 				SUPERUSER_PATH : _PATH_STDPATH);
1062 		}
1063 # endif /* HAVE_CYGWIN */
1064 #endif /* HAVE_LOGIN_CAP */
1065 
1066 		/* Normal systems set SHELL by default. */
1067 		child_set_env(&env, &envsize, "SHELL", shell);
1068 	}
1069 
1070 	/* Set custom environment options from RSA authentication. */
1071 	if (!options.use_login) {
1072 		while (custom_environment) {
1073 			struct envstring *ce = custom_environment;
1074 			char *str = ce->s;
1075 
1076 			for (i = 0; str[i] != '=' && str[i]; i++)
1077 				;
1078 			if (str[i] == '=') {
1079 				str[i] = 0;
1080 				child_set_env(&env, &envsize, str, str + i + 1);
1081 			}
1082 			custom_environment = ce->next;
1083 			xfree(ce->s);
1084 			xfree(ce);
1085 		}
1086 	}
1087 
1088 	/* SSH_CLIENT deprecated */
1089 	snprintf(buf, sizeof buf, "%.50s %d %d",
1090 	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1091 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1092 
1093 	laddr = get_local_ipaddr(packet_get_connection_in());
1094 	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1095 	    get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1096 	xfree(laddr);
1097 	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1098 
1099 	if (s->ttyfd != -1)
1100 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1101 	if (s->term)
1102 		child_set_env(&env, &envsize, "TERM", s->term);
1103 	if (s->display)
1104 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1105 	if (original_command)
1106 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1107 		    original_command);
1108 
1109 #ifdef _UNICOS
1110 	if (cray_tmpdir[0] != '\0')
1111 		child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1112 #endif /* _UNICOS */
1113 
1114 #ifdef _AIX
1115 	{
1116 		char *cp;
1117 
1118 		if ((cp = getenv("AUTHSTATE")) != NULL)
1119 			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1120 		if ((cp = getenv("KRB5CCNAME")) != NULL)
1121 			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1122 		read_environment_file(&env, &envsize, "/etc/environment");
1123 	}
1124 #endif
1125 #ifdef KRB5
1126 	if (s->authctxt->krb5_ccname)
1127 		child_set_env(&env, &envsize, "KRB5CCNAME",
1128 		    s->authctxt->krb5_ccname);
1129 #endif
1130 #ifdef USE_PAM
1131 	/*
1132 	 * Pull in any environment variables that may have
1133 	 * been set by PAM.
1134 	 */
1135 	if (options.use_pam) {
1136 		char **p;
1137 
1138 		p = fetch_pam_child_environment();
1139 		copy_environment(p, &env, &envsize);
1140 		free_pam_environment(p);
1141 
1142 		p = fetch_pam_environment();
1143 		copy_environment(p, &env, &envsize);
1144 		free_pam_environment(p);
1145 	}
1146 #endif /* USE_PAM */
1147 
1148 	if (auth_sock_name != NULL)
1149 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1150 		    auth_sock_name);
1151 
1152 	/* read $HOME/.ssh/environment. */
1153 	if (options.permit_user_env && !options.use_login) {
1154 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1155 		    strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1156 		read_environment_file(&env, &envsize, buf);
1157 	}
1158 	if (debug_flag) {
1159 		/* dump the environment */
1160 		fprintf(stderr, "Environment:\n");
1161 		for (i = 0; env[i]; i++)
1162 			fprintf(stderr, "  %.200s\n", env[i]);
1163 	}
1164 	return env;
1165 }
1166 
1167 /*
1168  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1169  * first in this order).
1170  */
1171 static void
1172 do_rc_files(Session *s, const char *shell)
1173 {
1174 	FILE *f = NULL;
1175 	char cmd[1024];
1176 	int do_xauth;
1177 	struct stat st;
1178 
1179 	do_xauth =
1180 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1181 
1182 	/* ignore _PATH_SSH_USER_RC for subsystems */
1183 	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1184 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1185 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1186 		if (debug_flag)
1187 			fprintf(stderr, "Running %s\n", cmd);
1188 		f = popen(cmd, "w");
1189 		if (f) {
1190 			if (do_xauth)
1191 				fprintf(f, "%s %s\n", s->auth_proto,
1192 				    s->auth_data);
1193 			pclose(f);
1194 		} else
1195 			fprintf(stderr, "Could not run %s\n",
1196 			    _PATH_SSH_USER_RC);
1197 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1198 		if (debug_flag)
1199 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1200 			    _PATH_SSH_SYSTEM_RC);
1201 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1202 		if (f) {
1203 			if (do_xauth)
1204 				fprintf(f, "%s %s\n", s->auth_proto,
1205 				    s->auth_data);
1206 			pclose(f);
1207 		} else
1208 			fprintf(stderr, "Could not run %s\n",
1209 			    _PATH_SSH_SYSTEM_RC);
1210 	} else if (do_xauth && options.xauth_location != NULL) {
1211 		/* Add authority data to .Xauthority if appropriate. */
1212 		if (debug_flag) {
1213 			fprintf(stderr,
1214 			    "Running %.500s remove %.100s\n",
1215 			    options.xauth_location, s->auth_display);
1216 			fprintf(stderr,
1217 			    "%.500s add %.100s %.100s %.100s\n",
1218 			    options.xauth_location, s->auth_display,
1219 			    s->auth_proto, s->auth_data);
1220 		}
1221 		snprintf(cmd, sizeof cmd, "%s -q -",
1222 		    options.xauth_location);
1223 		f = popen(cmd, "w");
1224 		if (f) {
1225 			fprintf(f, "remove %s\n",
1226 			    s->auth_display);
1227 			fprintf(f, "add %s %s %s\n",
1228 			    s->auth_display, s->auth_proto,
1229 			    s->auth_data);
1230 			pclose(f);
1231 		} else {
1232 			fprintf(stderr, "Could not run %s\n",
1233 			    cmd);
1234 		}
1235 	}
1236 }
1237 
1238 static void
1239 do_nologin(struct passwd *pw)
1240 {
1241 	FILE *f = NULL;
1242 	char buf[1024];
1243 
1244 #ifdef HAVE_LOGIN_CAP
1245 	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1246 		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1247 		    _PATH_NOLOGIN), "r");
1248 #else
1249 	if (pw->pw_uid)
1250 		f = fopen(_PATH_NOLOGIN, "r");
1251 #endif
1252 	if (f) {
1253 		/* /etc/nologin exists.  Print its contents and exit. */
1254 		logit("User %.100s not allowed because %s exists",
1255 		    pw->pw_name, _PATH_NOLOGIN);
1256 		while (fgets(buf, sizeof(buf), f))
1257 			fputs(buf, stderr);
1258 		fclose(f);
1259 		fflush(NULL);
1260 		exit(254);
1261 	}
1262 }
1263 
1264 /* Set login name, uid, gid, and groups. */
1265 void
1266 do_setusercontext(struct passwd *pw)
1267 {
1268 #ifndef HAVE_CYGWIN
1269 	if (getuid() == 0 || geteuid() == 0)
1270 #endif /* HAVE_CYGWIN */
1271 	{
1272 
1273 #ifdef HAVE_SETPCRED
1274 		if (setpcred(pw->pw_name, (char **)NULL) == -1)
1275 			fatal("Failed to set process credentials");
1276 #endif /* HAVE_SETPCRED */
1277 #ifdef HAVE_LOGIN_CAP
1278 # ifdef __bsdi__
1279 		setpgid(0, 0);
1280 # endif
1281 # ifdef USE_PAM
1282 		if (options.use_pam) {
1283 			do_pam_session();
1284 			do_pam_setcred(0);
1285 		}
1286 # endif /* USE_PAM */
1287 		if (setusercontext(lc, pw, pw->pw_uid,
1288 		    (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1289 			perror("unable to set user context");
1290 			exit(1);
1291 		}
1292 #else
1293 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1294 		/* Sets login uid for accounting */
1295 		if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1296 			error("setluid: %s", strerror(errno));
1297 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1298 
1299 		if (setlogin(pw->pw_name) < 0)
1300 			error("setlogin failed: %s", strerror(errno));
1301 		if (setgid(pw->pw_gid) < 0) {
1302 			perror("setgid");
1303 			exit(1);
1304 		}
1305 		/* Initialize the group list. */
1306 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1307 			perror("initgroups");
1308 			exit(1);
1309 		}
1310 		endgrent();
1311 # ifdef USE_PAM
1312 		/*
1313 		 * PAM credentials may take the form of supplementary groups.
1314 		 * These will have been wiped by the above initgroups() call.
1315 		 * Reestablish them here.
1316 		 */
1317 		if (options.use_pam) {
1318 			do_pam_session();
1319 			do_pam_setcred(0);
1320 		}
1321 # endif /* USE_PAM */
1322 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1323 		irix_setusercontext(pw);
1324 #  endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1325 # ifdef _AIX
1326 		aix_usrinfo(pw);
1327 # endif /* _AIX */
1328 		/* Permanently switch to the desired uid. */
1329 		permanently_set_uid(pw);
1330 #endif
1331 	}
1332 
1333 #ifdef HAVE_CYGWIN
1334 	if (is_winnt)
1335 #endif
1336 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1337 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1338 }
1339 
1340 static void
1341 do_pwchange(Session *s)
1342 {
1343 	fflush(NULL);
1344 	fprintf(stderr, "WARNING: Your password has expired.\n");
1345 	if (s->ttyfd != -1) {
1346 		fprintf(stderr,
1347 		    "You must change your password now and login again!\n");
1348 		execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1349 		perror("passwd");
1350 	} else {
1351 		fprintf(stderr,
1352 		    "Password change required but no TTY available.\n");
1353 	}
1354 	exit(1);
1355 }
1356 
1357 static void
1358 launch_login(struct passwd *pw, const char *hostname)
1359 {
1360 	/* Launch login(1). */
1361 
1362 	execl(LOGIN_PROGRAM, "login", "-h", hostname,
1363 #ifdef xxxLOGIN_NEEDS_TERM
1364 		    (s->term ? s->term : "unknown"),
1365 #endif /* LOGIN_NEEDS_TERM */
1366 #ifdef LOGIN_NO_ENDOPT
1367 	    "-p", "-f", pw->pw_name, (char *)NULL);
1368 #else
1369 	    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1370 #endif
1371 
1372 	/* Login couldn't be executed, die. */
1373 
1374 	perror("login");
1375 	exit(1);
1376 }
1377 
1378 static void
1379 child_close_fds(void)
1380 {
1381 	int i;
1382 
1383 	if (packet_get_connection_in() == packet_get_connection_out())
1384 		close(packet_get_connection_in());
1385 	else {
1386 		close(packet_get_connection_in());
1387 		close(packet_get_connection_out());
1388 	}
1389 	/*
1390 	 * Close all descriptors related to channels.  They will still remain
1391 	 * open in the parent.
1392 	 */
1393 	/* XXX better use close-on-exec? -markus */
1394 	channel_close_all();
1395 
1396 	/*
1397 	 * Close any extra file descriptors.  Note that there may still be
1398 	 * descriptors left by system functions.  They will be closed later.
1399 	 */
1400 	endpwent();
1401 
1402 	/*
1403 	 * Close any extra open file descriptors so that we don\'t have them
1404 	 * hanging around in clients.  Note that we want to do this after
1405 	 * initgroups, because at least on Solaris 2.3 it leaves file
1406 	 * descriptors open.
1407 	 */
1408 	for (i = 3; i < 64; i++)
1409 		close(i);
1410 }
1411 
1412 /*
1413  * Performs common processing for the child, such as setting up the
1414  * environment, closing extra file descriptors, setting the user and group
1415  * ids, and executing the command or shell.
1416  */
1417 void
1418 do_child(Session *s, const char *command)
1419 {
1420 	extern char **environ;
1421 	char **env;
1422 	char *argv[10];
1423 	const char *shell, *shell0, *hostname = NULL;
1424 	struct passwd *pw = s->pw;
1425 #ifdef HAVE_LOGIN_CAP
1426 	int lc_requirehome;
1427 #endif
1428 
1429 	/* remove hostkey from the child's memory */
1430 	destroy_sensitive_data();
1431 
1432 	/* Force a password change */
1433 	if (s->authctxt->force_pwchange) {
1434 		do_setusercontext(pw);
1435 		child_close_fds();
1436 		do_pwchange(s);
1437 		exit(1);
1438 	}
1439 
1440 	/* login(1) is only called if we execute the login shell */
1441 	if (options.use_login && command != NULL)
1442 		options.use_login = 0;
1443 
1444 #ifdef _UNICOS
1445 	cray_setup(pw->pw_uid, pw->pw_name, command);
1446 #endif /* _UNICOS */
1447 
1448 	/*
1449 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1450 	 * switch, so we let login(1) to this for us.
1451 	 */
1452 	if (!options.use_login) {
1453 #ifdef HAVE_OSF_SIA
1454 		session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1455 		if (!check_quietlogin(s, command))
1456 			do_motd();
1457 #else /* HAVE_OSF_SIA */
1458 		do_nologin(pw);
1459 		do_setusercontext(pw);
1460 		/*
1461 		 * PAM session modules in do_setusercontext may have
1462 		 * generated messages, so if this in an interactive
1463 		 * login then display them too.
1464 		 */
1465 		if (command == NULL)
1466 			display_loginmsg();
1467 #endif /* HAVE_OSF_SIA */
1468 	}
1469 
1470 	/*
1471 	 * Get the shell from the password data.  An empty shell field is
1472 	 * legal, and means /bin/sh.
1473 	 */
1474 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1475 
1476 	/*
1477 	 * Make sure $SHELL points to the shell from the password file,
1478 	 * even if shell is overridden from login.conf
1479 	 */
1480 	env = do_setup_env(s, shell);
1481 
1482 #ifdef HAVE_LOGIN_CAP
1483 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1484 #endif
1485 
1486 	/* we have to stash the hostname before we close our socket. */
1487 	if (options.use_login)
1488 		hostname = get_remote_name_or_ip(utmp_len,
1489 		    options.use_dns);
1490 	/*
1491 	 * Close the connection descriptors; note that this is the child, and
1492 	 * the server will still have the socket open, and it is important
1493 	 * that we do not shutdown it.  Note that the descriptors cannot be
1494 	 * closed before building the environment, as we call
1495 	 * get_remote_ipaddr there.
1496 	 */
1497 	child_close_fds();
1498 
1499 	/*
1500 	 * Must take new environment into use so that .ssh/rc,
1501 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1502 	 */
1503 	environ = env;
1504 
1505 #ifdef HAVE_LOGIN_CAP
1506 	lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1507 	login_close(lc);
1508 #endif
1509 #if defined(KRB5) && defined(USE_AFS)
1510 	/*
1511 	 * At this point, we check to see if AFS is active and if we have
1512 	 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1513 	 * if we can (and need to) extend the ticket into an AFS token. If
1514 	 * we don't do this, we run into potential problems if the user's
1515 	 * home directory is in AFS and it's not world-readable.
1516 	 */
1517 
1518 	if (options.kerberos_get_afs_token && k_hasafs() &&
1519 	     (s->authctxt->krb5_ctx != NULL)) {
1520 		char cell[64];
1521 
1522 		debug("Getting AFS token");
1523 
1524 		k_setpag();
1525 
1526 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1527 			krb5_afslog(s->authctxt->krb5_ctx,
1528 			    s->authctxt->krb5_fwd_ccache, cell, NULL);
1529 
1530 		krb5_afslog_home(s->authctxt->krb5_ctx,
1531 		    s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1532 	}
1533 #endif
1534 
1535 	/* Change current directory to the user\'s home directory. */
1536 	if (chdir(pw->pw_dir) < 0) {
1537 		fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1538 		    pw->pw_dir, strerror(errno));
1539 #ifdef HAVE_LOGIN_CAP
1540 		if (lc_requirehome)
1541 			exit(1);
1542 #endif
1543 	}
1544 
1545 	if (!options.use_login)
1546 		do_rc_files(s, shell);
1547 
1548 	/* restore SIGPIPE for child */
1549 	signal(SIGPIPE,  SIG_DFL);
1550 
1551 	if (options.use_login) {
1552 		launch_login(pw, hostname);
1553 		/* NEVERREACHED */
1554 	}
1555 
1556 	/* Get the last component of the shell name. */
1557 	if ((shell0 = strrchr(shell, '/')) != NULL)
1558 		shell0++;
1559 	else
1560 		shell0 = shell;
1561 
1562 	/*
1563 	 * If we have no command, execute the shell.  In this case, the shell
1564 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1565 	 * this is a login shell.
1566 	 */
1567 	if (!command) {
1568 		char argv0[256];
1569 
1570 		/* Start the shell.  Set initial character to '-'. */
1571 		argv0[0] = '-';
1572 
1573 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1574 		    >= sizeof(argv0) - 1) {
1575 			errno = EINVAL;
1576 			perror(shell);
1577 			exit(1);
1578 		}
1579 
1580 		/* Execute the shell. */
1581 		argv[0] = argv0;
1582 		argv[1] = NULL;
1583 		execve(shell, argv, env);
1584 
1585 		/* Executing the shell failed. */
1586 		perror(shell);
1587 		exit(1);
1588 	}
1589 	/*
1590 	 * Execute the command using the user's shell.  This uses the -c
1591 	 * option to execute the command.
1592 	 */
1593 	argv[0] = (char *) shell0;
1594 	argv[1] = "-c";
1595 	argv[2] = (char *) command;
1596 	argv[3] = NULL;
1597 	execve(shell, argv, env);
1598 	perror(shell);
1599 	exit(1);
1600 }
1601 
1602 Session *
1603 session_new(void)
1604 {
1605 	int i;
1606 	static int did_init = 0;
1607 	if (!did_init) {
1608 		debug("session_new: init");
1609 		for (i = 0; i < MAX_SESSIONS; i++) {
1610 			sessions[i].used = 0;
1611 		}
1612 		did_init = 1;
1613 	}
1614 	for (i = 0; i < MAX_SESSIONS; i++) {
1615 		Session *s = &sessions[i];
1616 		if (! s->used) {
1617 			memset(s, 0, sizeof(*s));
1618 			s->chanid = -1;
1619 			s->ptyfd = -1;
1620 			s->ttyfd = -1;
1621 			s->used = 1;
1622 			s->self = i;
1623 			debug("session_new: session %d", i);
1624 			return s;
1625 		}
1626 	}
1627 	return NULL;
1628 }
1629 
1630 static void
1631 session_dump(void)
1632 {
1633 	int i;
1634 	for (i = 0; i < MAX_SESSIONS; i++) {
1635 		Session *s = &sessions[i];
1636 		debug("dump: used %d session %d %p channel %d pid %ld",
1637 		    s->used,
1638 		    s->self,
1639 		    s,
1640 		    s->chanid,
1641 		    (long)s->pid);
1642 	}
1643 }
1644 
1645 int
1646 session_open(Authctxt *authctxt, int chanid)
1647 {
1648 	Session *s = session_new();
1649 	debug("session_open: channel %d", chanid);
1650 	if (s == NULL) {
1651 		error("no more sessions");
1652 		return 0;
1653 	}
1654 	s->authctxt = authctxt;
1655 	s->pw = authctxt->pw;
1656 	if (s->pw == NULL || !authctxt->valid)
1657 		fatal("no user for session %d", s->self);
1658 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1659 	s->chanid = chanid;
1660 	return 1;
1661 }
1662 
1663 Session *
1664 session_by_tty(char *tty)
1665 {
1666 	int i;
1667 	for (i = 0; i < MAX_SESSIONS; i++) {
1668 		Session *s = &sessions[i];
1669 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1670 			debug("session_by_tty: session %d tty %s", i, tty);
1671 			return s;
1672 		}
1673 	}
1674 	debug("session_by_tty: unknown tty %.100s", tty);
1675 	session_dump();
1676 	return NULL;
1677 }
1678 
1679 static Session *
1680 session_by_channel(int id)
1681 {
1682 	int i;
1683 	for (i = 0; i < MAX_SESSIONS; i++) {
1684 		Session *s = &sessions[i];
1685 		if (s->used && s->chanid == id) {
1686 			debug("session_by_channel: session %d channel %d", i, id);
1687 			return s;
1688 		}
1689 	}
1690 	debug("session_by_channel: unknown channel %d", id);
1691 	session_dump();
1692 	return NULL;
1693 }
1694 
1695 static Session *
1696 session_by_pid(pid_t pid)
1697 {
1698 	int i;
1699 	debug("session_by_pid: pid %ld", (long)pid);
1700 	for (i = 0; i < MAX_SESSIONS; i++) {
1701 		Session *s = &sessions[i];
1702 		if (s->used && s->pid == pid)
1703 			return s;
1704 	}
1705 	error("session_by_pid: unknown pid %ld", (long)pid);
1706 	session_dump();
1707 	return NULL;
1708 }
1709 
1710 static int
1711 session_window_change_req(Session *s)
1712 {
1713 	s->col = packet_get_int();
1714 	s->row = packet_get_int();
1715 	s->xpixel = packet_get_int();
1716 	s->ypixel = packet_get_int();
1717 	packet_check_eom();
1718 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1719 	return 1;
1720 }
1721 
1722 static int
1723 session_pty_req(Session *s)
1724 {
1725 	u_int len;
1726 	int n_bytes;
1727 
1728 	if (no_pty_flag) {
1729 		debug("Allocating a pty not permitted for this authentication.");
1730 		return 0;
1731 	}
1732 	if (s->ttyfd != -1) {
1733 		packet_disconnect("Protocol error: you already have a pty.");
1734 		return 0;
1735 	}
1736 
1737 	s->term = packet_get_string(&len);
1738 
1739 	if (compat20) {
1740 		s->col = packet_get_int();
1741 		s->row = packet_get_int();
1742 	} else {
1743 		s->row = packet_get_int();
1744 		s->col = packet_get_int();
1745 	}
1746 	s->xpixel = packet_get_int();
1747 	s->ypixel = packet_get_int();
1748 
1749 	if (strcmp(s->term, "") == 0) {
1750 		xfree(s->term);
1751 		s->term = NULL;
1752 	}
1753 
1754 	/* Allocate a pty and open it. */
1755 	debug("Allocating pty.");
1756 	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1757 		if (s->term)
1758 			xfree(s->term);
1759 		s->term = NULL;
1760 		s->ptyfd = -1;
1761 		s->ttyfd = -1;
1762 		error("session_pty_req: session %d alloc failed", s->self);
1763 		return 0;
1764 	}
1765 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1766 
1767 	/* for SSH1 the tty modes length is not given */
1768 	if (!compat20)
1769 		n_bytes = packet_remaining();
1770 	tty_parse_modes(s->ttyfd, &n_bytes);
1771 
1772 	if (!use_privsep)
1773 		pty_setowner(s->pw, s->tty);
1774 
1775 	/* Set window size from the packet. */
1776 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1777 
1778 	packet_check_eom();
1779 	session_proctitle(s);
1780 	return 1;
1781 }
1782 
1783 static int
1784 session_subsystem_req(Session *s)
1785 {
1786 	struct stat st;
1787 	u_int len;
1788 	int success = 0;
1789 	char *cmd, *subsys = packet_get_string(&len);
1790 	int i;
1791 
1792 	packet_check_eom();
1793 	logit("subsystem request for %.100s", subsys);
1794 
1795 	for (i = 0; i < options.num_subsystems; i++) {
1796 		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1797 			cmd = options.subsystem_command[i];
1798 			if (stat(cmd, &st) < 0) {
1799 				error("subsystem: cannot stat %s: %s", cmd,
1800 				    strerror(errno));
1801 				break;
1802 			}
1803 			debug("subsystem: exec() %s", cmd);
1804 			s->is_subsystem = 1;
1805 			do_exec(s, cmd);
1806 			success = 1;
1807 			break;
1808 		}
1809 	}
1810 
1811 	if (!success)
1812 		logit("subsystem request for %.100s failed, subsystem not found",
1813 		    subsys);
1814 
1815 	xfree(subsys);
1816 	return success;
1817 }
1818 
1819 static int
1820 session_x11_req(Session *s)
1821 {
1822 	int success;
1823 
1824 	s->single_connection = packet_get_char();
1825 	s->auth_proto = packet_get_string(NULL);
1826 	s->auth_data = packet_get_string(NULL);
1827 	s->screen = packet_get_int();
1828 	packet_check_eom();
1829 
1830 	success = session_setup_x11fwd(s);
1831 	if (!success) {
1832 		xfree(s->auth_proto);
1833 		xfree(s->auth_data);
1834 		s->auth_proto = NULL;
1835 		s->auth_data = NULL;
1836 	}
1837 	return success;
1838 }
1839 
1840 static int
1841 session_shell_req(Session *s)
1842 {
1843 	packet_check_eom();
1844 	do_exec(s, NULL);
1845 	return 1;
1846 }
1847 
1848 static int
1849 session_exec_req(Session *s)
1850 {
1851 	u_int len;
1852 	char *command = packet_get_string(&len);
1853 	packet_check_eom();
1854 	do_exec(s, command);
1855 	xfree(command);
1856 	return 1;
1857 }
1858 
1859 static int
1860 session_break_req(Session *s)
1861 {
1862 
1863 	packet_get_int();	/* ignored */
1864 	packet_check_eom();
1865 
1866 	if (s->ttyfd == -1 ||
1867 	    tcsendbreak(s->ttyfd, 0) < 0)
1868 		return 0;
1869 	return 1;
1870 }
1871 
1872 static int
1873 session_env_req(Session *s)
1874 {
1875 	char *name, *val;
1876 	u_int name_len, val_len, i;
1877 
1878 	name = packet_get_string(&name_len);
1879 	val = packet_get_string(&val_len);
1880 	packet_check_eom();
1881 
1882 	/* Don't set too many environment variables */
1883 	if (s->num_env > 128) {
1884 		debug2("Ignoring env request %s: too many env vars", name);
1885 		goto fail;
1886 	}
1887 
1888 	for (i = 0; i < options.num_accept_env; i++) {
1889 		if (match_pattern(name, options.accept_env[i])) {
1890 			debug2("Setting env %d: %s=%s", s->num_env, name, val);
1891 			s->env = xrealloc(s->env, sizeof(*s->env) *
1892 			    (s->num_env + 1));
1893 			s->env[s->num_env].name = name;
1894 			s->env[s->num_env].val = val;
1895 			s->num_env++;
1896 			return (1);
1897 		}
1898 	}
1899 	debug2("Ignoring env request %s: disallowed name", name);
1900 
1901  fail:
1902 	xfree(name);
1903 	xfree(val);
1904 	return (0);
1905 }
1906 
1907 static int
1908 session_auth_agent_req(Session *s)
1909 {
1910 	static int called = 0;
1911 	packet_check_eom();
1912 	if (no_agent_forwarding_flag) {
1913 		debug("session_auth_agent_req: no_agent_forwarding_flag");
1914 		return 0;
1915 	}
1916 	if (called) {
1917 		return 0;
1918 	} else {
1919 		called = 1;
1920 		return auth_input_request_forwarding(s->pw);
1921 	}
1922 }
1923 
1924 int
1925 session_input_channel_req(Channel *c, const char *rtype)
1926 {
1927 	int success = 0;
1928 	Session *s;
1929 
1930 	if ((s = session_by_channel(c->self)) == NULL) {
1931 		logit("session_input_channel_req: no session %d req %.100s",
1932 		    c->self, rtype);
1933 		return 0;
1934 	}
1935 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
1936 
1937 	/*
1938 	 * a session is in LARVAL state until a shell, a command
1939 	 * or a subsystem is executed
1940 	 */
1941 	if (c->type == SSH_CHANNEL_LARVAL) {
1942 		if (strcmp(rtype, "shell") == 0) {
1943 			success = session_shell_req(s);
1944 		} else if (strcmp(rtype, "exec") == 0) {
1945 			success = session_exec_req(s);
1946 		} else if (strcmp(rtype, "pty-req") == 0) {
1947 			success =  session_pty_req(s);
1948 		} else if (strcmp(rtype, "x11-req") == 0) {
1949 			success = session_x11_req(s);
1950 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1951 			success = session_auth_agent_req(s);
1952 		} else if (strcmp(rtype, "subsystem") == 0) {
1953 			success = session_subsystem_req(s);
1954 		} else if (strcmp(rtype, "env") == 0) {
1955 			success = session_env_req(s);
1956 		}
1957 	}
1958 	if (strcmp(rtype, "window-change") == 0) {
1959 		success = session_window_change_req(s);
1960 	} else if (strcmp(rtype, "break") == 0) {
1961 		success = session_break_req(s);
1962 	}
1963 
1964 	return success;
1965 }
1966 
1967 void
1968 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1969 {
1970 	if (!compat20)
1971 		fatal("session_set_fds: called for proto != 2.0");
1972 	/*
1973 	 * now that have a child and a pipe to the child,
1974 	 * we can activate our channel and register the fd's
1975 	 */
1976 	if (s->chanid == -1)
1977 		fatal("no channel for session %d", s->self);
1978 	channel_set_fds(s->chanid,
1979 	    fdout, fdin, fderr,
1980 	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1981 	    1,
1982 	    CHAN_SES_WINDOW_DEFAULT);
1983 }
1984 
1985 /*
1986  * Function to perform pty cleanup. Also called if we get aborted abnormally
1987  * (e.g., due to a dropped connection).
1988  */
1989 void
1990 session_pty_cleanup2(Session *s)
1991 {
1992 	if (s == NULL) {
1993 		error("session_pty_cleanup: no session");
1994 		return;
1995 	}
1996 	if (s->ttyfd == -1)
1997 		return;
1998 
1999 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2000 
2001 	/* Record that the user has logged out. */
2002 	if (s->pid != 0)
2003 		record_logout(s->pid, s->tty, s->pw->pw_name);
2004 
2005 	/* Release the pseudo-tty. */
2006 	if (getuid() == 0)
2007 		pty_release(s->tty);
2008 
2009 	/*
2010 	 * Close the server side of the socket pairs.  We must do this after
2011 	 * the pty cleanup, so that another process doesn't get this pty
2012 	 * while we're still cleaning up.
2013 	 */
2014 	if (close(s->ptymaster) < 0)
2015 		error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2016 
2017 	/* unlink pty from session */
2018 	s->ttyfd = -1;
2019 }
2020 
2021 void
2022 session_pty_cleanup(Session *s)
2023 {
2024 	PRIVSEP(session_pty_cleanup2(s));
2025 }
2026 
2027 static char *
2028 sig2name(int sig)
2029 {
2030 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2031 	SSH_SIG(ABRT);
2032 	SSH_SIG(ALRM);
2033 	SSH_SIG(FPE);
2034 	SSH_SIG(HUP);
2035 	SSH_SIG(ILL);
2036 	SSH_SIG(INT);
2037 	SSH_SIG(KILL);
2038 	SSH_SIG(PIPE);
2039 	SSH_SIG(QUIT);
2040 	SSH_SIG(SEGV);
2041 	SSH_SIG(TERM);
2042 	SSH_SIG(USR1);
2043 	SSH_SIG(USR2);
2044 #undef	SSH_SIG
2045 	return "SIG@openssh.com";
2046 }
2047 
2048 static void
2049 session_exit_message(Session *s, int status)
2050 {
2051 	Channel *c;
2052 
2053 	if ((c = channel_lookup(s->chanid)) == NULL)
2054 		fatal("session_exit_message: session %d: no channel %d",
2055 		    s->self, s->chanid);
2056 	debug("session_exit_message: session %d channel %d pid %ld",
2057 	    s->self, s->chanid, (long)s->pid);
2058 
2059 	if (WIFEXITED(status)) {
2060 		channel_request_start(s->chanid, "exit-status", 0);
2061 		packet_put_int(WEXITSTATUS(status));
2062 		packet_send();
2063 	} else if (WIFSIGNALED(status)) {
2064 		channel_request_start(s->chanid, "exit-signal", 0);
2065 		packet_put_cstring(sig2name(WTERMSIG(status)));
2066 #ifdef WCOREDUMP
2067 		packet_put_char(WCOREDUMP(status));
2068 #else /* WCOREDUMP */
2069 		packet_put_char(0);
2070 #endif /* WCOREDUMP */
2071 		packet_put_cstring("");
2072 		packet_put_cstring("");
2073 		packet_send();
2074 	} else {
2075 		/* Some weird exit cause.  Just exit. */
2076 		packet_disconnect("wait returned status %04x.", status);
2077 	}
2078 
2079 	/* disconnect channel */
2080 	debug("session_exit_message: release channel %d", s->chanid);
2081 	channel_cancel_cleanup(s->chanid);
2082 	/*
2083 	 * emulate a write failure with 'chan_write_failed', nobody will be
2084 	 * interested in data we write.
2085 	 * Note that we must not call 'chan_read_failed', since there could
2086 	 * be some more data waiting in the pipe.
2087 	 */
2088 	if (c->ostate != CHAN_OUTPUT_CLOSED)
2089 		chan_write_failed(c);
2090 	s->chanid = -1;
2091 }
2092 
2093 void
2094 session_close(Session *s)
2095 {
2096 	int i;
2097 
2098 	debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2099 	if (s->ttyfd != -1)
2100 		session_pty_cleanup(s);
2101 	if (s->term)
2102 		xfree(s->term);
2103 	if (s->display)
2104 		xfree(s->display);
2105 	if (s->auth_display)
2106 		xfree(s->auth_display);
2107 	if (s->auth_data)
2108 		xfree(s->auth_data);
2109 	if (s->auth_proto)
2110 		xfree(s->auth_proto);
2111 	s->used = 0;
2112 	for (i = 0; i < s->num_env; i++) {
2113 		xfree(s->env[i].name);
2114 		xfree(s->env[i].val);
2115 	}
2116 	if (s->env != NULL)
2117 		xfree(s->env);
2118 	session_proctitle(s);
2119 }
2120 
2121 void
2122 session_close_by_pid(pid_t pid, int status)
2123 {
2124 	Session *s = session_by_pid(pid);
2125 	if (s == NULL) {
2126 		debug("session_close_by_pid: no session for pid %ld",
2127 		    (long)pid);
2128 		return;
2129 	}
2130 	if (s->chanid != -1)
2131 		session_exit_message(s, status);
2132 	session_close(s);
2133 }
2134 
2135 /*
2136  * this is called when a channel dies before
2137  * the session 'child' itself dies
2138  */
2139 void
2140 session_close_by_channel(int id, void *arg)
2141 {
2142 	Session *s = session_by_channel(id);
2143 	if (s == NULL) {
2144 		debug("session_close_by_channel: no session for id %d", id);
2145 		return;
2146 	}
2147 	debug("session_close_by_channel: channel %d child %ld",
2148 	    id, (long)s->pid);
2149 	if (s->pid != 0) {
2150 		debug("session_close_by_channel: channel %d: has child", id);
2151 		/*
2152 		 * delay detach of session, but release pty, since
2153 		 * the fd's to the child are already closed
2154 		 */
2155 		if (s->ttyfd != -1)
2156 			session_pty_cleanup(s);
2157 		return;
2158 	}
2159 	/* detach by removing callback */
2160 	channel_cancel_cleanup(s->chanid);
2161 	s->chanid = -1;
2162 	session_close(s);
2163 }
2164 
2165 void
2166 session_destroy_all(void (*closefunc)(Session *))
2167 {
2168 	int i;
2169 	for (i = 0; i < MAX_SESSIONS; i++) {
2170 		Session *s = &sessions[i];
2171 		if (s->used) {
2172 			if (closefunc != NULL)
2173 				closefunc(s);
2174 			else
2175 				session_close(s);
2176 		}
2177 	}
2178 }
2179 
2180 static char *
2181 session_tty_list(void)
2182 {
2183 	static char buf[1024];
2184 	int i;
2185 	char *cp;
2186 
2187 	buf[0] = '\0';
2188 	for (i = 0; i < MAX_SESSIONS; i++) {
2189 		Session *s = &sessions[i];
2190 		if (s->used && s->ttyfd != -1) {
2191 
2192 			if (strncmp(s->tty, "/dev/", 5) != 0) {
2193 				cp = strrchr(s->tty, '/');
2194 				cp = (cp == NULL) ? s->tty : cp + 1;
2195 			} else
2196 				cp = s->tty + 5;
2197 
2198 			if (buf[0] != '\0')
2199 				strlcat(buf, ",", sizeof buf);
2200 			strlcat(buf, cp, sizeof buf);
2201 		}
2202 	}
2203 	if (buf[0] == '\0')
2204 		strlcpy(buf, "notty", sizeof buf);
2205 	return buf;
2206 }
2207 
2208 void
2209 session_proctitle(Session *s)
2210 {
2211 	if (s->pw == NULL)
2212 		error("no user for session %d", s->self);
2213 	else
2214 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2215 }
2216 
2217 int
2218 session_setup_x11fwd(Session *s)
2219 {
2220 	struct stat st;
2221 	char display[512], auth_display[512];
2222 	char hostname[MAXHOSTNAMELEN];
2223 
2224 	if (no_x11_forwarding_flag) {
2225 		packet_send_debug("X11 forwarding disabled in user configuration file.");
2226 		return 0;
2227 	}
2228 	if (!options.x11_forwarding) {
2229 		debug("X11 forwarding disabled in server configuration file.");
2230 		return 0;
2231 	}
2232 	if (!options.xauth_location ||
2233 	    (stat(options.xauth_location, &st) == -1)) {
2234 		packet_send_debug("No xauth program; cannot forward with spoofing.");
2235 		return 0;
2236 	}
2237 	if (options.use_login) {
2238 		packet_send_debug("X11 forwarding disabled; "
2239 		    "not compatible with UseLogin=yes.");
2240 		return 0;
2241 	}
2242 	if (s->display != NULL) {
2243 		debug("X11 display already set.");
2244 		return 0;
2245 	}
2246 	if (x11_create_display_inet(options.x11_display_offset,
2247 	    options.x11_use_localhost, s->single_connection,
2248 	    &s->display_number) == -1) {
2249 		debug("x11_create_display_inet failed.");
2250 		return 0;
2251 	}
2252 
2253 	/* Set up a suitable value for the DISPLAY variable. */
2254 	if (gethostname(hostname, sizeof(hostname)) < 0)
2255 		fatal("gethostname: %.100s", strerror(errno));
2256 	/*
2257 	 * auth_display must be used as the displayname when the
2258 	 * authorization entry is added with xauth(1).  This will be
2259 	 * different than the DISPLAY string for localhost displays.
2260 	 */
2261 	if (options.x11_use_localhost) {
2262 		snprintf(display, sizeof display, "localhost:%u.%u",
2263 		    s->display_number, s->screen);
2264 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2265 		    s->display_number, s->screen);
2266 		s->display = xstrdup(display);
2267 		s->auth_display = xstrdup(auth_display);
2268 	} else {
2269 #ifdef IPADDR_IN_DISPLAY
2270 		struct hostent *he;
2271 		struct in_addr my_addr;
2272 
2273 		he = gethostbyname(hostname);
2274 		if (he == NULL) {
2275 			error("Can't get IP address for X11 DISPLAY.");
2276 			packet_send_debug("Can't get IP address for X11 DISPLAY.");
2277 			return 0;
2278 		}
2279 		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2280 		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2281 		    s->display_number, s->screen);
2282 #else
2283 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2284 		    s->display_number, s->screen);
2285 #endif
2286 		s->display = xstrdup(display);
2287 		s->auth_display = xstrdup(display);
2288 	}
2289 
2290 	return 1;
2291 }
2292 
2293 static void
2294 do_authenticated2(Authctxt *authctxt)
2295 {
2296 	server_loop2(authctxt);
2297 }
2298 
2299 void
2300 do_cleanup(Authctxt *authctxt)
2301 {
2302 	static int called = 0;
2303 
2304 	debug("do_cleanup");
2305 
2306 	/* no cleanup if we're in the child for login shell */
2307 	if (is_child)
2308 		return;
2309 
2310 	/* avoid double cleanup */
2311 	if (called)
2312 		return;
2313 	called = 1;
2314 
2315 	if (authctxt == NULL)
2316 		return;
2317 #ifdef KRB5
2318 	if (options.kerberos_ticket_cleanup &&
2319 	    authctxt->krb5_ctx)
2320 		krb5_cleanup_proc(authctxt);
2321 #endif
2322 
2323 #ifdef GSSAPI
2324 	if (compat20 && options.gss_cleanup_creds)
2325 		ssh_gssapi_cleanup_creds();
2326 #endif
2327 
2328 #ifdef USE_PAM
2329 	if (options.use_pam) {
2330 		sshpam_cleanup();
2331 		sshpam_thread_cleanup();
2332 	}
2333 #endif
2334 
2335 	/* remove agent socket */
2336 	auth_sock_cleanup_proc(authctxt->pw);
2337 
2338 	/*
2339 	 * Cleanup ptys/utmp only if privsep is disabled,
2340 	 * or if running in monitor.
2341 	 */
2342 	if (!use_privsep || mm_is_monitor())
2343 		session_destroy_all(session_pty_cleanup2);
2344 }
2345