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