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