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