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