xref: /titanic_50/usr/src/cmd/ssh/sshd/session.c (revision adecd3c68045d04dc367d30faf2eb5cac1f45d5a)
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 2006 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], *path_maildir = _PATH_MAILDIR;
1042 	u_int i, envsize, pm_len;
1043 	char **env;
1044 	struct passwd *pw = s->pw;
1045 
1046 	/* Initialize the environment. */
1047 	envsize = 100;
1048 	env = xmalloc(envsize * sizeof(char *));
1049 	env[0] = NULL;
1050 
1051 #ifdef HAVE_CYGWIN
1052 	/*
1053 	 * The Windows environment contains some setting which are
1054 	 * important for a running system. They must not be dropped.
1055 	 */
1056 	copy_environment(environ, &env, &envsize);
1057 #endif
1058 
1059 #ifdef GSSAPI
1060 	/* Allow any GSSAPI methods that we've used to alter
1061 	 * the childs environment as they see fit
1062 	 */
1063 	ssh_gssapi_do_child(xxx_gssctxt, &env,&envsize);
1064 #endif
1065 
1066 	if (!options.use_login) {
1067 		/* Set basic environment. */
1068 		child_set_env(&env, &envsize, "USER", pw->pw_name);
1069 		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1070 		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1071 #ifdef HAVE_LOGIN_CAP
1072 		if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1073 			child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1074 		else
1075 			child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1076 #else /* HAVE_LOGIN_CAP */
1077 # ifndef HAVE_CYGWIN
1078 		/*
1079 		 * There's no standard path on Windows. The path contains
1080 		 * important components pointing to the system directories,
1081 		 * needed for loading shared libraries. So the path better
1082 		 * remains intact here.
1083 		 */
1084 #  ifdef SUPERUSER_PATH
1085 		child_set_env(&env, &envsize, "PATH",
1086 		    s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1087 #  else
1088 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1089 #  endif /* SUPERUSER_PATH */
1090 # endif /* HAVE_CYGWIN */
1091 #endif /* HAVE_LOGIN_CAP */
1092 
1093 		pm_len = strlen(path_maildir);
1094 		if (path_maildir[pm_len - 1] == '/' && pm_len > 1)
1095 			path_maildir[pm_len - 1] = NULL;
1096 		snprintf(buf, sizeof buf, "%.200s/%.50s",
1097 			 path_maildir, pw->pw_name);
1098 		child_set_env(&env, &envsize, "MAIL", buf);
1099 
1100 		/* Normal systems set SHELL by default. */
1101 		child_set_env(&env, &envsize, "SHELL", shell);
1102 
1103 #ifdef HAVE_DEFOPEN
1104 		deflt_do_setup_env(s, shell, &env, &envsize);
1105 #endif /* HAVE_DEFOPEN */
1106 	}
1107 
1108 #define PASS_ENV(x) \
1109 	if (getenv(x)) \
1110 		child_set_env(&env, &envsize, x, getenv(x));
1111 
1112 	if (getenv("TZ"))
1113 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1114 
1115 	if (s->auth_file != NULL)
1116 		child_set_env(&env, &envsize, "XAUTHORITY", s->auth_file);
1117 
1118 	PASS_ENV("LANG")
1119 	PASS_ENV("LC_ALL")
1120 	PASS_ENV("LC_CTYPE")
1121 	PASS_ENV("LC_COLLATE")
1122 	PASS_ENV("LC_CTIME")
1123 	PASS_ENV("LC_NUMERIC")
1124 	PASS_ENV("LC_MONETARY")
1125 	PASS_ENV("LC_MESSAGES")
1126 
1127 #undef PASS_ENV
1128 
1129 	if (s->env != NULL)
1130 		copy_environment(s->env, &env, &envsize);
1131 
1132 	/* Set custom environment options from RSA authentication. */
1133 	if (!options.use_login) {
1134 		while (custom_environment) {
1135 			struct envstring *ce = custom_environment;
1136 			char *str = ce->s;
1137 
1138 			for (i = 0; str[i] != '=' && str[i]; i++)
1139 				;
1140 			if (str[i] == '=') {
1141 				str[i] = 0;
1142 				child_set_env(&env, &envsize, str, str + i + 1);
1143 			}
1144 			custom_environment = ce->next;
1145 			xfree(ce->s);
1146 			xfree(ce);
1147 		}
1148 	}
1149 
1150 	/* SSH_CLIENT deprecated */
1151 	snprintf(buf, sizeof buf, "%.50s %d %d",
1152 	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1153 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1154 
1155 	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1156 	    get_remote_ipaddr(), get_remote_port(),
1157 	    get_local_ipaddr(packet_get_connection_in()), get_local_port());
1158 	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1159 
1160 	if (s->ttyfd != -1)
1161 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1162 	if (s->term)
1163 		child_set_env(&env, &envsize, "TERM", s->term);
1164 	if (s->display)
1165 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1166 	if (original_command)
1167 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1168 		    original_command);
1169 
1170 #ifdef _UNICOS
1171 	if (cray_tmpdir[0] != '\0')
1172 		child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1173 #endif /* _UNICOS */
1174 
1175 #ifdef _AIX
1176 	{
1177 		char *cp;
1178 
1179 		if ((cp = getenv("AUTHSTATE")) != NULL)
1180 			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1181 		if ((cp = getenv("KRB5CCNAME")) != NULL)
1182 			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1183 		read_environment_file(&env, &envsize, "/etc/environment");
1184 	}
1185 #endif
1186 #ifdef KRB4
1187 	if (s->authctxt->krb4_ticket_file)
1188 		child_set_env(&env, &envsize, "KRBTKFILE",
1189 		    s->authctxt->krb4_ticket_file);
1190 #endif
1191 #ifdef KRB5
1192 	if (s->authctxt->krb5_ticket_file)
1193 		child_set_env(&env, &envsize, "KRB5CCNAME",
1194 		    s->authctxt->krb5_ticket_file);
1195 #endif
1196 #ifdef USE_PAM
1197 	/*
1198 	 * Pull in any environment variables that may have
1199 	 * been set by PAM.
1200 	 */
1201 	{
1202 		char **p;
1203 
1204 		p = fetch_pam_environment(s->authctxt);
1205 		copy_environment(p, &env, &envsize);
1206 		free_pam_environment(p);
1207 	}
1208 #endif /* USE_PAM */
1209 
1210 	if (auth_sock_name != NULL)
1211 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1212 		    auth_sock_name);
1213 
1214 	/* read $HOME/.ssh/environment. */
1215 	if (options.permit_user_env && !options.use_login) {
1216 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1217 		    strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1218 		read_environment_file(&env, &envsize, buf);
1219 	}
1220 	if (debug_flag) {
1221 		/* dump the environment */
1222 		fprintf(stderr, gettext("Environment:\n"));
1223 		for (i = 0; env[i]; i++)
1224 			fprintf(stderr, "  %.200s\n", env[i]);
1225 	}
1226 	return env;
1227 }
1228 
1229 /*
1230  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1231  * first in this order).
1232  */
1233 static void
1234 do_rc_files(Session *s, const char *shell)
1235 {
1236 	FILE *f = NULL;
1237 	char cmd[1024];
1238 	int do_xauth;
1239 	struct stat st;
1240 
1241 	do_xauth =
1242 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1243 
1244 	/* ignore _PATH_SSH_USER_RC for subsystems */
1245 	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1246 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1247 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1248 		if (debug_flag)
1249 			fprintf(stderr, "Running %s\n", cmd);
1250 		f = popen(cmd, "w");
1251 		if (f) {
1252 			if (do_xauth)
1253 				fprintf(f, "%s %s\n", s->auth_proto,
1254 				    s->auth_data);
1255 			pclose(f);
1256 		} else
1257 			fprintf(stderr, "Could not run %s\n",
1258 			    _PATH_SSH_USER_RC);
1259 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1260 		if (debug_flag)
1261 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1262 			    _PATH_SSH_SYSTEM_RC);
1263 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1264 		if (f) {
1265 			if (do_xauth)
1266 				fprintf(f, "%s %s\n", s->auth_proto,
1267 				    s->auth_data);
1268 			pclose(f);
1269 		} else
1270 			fprintf(stderr, "Could not run %s\n",
1271 			    _PATH_SSH_SYSTEM_RC);
1272 	} else if (do_xauth && options.xauth_location != NULL) {
1273 		/* Add authority data to .Xauthority if appropriate. */
1274 		if (debug_flag) {
1275 			fprintf(stderr,
1276 			    "Running %.500s add "
1277 			    "%.100s %.100s %.100s\n",
1278 			    options.xauth_location, s->auth_display,
1279 			    s->auth_proto, s->auth_data);
1280 		}
1281 		snprintf(cmd, sizeof cmd, "%s -q -",
1282 		    options.xauth_location);
1283 		f = popen(cmd, "w");
1284 		if (f) {
1285 			fprintf(f, "add %s %s %s\n",
1286 			    s->auth_display, s->auth_proto,
1287 			    s->auth_data);
1288 			pclose(f);
1289 		} else {
1290 			fprintf(stderr, "Could not run %s\n",
1291 			    cmd);
1292 		}
1293 	}
1294 }
1295 
1296 static void
1297 do_nologin(struct passwd *pw)
1298 {
1299 	FILE *f = NULL;
1300 	char buf[1024];
1301 
1302 #ifdef HAVE_LOGIN_CAP
1303 	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1304 		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1305 		    _PATH_NOLOGIN), "r");
1306 #else
1307 	if (pw->pw_uid)
1308 		f = fopen(_PATH_NOLOGIN, "r");
1309 #endif
1310 	if (f) {
1311 		/* /etc/nologin exists.  Print its contents and exit. */
1312 		log("User %.100s not allowed because %s exists",
1313 		    pw->pw_name, _PATH_NOLOGIN);
1314 		while (fgets(buf, sizeof(buf), f))
1315 			fputs(buf, stderr);
1316 		fclose(f);
1317 		exit(254);
1318 	}
1319 }
1320 
1321 /* Set login name, uid, gid, and groups. */
1322 void
1323 do_setusercontext(struct passwd *pw)
1324 {
1325 #ifdef HAVE_CYGWIN
1326 	if (is_winnt) {
1327 #else /* HAVE_CYGWIN */
1328 	if (getuid() == 0 || geteuid() == 0) {
1329 #endif /* HAVE_CYGWIN */
1330 #ifdef HAVE_SETPCRED
1331 		setpcred(pw->pw_name);
1332 #endif /* HAVE_SETPCRED */
1333 #ifdef HAVE_LOGIN_CAP
1334 # ifdef __bsdi__
1335 		setpgid(0, 0);
1336 # endif
1337 		if (setusercontext(lc, pw, pw->pw_uid,
1338 		    (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1339 			perror("unable to set user context");
1340 			exit(1);
1341 		}
1342 #else
1343 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1344 		/* Sets login uid for accounting */
1345 		if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1346 			error("setluid: %s", strerror(errno));
1347 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1348 
1349 		if (setlogin(pw->pw_name) < 0)
1350 			error("setlogin failed: %s", strerror(errno));
1351 		if (setgid(pw->pw_gid) < 0) {
1352 			perror("setgid");
1353 			exit(1);
1354 		}
1355 		/* Initialize the group list. */
1356 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1357 			perror("initgroups");
1358 			exit(1);
1359 		}
1360 		endgrent();
1361 # if 0
1362 # ifdef USE_PAM
1363 		/*
1364 		 * PAM credentials may take the form of supplementary groups.
1365 		 * These will have been wiped by the above initgroups() call.
1366 		 * Reestablish them here.
1367 		 */
1368 		do_pam_setcred(0);
1369 # endif /* USE_PAM */
1370 # endif /* 0 */
1371 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1372 		irix_setusercontext(pw);
1373 #  endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1374 # ifdef _AIX
1375 		aix_usrinfo(pw);
1376 # endif /* _AIX */
1377 		/* Permanently switch to the desired uid. */
1378 		permanently_set_uid(pw);
1379 #endif
1380 	}
1381 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1382 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1383 }
1384 
1385 static void
1386 launch_login(struct passwd *pw, const char *hostname)
1387 {
1388 	/* Launch login(1). */
1389 
1390 	execl(LOGIN_PROGRAM, "login", "-h", hostname,
1391 #ifdef xxxLOGIN_NEEDS_TERM
1392 		    (s->term ? s->term : "unknown"),
1393 #endif /* LOGIN_NEEDS_TERM */
1394 #ifdef LOGIN_NO_ENDOPT
1395 	    "-p", "-f", pw->pw_name, (char *)NULL);
1396 #else
1397 	    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1398 #endif
1399 
1400 	/* Login couldn't be executed, die. */
1401 
1402 	perror("login");
1403 	exit(1);
1404 }
1405 
1406 /*
1407  * Performs common processing for the child, such as setting up the
1408  * environment, closing extra file descriptors, setting the user and group
1409  * ids, and executing the command or shell.
1410  */
1411 void
1412 do_child(Session *s, const char *command)
1413 {
1414 	extern char **environ;
1415 	char **env;
1416 	char *argv[10];
1417 	const char *shell, *shell0, *hostname = NULL;
1418 	struct passwd *pw = s->pw;
1419 
1420 	/* remove hostkey from the child's memory */
1421 	destroy_sensitive_data();
1422 
1423 	/* login(1) is only called if we execute the login shell */
1424 	if (options.use_login && command != NULL)
1425 		options.use_login = 0;
1426 
1427 #ifdef _UNICOS
1428 	cray_setup(pw->pw_uid, pw->pw_name, command);
1429 #endif /* _UNICOS */
1430 
1431 	/*
1432 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1433 	 * switch, so we let login(1) to this for us.
1434 	 */
1435 	if (!options.use_login) {
1436 #ifdef HAVE_OSF_SIA
1437 		session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1438 		if (!check_quietlogin(s, command))
1439 			do_motd();
1440 #else /* HAVE_OSF_SIA */
1441 		do_nologin(pw);
1442 		do_setusercontext(pw);
1443 #endif /* HAVE_OSF_SIA */
1444 	}
1445 
1446 	/*
1447 	 * Get the shell from the password data.  An empty shell field is
1448 	 * legal, and means /bin/sh.
1449 	 */
1450 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1451 #ifdef HAVE_LOGIN_CAP
1452 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1453 #endif
1454 
1455 	env = do_setup_env(s, shell);
1456 
1457 	/* we have to stash the hostname before we close our socket. */
1458 	if (options.use_login)
1459 		hostname = get_remote_name_or_ip(utmp_len,
1460 		    options.verify_reverse_mapping);
1461 	/*
1462 	 * Close the connection descriptors; note that this is the child, and
1463 	 * the server will still have the socket open, and it is important
1464 	 * that we do not shutdown it.  Note that the descriptors cannot be
1465 	 * closed before building the environment, as we call
1466 	 * get_remote_ipaddr there.
1467 	 */
1468 	if (packet_get_connection_in() == packet_get_connection_out())
1469 		close(packet_get_connection_in());
1470 	else {
1471 		close(packet_get_connection_in());
1472 		close(packet_get_connection_out());
1473 	}
1474 	/*
1475 	 * Close all descriptors related to channels.  They will still remain
1476 	 * open in the parent.
1477 	 */
1478 	/* XXX better use close-on-exec? -markus */
1479 	channel_close_all();
1480 
1481 	/*
1482 	 * Close any extra file descriptors.  Note that there may still be
1483 	 * descriptors left by system functions.  They will be closed later.
1484 	 */
1485 	endpwent();
1486 
1487 	/*
1488 	 * Close any extra open file descriptors so that we don\'t have them
1489 	 * hanging around in clients.  Note that we want to do this after
1490 	 * initgroups, because at least on Solaris 2.3 it leaves file
1491 	 * descriptors open.
1492 	 */
1493 	closefrom(STDERR_FILENO + 1);
1494 
1495 	/*
1496 	 * Must take new environment into use so that .ssh/rc,
1497 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1498 	 */
1499 	environ = env;
1500 
1501 #ifdef AFS
1502 	/* Try to get AFS tokens for the local cell. */
1503 	if (k_hasafs()) {
1504 		char cell[64];
1505 
1506 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1507 			krb_afslog(cell, 0);
1508 
1509 		krb_afslog(0, 0);
1510 	}
1511 #endif /* AFS */
1512 
1513 	/* Change current directory to the user\'s home directory. */
1514 	if (chdir(pw->pw_dir) < 0) {
1515 		fprintf(stderr,
1516 		    gettext("Could not chdir to home directory %s: %s\n"),
1517 		    pw->pw_dir, strerror(errno));
1518 #ifdef HAVE_LOGIN_CAP
1519 		if (login_getcapbool(lc, "requirehome", 0))
1520 			exit(1);
1521 #endif
1522 	}
1523 
1524 	if (!options.use_login)
1525 		do_rc_files(s, shell);
1526 
1527 	/* restore SIGPIPE for child */
1528 	signal(SIGPIPE,  SIG_DFL);
1529 
1530 	if (options.use_login) {
1531 		launch_login(pw, hostname);
1532 		/* NEVERREACHED */
1533 	}
1534 
1535 	/* Get the last component of the shell name. */
1536 	if ((shell0 = strrchr(shell, '/')) != NULL)
1537 		shell0++;
1538 	else
1539 		shell0 = shell;
1540 
1541 	/*
1542 	 * If we have no command, execute the shell.  In this case, the shell
1543 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1544 	 * this is a login shell.
1545 	 */
1546 	if (!command) {
1547 		char argv0[256];
1548 
1549 		/* Start the shell.  Set initial character to '-'. */
1550 		argv0[0] = '-';
1551 
1552 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1553 		    >= sizeof(argv0) - 1) {
1554 			errno = EINVAL;
1555 			perror(shell);
1556 			exit(1);
1557 		}
1558 
1559 		/* Execute the shell. */
1560 		argv[0] = argv0;
1561 		argv[1] = NULL;
1562 		execve(shell, argv, env);
1563 
1564 		/* Executing the shell failed. */
1565 		perror(shell);
1566 		exit(1);
1567 	}
1568 	/*
1569 	 * Execute the command using the user's shell.  This uses the -c
1570 	 * option to execute the command.
1571 	 */
1572 	argv[0] = (char *) shell0;
1573 	argv[1] = "-c";
1574 	argv[2] = (char *) command;
1575 	argv[3] = NULL;
1576 	execve(shell, argv, env);
1577 	perror(shell);
1578 	exit(1);
1579 }
1580 
1581 Session *
1582 session_new(void)
1583 {
1584 	int i;
1585 	static int did_init = 0;
1586 	if (!did_init) {
1587 		debug("session_new: init");
1588 		for (i = 0; i < MAX_SESSIONS; i++) {
1589 			sessions[i].used = 0;
1590 		}
1591 		did_init = 1;
1592 	}
1593 	for (i = 0; i < MAX_SESSIONS; i++) {
1594 		Session *s = &sessions[i];
1595 		if (! s->used) {
1596 			memset(s, 0, sizeof(*s));
1597 			s->chanid = -1;
1598 			s->ptyfd = -1;
1599 			s->ttyfd = -1;
1600 			s->used = 1;
1601 			s->self = i;
1602 			s->env = NULL;
1603 			debug("session_new: session %d", i);
1604 			return s;
1605 		}
1606 	}
1607 	return NULL;
1608 }
1609 
1610 static void
1611 session_dump(void)
1612 {
1613 	int i;
1614 	for (i = 0; i < MAX_SESSIONS; i++) {
1615 		Session *s = &sessions[i];
1616 		debug("dump: used %d session %d %p channel %d pid %ld",
1617 		    s->used,
1618 		    s->self,
1619 		    s,
1620 		    s->chanid,
1621 		    (long)s->pid);
1622 	}
1623 }
1624 
1625 int
1626 session_open(Authctxt *authctxt, int chanid)
1627 {
1628 	Session *s = session_new();
1629 	debug("session_open: channel %d", chanid);
1630 	if (s == NULL) {
1631 		error("no more sessions");
1632 		return 0;
1633 	}
1634 	s->authctxt = authctxt;
1635 	s->pw = authctxt->pw;
1636 	if (s->pw == NULL)
1637 		fatal("no user for session %d", s->self);
1638 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1639 	s->chanid = chanid;
1640 	return 1;
1641 }
1642 
1643 #ifndef lint
1644 Session *
1645 session_by_tty(char *tty)
1646 {
1647 	int i;
1648 	for (i = 0; i < MAX_SESSIONS; i++) {
1649 		Session *s = &sessions[i];
1650 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1651 			debug("session_by_tty: session %d tty %s", i, tty);
1652 			return s;
1653 		}
1654 	}
1655 	debug("session_by_tty: unknown tty %.100s", tty);
1656 	session_dump();
1657 	return NULL;
1658 }
1659 #endif /* lint */
1660 
1661 static Session *
1662 session_by_channel(int id)
1663 {
1664 	int i;
1665 	for (i = 0; i < MAX_SESSIONS; i++) {
1666 		Session *s = &sessions[i];
1667 		if (s->used && s->chanid == id) {
1668 			debug("session_by_channel: session %d channel %d", i, id);
1669 			return s;
1670 		}
1671 	}
1672 	debug("session_by_channel: unknown channel %d", id);
1673 	session_dump();
1674 	return NULL;
1675 }
1676 
1677 static Session *
1678 session_by_pid(pid_t pid)
1679 {
1680 	int i;
1681 	debug("session_by_pid: pid %ld", (long)pid);
1682 	for (i = 0; i < MAX_SESSIONS; i++) {
1683 		Session *s = &sessions[i];
1684 		if (s->used && s->pid == pid)
1685 			return s;
1686 	}
1687 	error("session_by_pid: unknown pid %ld", (long)pid);
1688 	session_dump();
1689 	return NULL;
1690 }
1691 
1692 static int
1693 session_window_change_req(Session *s)
1694 {
1695 	s->col = packet_get_int();
1696 	s->row = packet_get_int();
1697 	s->xpixel = packet_get_int();
1698 	s->ypixel = packet_get_int();
1699 	packet_check_eom();
1700 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1701 	return 1;
1702 }
1703 
1704 static int
1705 session_pty_req(Session *s)
1706 {
1707 	u_int len;
1708 	int n_bytes;
1709 
1710 	if (no_pty_flag) {
1711 		debug("Allocating a pty not permitted for this authentication.");
1712 		return 0;
1713 	}
1714 	if (s->ttyfd != -1) {
1715 		packet_disconnect("Protocol error: you already have a pty.");
1716 		return 0;
1717 	}
1718 	/* Get the time and hostname when the user last logged in. */
1719 	if (options.print_lastlog) {
1720 		s->hostname[0] = '\0';
1721 		s->last_login_time = get_last_login_time(s->pw->pw_uid,
1722 		    s->pw->pw_name, s->hostname, sizeof(s->hostname));
1723 
1724 		/*
1725 		 * PAM may update the last login date.
1726 		 *
1727 		 * Ideally PAM would also show the last login date as a
1728 		 * PAM_TEXT_INFO conversation message, and then we could just
1729 		 * always force the use of keyboard-interactive just so we can
1730 		 * pass any such PAM prompts and messages from the account and
1731 		 * session stacks, but skip pam_authenticate() if other userauth
1732 		 * has succeeded and the user's password isn't expired.
1733 		 *
1734 		 * Unfortunately this depends on support for keyboard-
1735 		 * interactive in the client, and support for lastlog messages
1736 		 * in some PAM module.
1737 		 *
1738 		 * As it is Solaris updates the lastlog in PAM, but does
1739 		 * not show the lastlog date in PAM.  If and when this state of
1740 		 * affairs changes this hack can be reconsidered, and, maybe,
1741 		 * removed.
1742 		 *
1743 		 * So we're stuck with a crude hack: get the lastlog
1744 		 * time before calling pam_open_session() and store it
1745 		 * in the Authctxt and then use it here once.  After
1746 		 * that, if the client opens any more pty sessions we'll
1747 		 * show the last lastlog entry since userauth.
1748 		 */
1749 		if (s->authctxt != NULL && s->authctxt->last_login_time > 0) {
1750 			s->last_login_time = s->authctxt->last_login_time;
1751 			(void) strlcpy(s->hostname,
1752 				       s->authctxt->last_login_host,
1753 				       sizeof(s->hostname));
1754 			s->authctxt->last_login_time = 0;
1755 			s->authctxt->last_login_host[0] = '\0';
1756 		}
1757 	}
1758 
1759 	s->term = packet_get_string(&len);
1760 
1761 	if (compat20) {
1762 		s->col = packet_get_int();
1763 		s->row = packet_get_int();
1764 	} else {
1765 		s->row = packet_get_int();
1766 		s->col = packet_get_int();
1767 	}
1768 	s->xpixel = packet_get_int();
1769 	s->ypixel = packet_get_int();
1770 
1771 	if (strcmp(s->term, "") == 0) {
1772 		xfree(s->term);
1773 		s->term = NULL;
1774 	}
1775 
1776 	/* Allocate a pty and open it. */
1777 	debug("Allocating pty.");
1778 	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1779 		if (s->term)
1780 			xfree(s->term);
1781 		s->term = NULL;
1782 		s->ptyfd = -1;
1783 		s->ttyfd = -1;
1784 		error("session_pty_req: session %d alloc failed", s->self);
1785 		return 0;
1786 	}
1787 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1788 
1789 	/* for SSH1 the tty modes length is not given */
1790 	if (!compat20)
1791 		n_bytes = packet_remaining();
1792 	tty_parse_modes(s->ttyfd, &n_bytes);
1793 
1794 	/*
1795 	 * Add a cleanup function to clear the utmp entry and record logout
1796 	 * time in case we call fatal() (e.g., the connection gets closed).
1797 	 */
1798 	fatal_add_cleanup(session_pty_cleanup, (void *)s);
1799 	if (!use_privsep)
1800 		pty_setowner(s->pw, s->tty);
1801 
1802 	/* Set window size from the packet. */
1803 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1804 
1805 	packet_check_eom();
1806 	session_proctitle(s);
1807 	return 1;
1808 }
1809 
1810 static int
1811 session_subsystem_req(Session *s)
1812 {
1813 	struct stat st;
1814 	u_int len;
1815 	int success = 0;
1816 	char *cmd, *subsys = packet_get_string(&len);
1817 	int i;
1818 
1819 	packet_check_eom();
1820 	log("subsystem request for %.100s", subsys);
1821 
1822 	for (i = 0; i < options.num_subsystems; i++) {
1823 		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1824 			cmd = options.subsystem_command[i];
1825 			if (stat(cmd, &st) < 0) {
1826 				error("subsystem: cannot stat %s: %s", cmd,
1827 				    strerror(errno));
1828 				break;
1829 			}
1830 			debug("subsystem: exec() %s", cmd);
1831 			s->is_subsystem = 1;
1832 			do_exec(s, cmd);
1833 			success = 1;
1834 			break;
1835 		}
1836 	}
1837 
1838 	if (!success)
1839 		log("subsystem request for %.100s failed, subsystem not found",
1840 		    subsys);
1841 
1842 	xfree(subsys);
1843 	return success;
1844 }
1845 
1846 /*
1847  * Serve "x11-req" channel request for X11 forwarding for the current session
1848  * channel.
1849  */
1850 static int
1851 session_x11_req(Session *s)
1852 {
1853 	int success;
1854 	char *xauthdir = "/tmp/ssh-xauth-XXXXXX";
1855 
1856 	s->single_connection = packet_get_char();
1857 	s->auth_proto = packet_get_string(NULL);
1858 	s->auth_data = packet_get_string(NULL);
1859 	s->screen = packet_get_int();
1860 	packet_check_eom();
1861 
1862 	success = session_setup_x11fwd(s);
1863 	if (!success) {
1864 		xfree(s->auth_proto);
1865 		xfree(s->auth_data);
1866 		s->auth_proto = NULL;
1867 		s->auth_data = NULL;
1868 	}
1869 
1870 	/*
1871 	 * Create per session X authority file so that different sessions
1872 	 * don't contend for one common file. The reason for this is that
1873 	 * xauth(1) locking doesn't work too well over network filesystems.
1874 	 *
1875 	 * If mkdtemp() fails then s->auth_file remains NULL which means that
1876 	 * we won't set XAUTHORITY variable in child's environment and
1877 	 * xauth(1) will use the default location for the authority file.
1878 	 */
1879 	if (success && mkdtemp(xauthdir) != NULL) {
1880 		s->auth_file = xmalloc(MAXPATHLEN);
1881 		snprintf(s->auth_file, MAXPATHLEN, "%s/xauthfile",
1882 		    xauthdir);
1883 		/*
1884 		 * add a cleanup function to remove the temporary
1885 		 * xauth file in case we call fatal() (e.g., the
1886 		 * connection gets closed).
1887 		 */
1888 		fatal_add_cleanup(session_xauthfile_cleanup, (void *)s);
1889 	} else {
1890 		error("failed to create the temporary authority file, "
1891 		    "will use the default one");
1892 	}
1893 
1894 	return success;
1895 }
1896 
1897 static int
1898 session_shell_req(Session *s)
1899 {
1900 	packet_check_eom();
1901 	do_exec(s, NULL);
1902 	return 1;
1903 }
1904 
1905 static int
1906 session_exec_req(Session *s)
1907 {
1908 	u_int len;
1909 	char *command = packet_get_string(&len);
1910 	packet_check_eom();
1911 	do_exec(s, command);
1912 	xfree(command);
1913 	return 1;
1914 }
1915 
1916 static int
1917 session_auth_agent_req(Session *s)
1918 {
1919 	static int called = 0;
1920 	packet_check_eom();
1921 	if (no_agent_forwarding_flag) {
1922 		debug("session_auth_agent_req: no_agent_forwarding_flag");
1923 		return 0;
1924 	}
1925 	if (called) {
1926 		return 0;
1927 	} else {
1928 		called = 1;
1929 		return auth_input_request_forwarding(s->pw);
1930 	}
1931 }
1932 
1933 static int
1934 session_loc_env_check(char *var, char *val)
1935 {
1936 	char *current;
1937 	int cat, ret;
1938 
1939 	if (strcmp(var, "LANG") == 0)
1940 		cat = LC_ALL;
1941 	else if (strcmp(var, "LC_ALL") == 0)
1942 		cat = LC_ALL;
1943 	else if (strcmp(var, "LC_CTYPE") == 0)
1944 		cat = LC_CTYPE;
1945 	else if (strcmp(var, "LC_COLLATE") == 0)
1946 		cat = LC_COLLATE;
1947 	else if (strcmp(var, "LC_TIME") == 0)
1948 		cat = LC_TIME;
1949 	else if (strcmp(var, "LC_NUMERIC") == 0)
1950 		cat = LC_NUMERIC;
1951 	else if (strcmp(var, "LC_MONETARY") == 0)
1952 		cat = LC_MONETARY;
1953 	else if (strcmp(var, "LC_MESSAGES") == 0)
1954 		cat = LC_MESSAGES;
1955 
1956 	if ((current = setlocale(cat, NULL)) != NULL)
1957 		current = xstrdup(current);
1958 
1959 	ret = (setlocale(cat, val) != NULL);
1960 	(void) setlocale(cat, current);
1961 	return (ret);
1962 }
1963 
1964 static int
1965 session_env_req(Session *s)
1966 {
1967 	Channel *c;
1968 	char *var, *val, *e;
1969 	char **p;
1970 	size_t len;
1971 	int ret = 0;
1972 
1973 	/* Get var/val from the rest of this packet */
1974 	var = packet_get_string(NULL);
1975 	val = packet_get_string(NULL);
1976 
1977 	/*
1978 	 * We'll need the channel ID for the packet_send_debug messages,
1979 	 * so get it now.
1980 	 */
1981 	if ((c = channel_lookup(s->chanid)) == NULL)
1982 		goto done;	/* shouldn't happen! */
1983 
1984 	debug2("Received request for environment variable %s=%s", var, val);
1985 
1986 	/* For now allow only LANG and LC_* */
1987 	if (strcmp(var, "LANG") != 0 && strncmp(var, "LC_", 3) != 0) {
1988 		debug2("Rejecting request for environment variable %s", var);
1989 		goto done;
1990 	}
1991 
1992 	if (!session_loc_env_check(var, val)) {
1993 		packet_send_debug(gettext("Missing locale support for %s=%s"),
1994 			var, val);
1995 		goto done;
1996 	}
1997 
1998 	packet_send_debug(gettext("Channel %d set: %s=%s"), c->remote_id,
1999 		var, val);
2000 
2001 	/*
2002 	 * Always append new environment variables without regard to old
2003 	 * ones being overriden.  The way these are actually added to
2004 	 * the environment of the session process later settings
2005 	 * override earlier ones; see copy_environment().
2006 	 */
2007 	if (s->env == NULL) {
2008 		char **env;
2009 
2010 		env = xmalloc(sizeof (char **) * 2);
2011 		memset(env, 0, sizeof (char **) * 2);
2012 
2013 		s->env = env;
2014 		p = env;
2015 	} else {
2016 		for (p = s->env; *p != NULL ; p++);
2017 
2018 		s->env = xrealloc(s->env, (p - s->env + 2) * sizeof (char **));
2019 
2020 		for (p = s->env; *p != NULL ; p++);
2021 	}
2022 
2023 	len = snprintf(NULL, 0, "%s=%s", var, val);
2024 	e = xmalloc(len + 1);
2025 	(void) snprintf(e, len + 1, "%s=%s", var, val);
2026 
2027 	(*p++) = e;
2028 	*p = NULL;
2029 
2030 	ret = 1;
2031 
2032 done:
2033 	xfree(var);
2034 	xfree(val);
2035 
2036 	return (ret);
2037 }
2038 
2039 static void
2040 session_free_env(char ***envp)
2041 {
2042 	char **env, **p;
2043 
2044 	if (envp == NULL || *envp == NULL)
2045 		return;
2046 
2047 	env = *envp;
2048 
2049 	*envp = NULL;
2050 
2051 	for (p = env; *p != NULL; p++)
2052 		xfree(*p);
2053 
2054 	xfree(env);
2055 }
2056 
2057 int
2058 session_input_channel_req(Channel *c, const char *rtype)
2059 {
2060 	int success = 0;
2061 	Session *s;
2062 
2063 	if ((s = session_by_channel(c->self)) == NULL) {
2064 		log("session_input_channel_req: no session %d req %.100s",
2065 		    c->self, rtype);
2066 		return 0;
2067 	}
2068 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
2069 
2070 	/*
2071 	 * a session is in LARVAL state until a shell, a command
2072 	 * or a subsystem is executed
2073 	 */
2074 	if (c->type == SSH_CHANNEL_LARVAL) {
2075 		if (strcmp(rtype, "shell") == 0) {
2076 			success = session_shell_req(s);
2077 		} else if (strcmp(rtype, "exec") == 0) {
2078 			success = session_exec_req(s);
2079 		} else if (strcmp(rtype, "pty-req") == 0) {
2080 			success =  session_pty_req(s);
2081 		} else if (strcmp(rtype, "x11-req") == 0) {
2082 			success = session_x11_req(s);
2083 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2084 			success = session_auth_agent_req(s);
2085 		} else if (strcmp(rtype, "subsystem") == 0) {
2086 			success = session_subsystem_req(s);
2087 		} else if (strcmp(rtype, "env") == 0) {
2088 			success = session_env_req(s);
2089 		}
2090 	}
2091 	if (strcmp(rtype, "window-change") == 0) {
2092 		success = session_window_change_req(s);
2093 	}
2094 	return success;
2095 }
2096 
2097 void
2098 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2099 {
2100 	if (!compat20)
2101 		fatal("session_set_fds: called for proto != 2.0");
2102 	/*
2103 	 * now that have a child and a pipe to the child,
2104 	 * we can activate our channel and register the fd's
2105 	 */
2106 	if (s->chanid == -1)
2107 		fatal("no channel for session %d", s->self);
2108 	channel_set_fds(s->chanid,
2109 	    fdout, fdin, fderr,
2110 	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2111 	    1,
2112 	    CHAN_SES_WINDOW_DEFAULT);
2113 }
2114 
2115 /*
2116  * Function to perform pty cleanup. Also called if we get aborted abnormally
2117  * (e.g., due to a dropped connection).
2118  */
2119 void
2120 session_pty_cleanup2(void *session)
2121 {
2122 	Session *s = session;
2123 
2124 	if (s == NULL) {
2125 		error("session_pty_cleanup: no session");
2126 		return;
2127 	}
2128 	if (s->ttyfd == -1)
2129 		return;
2130 
2131 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2132 
2133 #ifdef USE_PAM
2134 	session_do_pam(s, 0);
2135 #endif /* USE_PAM */
2136 
2137 	/* Record that the user has logged out. */
2138 	if (s->pid != 0) {
2139 		debug3("Recording SSHv2 channel login in utmpx/wtmpx");
2140 #ifdef ALTPRIVSEP
2141 		altprivsep_record_logout(s->pid);
2142 #else /* ALTPRIVSEP */
2143 		record_logout(s->pid, s->tty, NULL, s->pw->pw_name);
2144 #endif /* ALTPRIVSEP */
2145 	}
2146 
2147 	/* Release the pseudo-tty. */
2148 	if (getuid() == 0)
2149 		pty_release(s->tty);
2150 
2151 	/*
2152 	 * Close the server side of the socket pairs.  We must do this after
2153 	 * the pty cleanup, so that another process doesn't get this pty
2154 	 * while we're still cleaning up.
2155 	 */
2156 	if (close(s->ptymaster) < 0)
2157 		error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2158 
2159 	/* unlink pty from session */
2160 	s->ttyfd = -1;
2161 }
2162 
2163 void
2164 session_pty_cleanup(void *session)
2165 {
2166 	PRIVSEP(session_pty_cleanup2(session));
2167 }
2168 
2169 /*
2170  * We use a different temporary X authority file per every session so we
2171  * should remove those files when fatal() is called.
2172  */
2173 void
2174 session_xauthfile_cleanup(void *session)
2175 {
2176 	Session *s = session;
2177 
2178 	if (s == NULL) {
2179 		error("session_xauthfile_cleanup: no session");
2180 		return;
2181 	}
2182 
2183 	debug("session_xauthfile_cleanup: session %d removing %s", s->self,
2184 	    s->auth_file);
2185 
2186 	if (unlink(s->auth_file) == -1) {
2187 		error("session_xauthfile_cleanup: cannot remove xauth file: "
2188 		    "%.100s", strerror(errno));
2189 		return;
2190 	}
2191 
2192 	/* dirname() will modify s->auth_file but that's ok */
2193 	if (rmdir(dirname(s->auth_file)) == -1) {
2194 		error("session_xauthfile_cleanup: "
2195 		    "cannot remove xauth directory: %.100s", strerror(errno));
2196 		return;
2197 	}
2198 }
2199 
2200 static char *
2201 sig2name(int sig)
2202 {
2203 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2204 	SSH_SIG(ABRT);
2205 	SSH_SIG(ALRM);
2206 	SSH_SIG(FPE);
2207 	SSH_SIG(HUP);
2208 	SSH_SIG(ILL);
2209 	SSH_SIG(INT);
2210 	SSH_SIG(KILL);
2211 	SSH_SIG(PIPE);
2212 	SSH_SIG(QUIT);
2213 	SSH_SIG(SEGV);
2214 	SSH_SIG(TERM);
2215 	SSH_SIG(USR1);
2216 	SSH_SIG(USR2);
2217 #undef	SSH_SIG
2218 	return "SIG@openssh.com";
2219 }
2220 
2221 static void
2222 session_exit_message(Session *s, int status)
2223 {
2224 	Channel *c;
2225 
2226 	if ((c = channel_lookup(s->chanid)) == NULL)
2227 		fatal("session_exit_message: session %d: no channel %d",
2228 		    s->self, s->chanid);
2229 	debug("session_exit_message: session %d channel %d pid %ld",
2230 	    s->self, s->chanid, (long)s->pid);
2231 
2232 	if (WIFEXITED(status)) {
2233 		channel_request_start(s->chanid, "exit-status", 0);
2234 		packet_put_int(WEXITSTATUS(status));
2235 		packet_send();
2236 	} else if (WIFSIGNALED(status)) {
2237 		channel_request_start(s->chanid, "exit-signal", 0);
2238 		packet_put_cstring(sig2name(WTERMSIG(status)));
2239 #ifdef WCOREDUMP
2240 		packet_put_char(WCOREDUMP(status));
2241 #else /* WCOREDUMP */
2242 		packet_put_char(0);
2243 #endif /* WCOREDUMP */
2244 		packet_put_cstring("");
2245 		packet_put_cstring("");
2246 		packet_send();
2247 	} else {
2248 		/* Some weird exit cause.  Just exit. */
2249 		packet_disconnect("wait returned status %04x.", status);
2250 	}
2251 
2252 	/* Ok to close channel now */
2253 	channel_set_wait_for_exit(s->chanid, 0);
2254 
2255 	/* disconnect channel */
2256 	debug("session_exit_message: release channel %d", s->chanid);
2257 	channel_cancel_cleanup(s->chanid);
2258 	/*
2259 	 * emulate a write failure with 'chan_write_failed', nobody will be
2260 	 * interested in data we write.
2261 	 * Note that we must not call 'chan_read_failed', since there could
2262 	 * be some more data waiting in the pipe.
2263 	 */
2264 	if (c->ostate != CHAN_OUTPUT_CLOSED)
2265 		chan_write_failed(c);
2266 	s->chanid = -1;
2267 }
2268 
2269 void
2270 session_close(Session *s)
2271 {
2272 	debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2273 	if (s->ttyfd != -1) {
2274 		fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2275 		session_pty_cleanup(s);
2276 	}
2277 	if (s->auth_file != NULL) {
2278 		fatal_remove_cleanup(session_xauthfile_cleanup, (void *)s);
2279 		session_xauthfile_cleanup(s);
2280 		xfree(s->auth_file);
2281 	}
2282 	if (s->term)
2283 		xfree(s->term);
2284 	if (s->display)
2285 		xfree(s->display);
2286 	if (s->auth_display)
2287 		xfree(s->auth_display);
2288 	if (s->auth_data)
2289 		xfree(s->auth_data);
2290 	if (s->auth_proto)
2291 		xfree(s->auth_proto);
2292 	if (s->command)
2293 		xfree(s->command);
2294 	session_free_env(&s->env);
2295 	s->used = 0;
2296 	session_proctitle(s);
2297 }
2298 
2299 void
2300 session_close_by_pid(pid_t pid, int status)
2301 {
2302 	Session *s = session_by_pid(pid);
2303 	if (s == NULL) {
2304 		debug("session_close_by_pid: no session for pid %ld",
2305 		    (long)pid);
2306 		return;
2307 	}
2308 	if (s->chanid != -1)
2309 		session_exit_message(s, status);
2310 	session_close(s);
2311 }
2312 
2313 /*
2314  * This is called when a channel dies before the session 'child' itself dies.
2315  * It can happen for example if we exit from an interactive shell before we
2316  * exit from forwarded X11 applications.
2317  */
2318 void
2319 session_close_by_channel(int id, void *arg)
2320 {
2321 	Session *s = session_by_channel(id);
2322 	if (s == NULL) {
2323 		debug("session_close_by_channel: no session for id %d", id);
2324 		return;
2325 	}
2326 	debug("session_close_by_channel: channel %d child %ld",
2327 	    id, (long)s->pid);
2328 	if (s->pid != 0) {
2329 		debug("session_close_by_channel: channel %d: has child", id);
2330 		/*
2331 		 * delay detach of session, but release pty, since
2332 		 * the fd's to the child are already closed
2333 		 */
2334 		if (s->ttyfd != -1) {
2335 			fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2336 			session_pty_cleanup(s);
2337 		}
2338 		return;
2339 	}
2340 	/* detach by removing callback */
2341 	channel_cancel_cleanup(s->chanid);
2342 	s->chanid = -1;
2343 	session_close(s);
2344 }
2345 
2346 void
2347 session_destroy_all(void (*closefunc)(Session *))
2348 {
2349 	int i;
2350 	for (i = 0; i < MAX_SESSIONS; i++) {
2351 		Session *s = &sessions[i];
2352 		if (s->used) {
2353 			if (closefunc != NULL)
2354 				closefunc(s);
2355 			else
2356 				session_close(s);
2357 		}
2358 	}
2359 }
2360 
2361 static char *
2362 session_tty_list(void)
2363 {
2364 	static char buf[1024];
2365 	int i;
2366 	buf[0] = '\0';
2367 	for (i = 0; i < MAX_SESSIONS; i++) {
2368 		Session *s = &sessions[i];
2369 		if (s->used && s->ttyfd != -1) {
2370 			if (buf[0] != '\0')
2371 				strlcat(buf, ",", sizeof buf);
2372 			strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2373 		}
2374 	}
2375 	if (buf[0] == '\0')
2376 		strlcpy(buf, "notty", sizeof buf);
2377 	return buf;
2378 }
2379 
2380 void
2381 session_proctitle(Session *s)
2382 {
2383 	if (s->pw == NULL)
2384 		error("no user for session %d", s->self);
2385 	else
2386 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2387 }
2388 
2389 int
2390 session_setup_x11fwd(Session *s)
2391 {
2392 	struct stat st;
2393 	char display[512], auth_display[512];
2394 	char hostname[MAXHOSTNAMELEN];
2395 
2396 	if (no_x11_forwarding_flag) {
2397 		packet_send_debug("X11 forwarding disabled in user configuration file.");
2398 		return 0;
2399 	}
2400 	if (!options.x11_forwarding) {
2401 		debug("X11 forwarding disabled in server configuration file.");
2402 		return 0;
2403 	}
2404 	if (!options.xauth_location ||
2405 	    (stat(options.xauth_location, &st) == -1)) {
2406 		packet_send_debug("No xauth program; cannot forward with spoofing.");
2407 		return 0;
2408 	}
2409 	if (options.use_login) {
2410 		packet_send_debug("X11 forwarding disabled; "
2411 		    "not compatible with UseLogin=yes.");
2412 		return 0;
2413 	}
2414 	if (s->display != NULL) {
2415 		debug("X11 display already set.");
2416 		return 0;
2417 	}
2418 	if (x11_create_display_inet(options.x11_display_offset,
2419 	    options.x11_use_localhost, s->single_connection,
2420 	    &s->display_number) == -1) {
2421 		debug("x11_create_display_inet failed.");
2422 		return 0;
2423 	}
2424 
2425 	/* Set up a suitable value for the DISPLAY variable. */
2426 	if (gethostname(hostname, sizeof(hostname)) < 0)
2427 		fatal("gethostname: %.100s", strerror(errno));
2428 	/*
2429 	 * auth_display must be used as the displayname when the
2430 	 * authorization entry is added with xauth(1).  This will be
2431 	 * different than the DISPLAY string for localhost displays.
2432 	 */
2433 	if (options.x11_use_localhost) {
2434 		snprintf(display, sizeof display, "localhost:%u.%u",
2435 		    s->display_number, s->screen);
2436 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2437 		    s->display_number, s->screen);
2438 		s->display = xstrdup(display);
2439 		s->auth_display = xstrdup(auth_display);
2440 	} else {
2441 #ifdef IPADDR_IN_DISPLAY
2442 		struct hostent *he;
2443 		struct in_addr my_addr;
2444 
2445 		he = gethostbyname(hostname);
2446 		if (he == NULL) {
2447 			error("Can't get IP address for X11 DISPLAY.");
2448 			packet_send_debug("Can't get IP address for X11 DISPLAY.");
2449 			return 0;
2450 		}
2451 		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2452 		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2453 		    s->display_number, s->screen);
2454 #else
2455 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2456 		    s->display_number, s->screen);
2457 #endif
2458 		s->display = xstrdup(display);
2459 		s->auth_display = xstrdup(display);
2460 	}
2461 
2462 	return 1;
2463 }
2464 
2465 #ifdef USE_PAM
2466 int session_do_pam_conv(int, struct pam_message **,
2467 			struct pam_response **, void *);
2468 
2469 static struct pam_conv session_pam_conv = {
2470 	session_do_pam_conv,
2471 	NULL
2472 };
2473 
2474 static void
2475 session_do_pam(Session *s, int do_open)
2476 {
2477 	int pam_retval;
2478 	char *where, *old_tty, *old_tty_copy = NULL;
2479 	struct pam_conv old_conv, *old_conv_ptr;
2480 
2481 	if (!s || !s->authctxt || !s->authctxt->pam || !s->authctxt->pam->h)
2482 		return;
2483 
2484 	/* Save current PAM item values */
2485 	where = "getting PAM_CONV";
2486 	pam_retval = pam_get_item(s->authctxt->pam->h, PAM_CONV,
2487 				  (void **) &old_conv_ptr);
2488 	if (pam_retval != PAM_SUCCESS)
2489 		goto done;
2490 	old_conv = *old_conv_ptr;
2491 
2492 	where = "getting PAM_TTY";
2493 	pam_retval = pam_get_item(s->authctxt->pam->h, PAM_TTY,
2494 				  (void **) &old_tty);
2495 	if (pam_retval != PAM_SUCCESS)
2496 		goto done;
2497 	old_tty_copy = xstrdup(old_tty);
2498 
2499 	/* Change PAM_TTY and PAM_CONV items */
2500 	where = "setting PAM_TTY";
2501 	pam_retval = pam_set_item(s->authctxt->pam->h, PAM_TTY, s->tty);
2502 	if (pam_retval != PAM_SUCCESS)
2503 		goto done;
2504 
2505 	where = "setting PAM_CONV";
2506 	session_pam_conv.appdata_ptr = s;
2507 	pam_retval = pam_set_item(s->authctxt->pam->h,
2508 				  PAM_CONV, &session_pam_conv);
2509 	if (pam_retval != PAM_SUCCESS)
2510 		goto done;
2511 
2512 	/* Call pam_open/close_session() */
2513 	if (do_open) {
2514 		where = "calling pam_open_session()";
2515 		pam_retval = pam_open_session(s->authctxt->pam->h, 0);
2516 	}
2517 	else {
2518 		where = "calling pam_close_session()";
2519 		pam_retval = pam_close_session(s->authctxt->pam->h, 0);
2520 	}
2521 
2522 	/* Reset PAM_TTY and PAM_CONV items to previous values */
2523 	where = "setting PAM_TTY";
2524 	pam_retval = pam_set_item(s->authctxt->pam->h, PAM_TTY, old_tty_copy);
2525 	if (pam_retval != PAM_SUCCESS)
2526 		goto done;
2527 
2528 	where = "setting PAM_CONV";
2529 	pam_retval = pam_set_item(s->authctxt->pam->h, PAM_CONV, &old_conv);
2530 	if (pam_retval != PAM_SUCCESS)
2531 		goto done;
2532 
2533 	session_pam_conv.appdata_ptr = NULL;
2534 
2535 done:
2536 	if (old_tty_copy)
2537 		xfree(old_tty_copy);
2538 
2539 	if (pam_retval == PAM_SUCCESS)
2540 		return;
2541 
2542 	/* fatal()? probably not... */
2543 	log("PAM failed[%d] while %s: %s", pam_retval, where,
2544 	    PAM_STRERROR(s->authctxt->pam->h, pam_retval));
2545 }
2546 
2547 int
2548 session_do_pam_conv(int num_prompts,
2549 		    struct pam_message **prompts,
2550 		    struct pam_response **resp,
2551 		    void *app_data)
2552 {
2553 	Session *s = (Session *) app_data;
2554 
2555 	struct pam_response *reply;
2556 	int count;
2557 	char *prompt;
2558 
2559 	if (channel_lookup(s->chanid) == NULL)
2560 		return PAM_CONV_ERR;
2561 
2562 	/* PAM will free this later */
2563 	reply = xmalloc(num_prompts * sizeof(*reply));
2564 
2565 	(void) memset(reply, 0, num_prompts * sizeof(*reply));
2566 	for (count = 0; count < num_prompts; count++) {
2567 		switch(PAM_MSG_MEMBER(prompts, count, msg_style)) {
2568 		case PAM_TEXT_INFO:
2569 			/* Write to stdout of channel */
2570 			prompt = PAM_MSG_MEMBER(prompts, count, msg);
2571 			if (prompt != NULL && s->ttyfd != -1) {
2572 				debug2("session_do_pam_conv: text info "
2573 				       "prompt: %s", prompt);
2574 				(void) write(s->ttyfd, prompt, strlen(prompt));
2575 				(void) write(s->ttyfd, "\n", 1);
2576 			}
2577 			reply[count].resp = xstrdup("");
2578 			reply[count].resp_retcode = PAM_SUCCESS;
2579 			break;
2580 		case PAM_ERROR_MSG:
2581 			/* Write to stderr of channel */
2582 			prompt = PAM_MSG_MEMBER(prompts, count, msg);
2583 			if (prompt != NULL && s->ttyfd != -1) {
2584 				debug2("session_do_pam_conv: error "
2585 				       "prompt: %s", prompt);
2586 				(void) write(s->ttyfd, prompt, strlen(prompt));
2587 				(void) write(s->ttyfd, "\n", 1);
2588 			}
2589 			reply[count].resp = xstrdup("");
2590 			reply[count].resp_retcode = PAM_SUCCESS;
2591 			break;
2592 		case PAM_PROMPT_ECHO_ON:
2593 		case PAM_PROMPT_ECHO_OFF:
2594 		    /*
2595 		     * XXX Someday add support for echo on/off prompts
2596 		     *     here on sessions with ttys.
2597 		     */
2598 		default:
2599 			xfree(reply);
2600 			return PAM_CONV_ERR;
2601 		}
2602 	}
2603 
2604 	*resp = reply;
2605 
2606 	return PAM_SUCCESS;
2607 }
2608 #endif /* USE_PAM */
2609 
2610 static void
2611 do_authenticated2(Authctxt *authctxt)
2612 {
2613 	server_loop2(authctxt);
2614 }
2615