xref: /freebsd/crypto/openssh/session.c (revision 11f0b352e05306cf6f1f85e9087022c0a92624a3)
1 /*
2  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3  *                    All rights reserved
4  *
5  * As far as I am concerned, the code I have written for this software
6  * can be used freely for any purpose.  Any derived versions of this
7  * software must be clearly marked as such, and if the derived work is
8  * incompatible with the protocol description in the RFC file, it must be
9  * called by a name other than "ssh" or "Secure Shell".
10  *
11  * SSH2 support by Markus Friedl.
12  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include "includes.h"
36 RCSID("$OpenBSD: session.c,v 1.142 2002/06/26 13:49:26 deraadt Exp $");
37 RCSID("$FreeBSD$");
38 
39 #include "ssh.h"
40 #include "ssh1.h"
41 #include "ssh2.h"
42 #include "xmalloc.h"
43 #include "sshpty.h"
44 #include "packet.h"
45 #include "buffer.h"
46 #include "mpaux.h"
47 #include "uidswap.h"
48 #include "compat.h"
49 #include "channels.h"
50 #include "bufaux.h"
51 #include "auth.h"
52 #include "auth-options.h"
53 #include "pathnames.h"
54 #include "log.h"
55 #include "servconf.h"
56 #include "sshlogin.h"
57 #include "serverloop.h"
58 #include "canohost.h"
59 #include "session.h"
60 #include "monitor_wrap.h"
61 
62 #ifdef HAVE_CYGWIN
63 #include <windows.h>
64 #include <sys/cygwin.h>
65 #define is_winnt       (GetVersion() < 0x80000000)
66 #endif
67 
68 /* func */
69 
70 Session *session_new(void);
71 void	session_set_fds(Session *, int, int, int);
72 void	session_pty_cleanup(void *);
73 void	session_proctitle(Session *);
74 int	session_setup_x11fwd(Session *);
75 void	do_exec_pty(Session *, const char *);
76 void	do_exec_no_pty(Session *, const char *);
77 void	do_exec(Session *, const char *);
78 void	do_login(Session *, const char *);
79 #ifdef LOGIN_NEEDS_UTMPX
80 static void	do_pre_login(Session *s);
81 #endif
82 void	do_child(Session *, const char *);
83 void	do_motd(void);
84 int	check_quietlogin(Session *, const char *);
85 
86 static void do_authenticated1(Authctxt *);
87 static void do_authenticated2(Authctxt *);
88 
89 static int session_pty_req(Session *);
90 
91 /* import */
92 extern ServerOptions options;
93 extern char *__progname;
94 extern int log_stderr;
95 extern int debug_flag;
96 extern u_int utmp_len;
97 extern int startup_pipe;
98 extern void destroy_sensitive_data(void);
99 
100 /* original command from peer. */
101 const char *original_command = NULL;
102 
103 /* data */
104 #define MAX_SESSIONS 10
105 Session	sessions[MAX_SESSIONS];
106 
107 #ifdef WITH_AIXAUTHENTICATE
108 char *aixloginmsg;
109 #endif /* WITH_AIXAUTHENTICATE */
110 
111 #ifdef HAVE_LOGIN_CAP
112 login_cap_t *lc;
113 #endif
114 
115 /* Name and directory of socket for authentication agent forwarding. */
116 static char *auth_sock_name = NULL;
117 static char *auth_sock_dir = NULL;
118 
119 /* removes the agent forwarding socket */
120 
121 static void
122 auth_sock_cleanup_proc(void *_pw)
123 {
124 	struct passwd *pw = _pw;
125 
126 	if (auth_sock_name != NULL) {
127 		temporarily_use_uid(pw);
128 		unlink(auth_sock_name);
129 		rmdir(auth_sock_dir);
130 		auth_sock_name = NULL;
131 		restore_uid();
132 	}
133 }
134 
135 static int
136 auth_input_request_forwarding(struct passwd * pw)
137 {
138 	Channel *nc;
139 	int sock;
140 	struct sockaddr_un sunaddr;
141 
142 	if (auth_sock_name != NULL) {
143 		error("authentication forwarding requested twice.");
144 		return 0;
145 	}
146 
147 	/* Temporarily drop privileged uid for mkdir/bind. */
148 	temporarily_use_uid(pw);
149 
150 	/* Allocate a buffer for the socket name, and format the name. */
151 	auth_sock_name = xmalloc(MAXPATHLEN);
152 	auth_sock_dir = xmalloc(MAXPATHLEN);
153 	strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
154 
155 	/* Create private directory for socket */
156 	if (mkdtemp(auth_sock_dir) == NULL) {
157 		packet_send_debug("Agent forwarding disabled: "
158 		    "mkdtemp() failed: %.100s", strerror(errno));
159 		restore_uid();
160 		xfree(auth_sock_name);
161 		xfree(auth_sock_dir);
162 		auth_sock_name = NULL;
163 		auth_sock_dir = NULL;
164 		return 0;
165 	}
166 	snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
167 		 auth_sock_dir, (long) getpid());
168 
169 	/* delete agent socket on fatal() */
170 	fatal_add_cleanup(auth_sock_cleanup_proc, pw);
171 
172 	/* Create the socket. */
173 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
174 	if (sock < 0)
175 		packet_disconnect("socket: %.100s", strerror(errno));
176 
177 	/* Bind it to the name. */
178 	memset(&sunaddr, 0, sizeof(sunaddr));
179 	sunaddr.sun_family = AF_UNIX;
180 	strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
181 
182 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
183 		packet_disconnect("bind: %.100s", strerror(errno));
184 
185 	/* Restore the privileged uid. */
186 	restore_uid();
187 
188 	/* Start listening on the socket. */
189 	if (listen(sock, 5) < 0)
190 		packet_disconnect("listen: %.100s", strerror(errno));
191 
192 	/* Allocate a channel for the authentication agent socket. */
193 	nc = channel_new("auth socket",
194 	    SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
195 	    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
196 	    0, xstrdup("auth socket"), 1);
197 	strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
198 	return 1;
199 }
200 
201 
202 void
203 do_authenticated(Authctxt *authctxt)
204 {
205 	/*
206 	 * Cancel the alarm we set to limit the time taken for
207 	 * authentication.
208 	 */
209 	alarm(0);
210 	if (startup_pipe != -1) {
211 		close(startup_pipe);
212 		startup_pipe = -1;
213 	}
214 #ifdef WITH_AIXAUTHENTICATE
215 	/* We don't have a pty yet, so just label the line as "ssh" */
216 	if (loginsuccess(authctxt->user,
217 	    get_canonical_hostname(options.verify_reverse_mapping),
218 	    "ssh", &aixloginmsg) < 0)
219 		aixloginmsg = NULL;
220 #endif /* WITH_AIXAUTHENTICATE */
221 
222 	/* setup the channel layer */
223 	if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
224 		channel_permit_all_opens();
225 
226 	if (compat20)
227 		do_authenticated2(authctxt);
228 	else
229 		do_authenticated1(authctxt);
230 
231 	/* remove agent socket */
232 	if (auth_sock_name != NULL)
233 		auth_sock_cleanup_proc(authctxt->pw);
234 #ifdef KRB4
235 	if (options.kerberos_ticket_cleanup)
236 		krb4_cleanup_proc(authctxt);
237 #endif
238 #ifdef KRB5
239 	if (options.kerberos_ticket_cleanup)
240 		krb5_cleanup_proc(authctxt);
241 #endif
242 }
243 
244 /*
245  * Prepares for an interactive session.  This is called after the user has
246  * been successfully authenticated.  During this message exchange, pseudo
247  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
248  * are requested, etc.
249  */
250 static void
251 do_authenticated1(Authctxt *authctxt)
252 {
253 	Session *s;
254 	char *command;
255 	int success, type, screen_flag;
256 	int enable_compression_after_reply = 0;
257 	u_int proto_len, data_len, dlen, compression_level = 0;
258 
259 	s = session_new();
260 	s->authctxt = authctxt;
261 	s->pw = authctxt->pw;
262 
263 	/*
264 	 * We stay in this loop until the client requests to execute a shell
265 	 * or a command.
266 	 */
267 	for (;;) {
268 		success = 0;
269 
270 		/* Get a packet from the client. */
271 		type = packet_read();
272 
273 		/* Process the packet. */
274 		switch (type) {
275 		case SSH_CMSG_REQUEST_COMPRESSION:
276 			compression_level = packet_get_int();
277 			packet_check_eom();
278 			if (compression_level < 1 || compression_level > 9) {
279 				packet_send_debug("Received illegal compression level %d.",
280 				    compression_level);
281 				break;
282 			}
283 			if (!options.compression) {
284 				debug2("compression disabled");
285 				break;
286 			}
287 			/* Enable compression after we have responded with SUCCESS. */
288 			enable_compression_after_reply = 1;
289 			success = 1;
290 			break;
291 
292 		case SSH_CMSG_REQUEST_PTY:
293 			success = session_pty_req(s);
294 			break;
295 
296 		case SSH_CMSG_X11_REQUEST_FORWARDING:
297 			s->auth_proto = packet_get_string(&proto_len);
298 			s->auth_data = packet_get_string(&data_len);
299 
300 			screen_flag = packet_get_protocol_flags() &
301 			    SSH_PROTOFLAG_SCREEN_NUMBER;
302 			debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
303 
304 			if (packet_remaining() == 4) {
305 				if (!screen_flag)
306 					debug2("Buggy client: "
307 					    "X11 screen flag missing");
308 				s->screen = packet_get_int();
309 			} else {
310 				s->screen = 0;
311 			}
312 			packet_check_eom();
313 			success = session_setup_x11fwd(s);
314 			if (!success) {
315 				xfree(s->auth_proto);
316 				xfree(s->auth_data);
317 				s->auth_proto = NULL;
318 				s->auth_data = NULL;
319 			}
320 			break;
321 
322 		case SSH_CMSG_AGENT_REQUEST_FORWARDING:
323 			if (no_agent_forwarding_flag || compat13) {
324 				debug("Authentication agent forwarding not permitted for this authentication.");
325 				break;
326 			}
327 			debug("Received authentication agent forwarding request.");
328 			success = auth_input_request_forwarding(s->pw);
329 			break;
330 
331 		case SSH_CMSG_PORT_FORWARD_REQUEST:
332 			if (no_port_forwarding_flag) {
333 				debug("Port forwarding not permitted for this authentication.");
334 				break;
335 			}
336 			if (!options.allow_tcp_forwarding) {
337 				debug("Port forwarding not permitted.");
338 				break;
339 			}
340 			debug("Received TCP/IP port forwarding request.");
341 			channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
342 			success = 1;
343 			break;
344 
345 		case SSH_CMSG_MAX_PACKET_SIZE:
346 			if (packet_set_maxsize(packet_get_int()) > 0)
347 				success = 1;
348 			break;
349 
350 #if defined(AFS) || defined(KRB5)
351 		case SSH_CMSG_HAVE_KERBEROS_TGT:
352 			if (!options.kerberos_tgt_passing) {
353 				verbose("Kerberos TGT passing disabled.");
354 			} else {
355 				char *kdata = packet_get_string(&dlen);
356 				packet_check_eom();
357 
358 				/* XXX - 0x41, see creds_to_radix version */
359 				if (kdata[0] != 0x41) {
360 #ifdef KRB5
361 					krb5_data tgt;
362 					tgt.data = kdata;
363 					tgt.length = dlen;
364 
365 					if (auth_krb5_tgt(s->authctxt, &tgt))
366 						success = 1;
367 					else
368 						verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
369 #endif /* KRB5 */
370 				} else {
371 #ifdef AFS
372 					if (auth_krb4_tgt(s->authctxt, kdata))
373 						success = 1;
374 					else
375 						verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
376 #endif /* AFS */
377 				}
378 				xfree(kdata);
379 			}
380 			break;
381 #endif /* AFS || KRB5 */
382 
383 #ifdef AFS
384 		case SSH_CMSG_HAVE_AFS_TOKEN:
385 			if (!options.afs_token_passing || !k_hasafs()) {
386 				verbose("AFS token passing disabled.");
387 			} else {
388 				/* Accept AFS token. */
389 				char *token = packet_get_string(&dlen);
390 				packet_check_eom();
391 
392 				if (auth_afs_token(s->authctxt, token))
393 					success = 1;
394 				else
395 					verbose("AFS token refused for %.100s",
396 					    s->authctxt->user);
397 				xfree(token);
398 			}
399 			break;
400 #endif /* AFS */
401 
402 		case SSH_CMSG_EXEC_SHELL:
403 		case SSH_CMSG_EXEC_CMD:
404 			if (type == SSH_CMSG_EXEC_CMD) {
405 				command = packet_get_string(&dlen);
406 				debug("Exec command '%.500s'", command);
407 				do_exec(s, command);
408 				xfree(command);
409 			} else {
410 				do_exec(s, NULL);
411 			}
412 			packet_check_eom();
413 			session_close(s);
414 			return;
415 
416 		default:
417 			/*
418 			 * Any unknown messages in this phase are ignored,
419 			 * and a failure message is returned.
420 			 */
421 			log("Unknown packet type received after authentication: %d", type);
422 		}
423 		packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
424 		packet_send();
425 		packet_write_wait();
426 
427 		/* Enable compression now that we have replied if appropriate. */
428 		if (enable_compression_after_reply) {
429 			enable_compression_after_reply = 0;
430 			packet_start_compression(compression_level);
431 		}
432 	}
433 }
434 
435 /*
436  * This is called to fork and execute a command when we have no tty.  This
437  * will call do_child from the child, and server_loop from the parent after
438  * setting up file descriptors and such.
439  */
440 void
441 do_exec_no_pty(Session *s, const char *command)
442 {
443 	pid_t pid;
444 
445 #ifdef USE_PIPES
446 	int pin[2], pout[2], perr[2];
447 	/* Allocate pipes for communicating with the program. */
448 	if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
449 		packet_disconnect("Could not create pipes: %.100s",
450 				  strerror(errno));
451 #else /* USE_PIPES */
452 	int inout[2], err[2];
453 	/* Uses socket pairs to communicate with the program. */
454 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
455 	    socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
456 		packet_disconnect("Could not create socket pairs: %.100s",
457 				  strerror(errno));
458 #endif /* USE_PIPES */
459 	if (s == NULL)
460 		fatal("do_exec_no_pty: no session");
461 
462 	session_proctitle(s);
463 
464 #if defined(USE_PAM)
465 	do_pam_session(s->pw->pw_name, NULL);
466 	do_pam_setcred(1);
467 	if (is_pam_password_change_required())
468 		packet_disconnect("Password change required but no "
469 		    "TTY available");
470 #endif /* USE_PAM */
471 
472 	/* Fork the child. */
473 	if ((pid = fork()) == 0) {
474 		/* Child.  Reinitialize the log since the pid has changed. */
475 		log_init(__progname, options.log_level, options.log_facility, log_stderr);
476 
477 		/*
478 		 * Create a new session and process group since the 4.4BSD
479 		 * setlogin() affects the entire process group.
480 		 */
481 		if (setsid() < 0)
482 			error("setsid failed: %.100s", strerror(errno));
483 
484 #ifdef USE_PIPES
485 		/*
486 		 * Redirect stdin.  We close the parent side of the socket
487 		 * pair, and make the child side the standard input.
488 		 */
489 		close(pin[1]);
490 		if (dup2(pin[0], 0) < 0)
491 			perror("dup2 stdin");
492 		close(pin[0]);
493 
494 		/* Redirect stdout. */
495 		close(pout[0]);
496 		if (dup2(pout[1], 1) < 0)
497 			perror("dup2 stdout");
498 		close(pout[1]);
499 
500 		/* Redirect stderr. */
501 		close(perr[0]);
502 		if (dup2(perr[1], 2) < 0)
503 			perror("dup2 stderr");
504 		close(perr[1]);
505 #else /* USE_PIPES */
506 		/*
507 		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
508 		 * use the same socket, as some programs (particularly rdist)
509 		 * seem to depend on it.
510 		 */
511 		close(inout[1]);
512 		close(err[1]);
513 		if (dup2(inout[0], 0) < 0)	/* stdin */
514 			perror("dup2 stdin");
515 		if (dup2(inout[0], 1) < 0)	/* stdout.  Note: same socket as stdin. */
516 			perror("dup2 stdout");
517 		if (dup2(err[0], 2) < 0)	/* stderr */
518 			perror("dup2 stderr");
519 #endif /* USE_PIPES */
520 
521 		/* Do processing for the child (exec command etc). */
522 		do_child(s, command);
523 		/* NOTREACHED */
524 	}
525 #ifdef HAVE_CYGWIN
526 	if (is_winnt)
527 		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
528 #endif
529 	if (pid < 0)
530 		packet_disconnect("fork failed: %.100s", strerror(errno));
531 	s->pid = pid;
532 	/* Set interactive/non-interactive mode. */
533 	packet_set_interactive(s->display != NULL);
534 #ifdef USE_PIPES
535 	/* We are the parent.  Close the child sides of the pipes. */
536 	close(pin[0]);
537 	close(pout[1]);
538 	close(perr[1]);
539 
540 	if (compat20) {
541 		session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
542 	} else {
543 		/* Enter the interactive session. */
544 		server_loop(pid, pin[1], pout[0], perr[0]);
545 		/* server_loop has closed pin[1], pout[0], and perr[0]. */
546 	}
547 #else /* USE_PIPES */
548 	/* We are the parent.  Close the child sides of the socket pairs. */
549 	close(inout[0]);
550 	close(err[0]);
551 
552 	/*
553 	 * Enter the interactive session.  Note: server_loop must be able to
554 	 * handle the case that fdin and fdout are the same.
555 	 */
556 	if (compat20) {
557 		session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
558 	} else {
559 		server_loop(pid, inout[1], inout[1], err[1]);
560 		/* server_loop has closed inout[1] and err[1]. */
561 	}
562 #endif /* USE_PIPES */
563 }
564 
565 /*
566  * This is called to fork and execute a command when we have a tty.  This
567  * will call do_child from the child, and server_loop from the parent after
568  * setting up file descriptors, controlling tty, updating wtmp, utmp,
569  * lastlog, and other such operations.
570  */
571 void
572 do_exec_pty(Session *s, const char *command)
573 {
574 	int fdout, ptyfd, ttyfd, ptymaster;
575 	pid_t pid;
576 
577 	if (s == NULL)
578 		fatal("do_exec_pty: no session");
579 	ptyfd = s->ptyfd;
580 	ttyfd = s->ttyfd;
581 
582 #if defined(USE_PAM)
583 	do_pam_session(s->pw->pw_name, s->tty);
584 	do_pam_setcred(1);
585 #endif
586 
587 	/* Fork the child. */
588 	if ((pid = fork()) == 0) {
589 
590 		/* Child.  Reinitialize the log because the pid has changed. */
591 		log_init(__progname, options.log_level, options.log_facility, log_stderr);
592 		/* Close the master side of the pseudo tty. */
593 		close(ptyfd);
594 
595 		/* Make the pseudo tty our controlling tty. */
596 		pty_make_controlling_tty(&ttyfd, s->tty);
597 
598 		/* Redirect stdin/stdout/stderr from the pseudo tty. */
599 		if (dup2(ttyfd, 0) < 0)
600 			error("dup2 stdin: %s", strerror(errno));
601 		if (dup2(ttyfd, 1) < 0)
602 			error("dup2 stdout: %s", strerror(errno));
603 		if (dup2(ttyfd, 2) < 0)
604 			error("dup2 stderr: %s", strerror(errno));
605 
606 		/* Close the extra descriptor for the pseudo tty. */
607 		close(ttyfd);
608 
609 		/* record login, etc. similar to login(1) */
610 #ifndef HAVE_OSF_SIA
611 		if (!(options.use_login && command == NULL))
612 			do_login(s, command);
613 # ifdef LOGIN_NEEDS_UTMPX
614 		else
615 			do_pre_login(s);
616 # endif
617 #endif
618 
619 		/* Do common processing for the child, such as execing the command. */
620 		do_child(s, command);
621 		/* NOTREACHED */
622 	}
623 #ifdef HAVE_CYGWIN
624 	if (is_winnt)
625 		cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
626 #endif
627 	if (pid < 0)
628 		packet_disconnect("fork failed: %.100s", strerror(errno));
629 	s->pid = pid;
630 
631 	/* Parent.  Close the slave side of the pseudo tty. */
632 	close(ttyfd);
633 
634 	/*
635 	 * Create another descriptor of the pty master side for use as the
636 	 * standard input.  We could use the original descriptor, but this
637 	 * simplifies code in server_loop.  The descriptor is bidirectional.
638 	 */
639 	fdout = dup(ptyfd);
640 	if (fdout < 0)
641 		packet_disconnect("dup #1 failed: %.100s", strerror(errno));
642 
643 	/* we keep a reference to the pty master */
644 	ptymaster = dup(ptyfd);
645 	if (ptymaster < 0)
646 		packet_disconnect("dup #2 failed: %.100s", strerror(errno));
647 	s->ptymaster = ptymaster;
648 
649 	/* Enter interactive session. */
650 	packet_set_interactive(1);
651 	if (compat20) {
652 		session_set_fds(s, ptyfd, fdout, -1);
653 	} else {
654 		server_loop(pid, ptyfd, fdout, -1);
655 		/* server_loop _has_ closed ptyfd and fdout. */
656 	}
657 }
658 
659 #ifdef LOGIN_NEEDS_UTMPX
660 static void
661 do_pre_login(Session *s)
662 {
663 	socklen_t fromlen;
664 	struct sockaddr_storage from;
665 	pid_t pid = getpid();
666 
667 	/*
668 	 * Get IP address of client. If the connection is not a socket, let
669 	 * the address be 0.0.0.0.
670 	 */
671 	memset(&from, 0, sizeof(from));
672 	if (packet_connection_is_on_socket()) {
673 		fromlen = sizeof(from);
674 		if (getpeername(packet_get_connection_in(),
675 		    (struct sockaddr *) & from, &fromlen) < 0) {
676 			debug("getpeername: %.100s", strerror(errno));
677 			fatal_cleanup();
678 		}
679 	}
680 
681 	record_utmp_only(pid, s->tty, s->pw->pw_name,
682 	    get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
683 	    (struct sockaddr *)&from);
684 }
685 #endif
686 
687 /*
688  * This is called to fork and execute a command.  If another command is
689  * to be forced, execute that instead.
690  */
691 void
692 do_exec(Session *s, const char *command)
693 {
694 	if (forced_command) {
695 		original_command = command;
696 		command = forced_command;
697 		debug("Forced command '%.900s'", command);
698 	}
699 
700 	if (s->ttyfd != -1)
701 		do_exec_pty(s, command);
702 	else
703 		do_exec_no_pty(s, command);
704 
705 	original_command = NULL;
706 }
707 
708 
709 /* administrative, login(1)-like work */
710 void
711 do_login(Session *s, const char *command)
712 {
713 	char *time_string;
714 	socklen_t fromlen;
715 	struct sockaddr_storage from;
716 	struct passwd * pw = s->pw;
717 	pid_t pid = getpid();
718 
719 	/*
720 	 * Get IP address of client. If the connection is not a socket, let
721 	 * the address be 0.0.0.0.
722 	 */
723 	memset(&from, 0, sizeof(from));
724 	if (packet_connection_is_on_socket()) {
725 		fromlen = sizeof(from);
726 		if (getpeername(packet_get_connection_in(),
727 		    (struct sockaddr *) & from, &fromlen) < 0) {
728 			debug("getpeername: %.100s", strerror(errno));
729 			fatal_cleanup();
730 		}
731 	}
732 
733 	/* Record that there was a login on that tty from the remote host. */
734 	if (!use_privsep)
735 		record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
736 		    get_remote_name_or_ip(utmp_len,
737 		    options.verify_reverse_mapping),
738 		    (struct sockaddr *)&from);
739 
740 #ifdef USE_PAM
741 	/*
742 	 * If password change is needed, do it now.
743 	 * This needs to occur before the ~/.hushlogin check.
744 	 */
745 	if (is_pam_password_change_required()) {
746 		print_pam_messages();
747 		do_pam_chauthtok();
748 	}
749 #endif
750 
751 	if (check_quietlogin(s, command))
752 		return;
753 
754 #ifdef USE_PAM
755 	if (!is_pam_password_change_required())
756 		print_pam_messages();
757 #endif /* USE_PAM */
758 #ifdef WITH_AIXAUTHENTICATE
759 	if (aixloginmsg && *aixloginmsg)
760 		printf("%s\n", aixloginmsg);
761 #endif /* WITH_AIXAUTHENTICATE */
762 
763 	if (options.print_lastlog && s->last_login_time != 0) {
764 		time_string = ctime(&s->last_login_time);
765 		if (strchr(time_string, '\n'))
766 			*strchr(time_string, '\n') = 0;
767 		if (strcmp(s->hostname, "") == 0)
768 			printf("Last login: %s\r\n", time_string);
769 		else
770 			printf("Last login: %s from %s\r\n", time_string,
771 			    s->hostname);
772 	}
773 
774 	do_motd();
775 }
776 
777 /*
778  * Display the message of the day.
779  */
780 void
781 do_motd(void)
782 {
783 	FILE *f;
784 	char buf[256];
785 
786 	if (options.print_motd) {
787 #ifdef HAVE_LOGIN_CAP
788 		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
789 		    "/etc/motd"), "r");
790 #else
791 		f = fopen("/etc/motd", "r");
792 #endif
793 		if (f) {
794 			while (fgets(buf, sizeof(buf), f))
795 				fputs(buf, stdout);
796 			fclose(f);
797 		}
798 	}
799 }
800 
801 
802 /*
803  * Check for quiet login, either .hushlogin or command given.
804  */
805 int
806 check_quietlogin(Session *s, const char *command)
807 {
808 	char buf[256];
809 	struct passwd *pw = s->pw;
810 	struct stat st;
811 
812 	/* Return 1 if .hushlogin exists or a command given. */
813 	if (command != NULL)
814 		return 1;
815 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
816 #ifdef HAVE_LOGIN_CAP
817 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
818 		return 1;
819 #else
820 	if (stat(buf, &st) >= 0)
821 		return 1;
822 #endif
823 	return 0;
824 }
825 
826 /*
827  * Sets the value of the given variable in the environment.  If the variable
828  * already exists, its value is overriden.
829  */
830 static void
831 child_set_env(char ***envp, u_int *envsizep, const char *name,
832 	const char *value)
833 {
834 	u_int i, namelen;
835 	char **env;
836 
837 	/*
838 	 * Find the slot where the value should be stored.  If the variable
839 	 * already exists, we reuse the slot; otherwise we append a new slot
840 	 * at the end of the array, expanding if necessary.
841 	 */
842 	env = *envp;
843 	namelen = strlen(name);
844 	for (i = 0; env[i]; i++)
845 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
846 			break;
847 	if (env[i]) {
848 		/* Reuse the slot. */
849 		xfree(env[i]);
850 	} else {
851 		/* New variable.  Expand if necessary. */
852 		if (i >= (*envsizep) - 1) {
853 			if (*envsizep >= 1000)
854 				fatal("child_set_env: too many env vars,"
855 				    " skipping: %.100s", name);
856 			(*envsizep) += 50;
857 			env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
858 		}
859 		/* Need to set the NULL pointer at end of array beyond the new slot. */
860 		env[i + 1] = NULL;
861 	}
862 
863 	/* Allocate space and format the variable in the appropriate slot. */
864 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
865 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
866 }
867 
868 /*
869  * Reads environment variables from the given file and adds/overrides them
870  * into the environment.  If the file does not exist, this does nothing.
871  * Otherwise, it must consist of empty lines, comments (line starts with '#')
872  * and assignments of the form name=value.  No other forms are allowed.
873  */
874 static void
875 read_environment_file(char ***env, u_int *envsize,
876 	const char *filename)
877 {
878 	FILE *f;
879 	char buf[4096];
880 	char *cp, *value;
881 	u_int lineno = 0;
882 
883 	f = fopen(filename, "r");
884 	if (!f)
885 		return;
886 
887 	while (fgets(buf, sizeof(buf), f)) {
888 		if (++lineno > 1000)
889 			fatal("Too many lines in environment file %s", filename);
890 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
891 			;
892 		if (!*cp || *cp == '#' || *cp == '\n')
893 			continue;
894 		if (strchr(cp, '\n'))
895 			*strchr(cp, '\n') = '\0';
896 		value = strchr(cp, '=');
897 		if (value == NULL) {
898 			fprintf(stderr, "Bad line %u in %.100s\n", lineno,
899 			    filename);
900 			continue;
901 		}
902 		/*
903 		 * Replace the equals sign by nul, and advance value to
904 		 * the value string.
905 		 */
906 		*value = '\0';
907 		value++;
908 		child_set_env(env, envsize, cp, value);
909 	}
910 	fclose(f);
911 }
912 
913 void copy_environment(char **source, char ***env, u_int *envsize)
914 {
915 	char *var_name, *var_val;
916 	int i;
917 
918 	if (source == NULL)
919 		return;
920 
921 	for(i = 0; source[i] != NULL; i++) {
922 		var_name = xstrdup(source[i]);
923 		if ((var_val = strstr(var_name, "=")) == NULL) {
924 			xfree(var_name);
925 			continue;
926 		}
927 		*var_val++ = '\0';
928 
929 		debug3("Copy environment: %s=%s", var_name, var_val);
930 		child_set_env(env, envsize, var_name, var_val);
931 
932 		xfree(var_name);
933 	}
934 }
935 
936 static char **
937 do_setup_env(Session *s, const char *shell)
938 {
939 	char buf[256];
940 	u_int i, envsize;
941 	char **env;
942 #ifdef HAVE_LOGIN_CAP
943 	extern char **environ;
944 	char **senv, **var;
945 #endif
946 	struct passwd *pw = s->pw;
947 
948 	/* Initialize the environment. */
949 	envsize = 100;
950 	env = xmalloc(envsize * sizeof(char *));
951 	env[0] = NULL;
952 
953 #ifdef HAVE_CYGWIN
954 	/*
955 	 * The Windows environment contains some setting which are
956 	 * important for a running system. They must not be dropped.
957 	 */
958 	copy_environment(environ, &env, &envsize);
959 #endif
960 
961 	if (getenv("TZ"))
962 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
963 	if (!options.use_login) {
964 		/* Set basic environment. */
965 		child_set_env(&env, &envsize, "USER", pw->pw_name);
966 		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
967 		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
968 		snprintf(buf, sizeof buf, "%.200s/%.50s",
969 			 _PATH_MAILDIR, pw->pw_name);
970 		child_set_env(&env, &envsize, "MAIL", buf);
971 #ifdef HAVE_LOGIN_CAP
972 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
973 		child_set_env(&env, &envsize, "TERM", "su");
974 		senv = environ;
975 		environ = xmalloc(sizeof(char *));
976 		*environ = NULL;
977 		(void) setusercontext(lc, pw, pw->pw_uid,
978 		    LOGIN_SETENV|LOGIN_SETPATH);
979 		copy_environment(environ, &env, &envsize);
980 		for (var = environ; *var != NULL; ++var)
981 			xfree(*var);
982 		xfree(environ);
983 		environ = senv;
984 #else /* HAVE_LOGIN_CAP */
985 # ifndef HAVE_CYGWIN
986 		/*
987 		 * There's no standard path on Windows. The path contains
988 		 * important components pointing to the system directories,
989 		 * needed for loading shared libraries. So the path better
990 		 * remains intact here.
991 		 */
992 #  ifdef SUPERUSER_PATH
993 		child_set_env(&env, &envsize, "PATH",
994 		    s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
995 #  else
996 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
997 #  endif /* SUPERUSER_PATH */
998 # endif /* HAVE_CYGWIN */
999 #endif /* HAVE_LOGIN_CAP */
1000 
1001 		/* Normal systems set SHELL by default. */
1002 		child_set_env(&env, &envsize, "SHELL", shell);
1003 	}
1004 
1005 	/* Set custom environment options from RSA authentication. */
1006 	if (!options.use_login) {
1007 		while (custom_environment) {
1008 			struct envstring *ce = custom_environment;
1009 			char *s = ce->s;
1010 
1011 			for (i = 0; s[i] != '=' && s[i]; i++)
1012 				;
1013 			if (s[i] == '=') {
1014 				s[i] = 0;
1015 				child_set_env(&env, &envsize, s, s + i + 1);
1016 			}
1017 			custom_environment = ce->next;
1018 			xfree(ce->s);
1019 			xfree(ce);
1020 		}
1021 	}
1022 
1023 	snprintf(buf, sizeof buf, "%.50s %d %d",
1024 	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1025 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1026 
1027 	if (s->ttyfd != -1)
1028 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1029 	if (s->term)
1030 		child_set_env(&env, &envsize, "TERM", s->term);
1031 	if (s->display)
1032 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1033 	if (original_command)
1034 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1035 		    original_command);
1036 
1037 #ifdef _AIX
1038 	{
1039 		char *cp;
1040 
1041 		if ((cp = getenv("AUTHSTATE")) != NULL)
1042 			child_set_env(&env, &envsize, "AUTHSTATE", cp);
1043 		if ((cp = getenv("KRB5CCNAME")) != NULL)
1044 			child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1045 		read_environment_file(&env, &envsize, "/etc/environment");
1046 	}
1047 #endif
1048 #ifdef KRB4
1049 	if (s->authctxt->krb4_ticket_file)
1050 		child_set_env(&env, &envsize, "KRBTKFILE",
1051 		    s->authctxt->krb4_ticket_file);
1052 #endif
1053 #ifdef KRB5
1054 	if (s->authctxt->krb5_ticket_file)
1055 		child_set_env(&env, &envsize, "KRB5CCNAME",
1056 		    s->authctxt->krb5_ticket_file);
1057 #endif
1058 #ifdef USE_PAM
1059 	/* Pull in any environment variables that may have been set by PAM. */
1060 	copy_environment(fetch_pam_environment(), &env, &envsize);
1061 #endif /* USE_PAM */
1062 
1063 	if (auth_sock_name != NULL)
1064 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1065 		    auth_sock_name);
1066 
1067 	/* read $HOME/.ssh/environment. */
1068 	if (!options.use_login) {
1069 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1070 		    pw->pw_dir);
1071 		read_environment_file(&env, &envsize, buf);
1072 	}
1073 	if (debug_flag) {
1074 		/* dump the environment */
1075 		fprintf(stderr, "Environment:\n");
1076 		for (i = 0; env[i]; i++)
1077 			fprintf(stderr, "  %.200s\n", env[i]);
1078 	}
1079 	return env;
1080 }
1081 
1082 /*
1083  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1084  * first in this order).
1085  */
1086 static void
1087 do_rc_files(Session *s, const char *shell)
1088 {
1089 	FILE *f = NULL;
1090 	char cmd[1024];
1091 	int do_xauth;
1092 	struct stat st;
1093 
1094 	do_xauth =
1095 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1096 
1097 	/* ignore _PATH_SSH_USER_RC for subsystems */
1098 	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1099 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1100 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1101 		if (debug_flag)
1102 			fprintf(stderr, "Running %s\n", cmd);
1103 		f = popen(cmd, "w");
1104 		if (f) {
1105 			if (do_xauth)
1106 				fprintf(f, "%s %s\n", s->auth_proto,
1107 				    s->auth_data);
1108 			pclose(f);
1109 		} else
1110 			fprintf(stderr, "Could not run %s\n",
1111 			    _PATH_SSH_USER_RC);
1112 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1113 		if (debug_flag)
1114 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1115 			    _PATH_SSH_SYSTEM_RC);
1116 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1117 		if (f) {
1118 			if (do_xauth)
1119 				fprintf(f, "%s %s\n", s->auth_proto,
1120 				    s->auth_data);
1121 			pclose(f);
1122 		} else
1123 			fprintf(stderr, "Could not run %s\n",
1124 			    _PATH_SSH_SYSTEM_RC);
1125 	} else if (do_xauth && options.xauth_location != NULL) {
1126 		/* Add authority data to .Xauthority if appropriate. */
1127 		if (debug_flag) {
1128 			fprintf(stderr,
1129 			    "Running %.500s add "
1130 			    "%.100s %.100s %.100s\n",
1131 			    options.xauth_location, s->auth_display,
1132 			    s->auth_proto, s->auth_data);
1133 		}
1134 		snprintf(cmd, sizeof cmd, "%s -q -",
1135 		    options.xauth_location);
1136 		f = popen(cmd, "w");
1137 		if (f) {
1138 			fprintf(f, "add %s %s %s\n",
1139 			    s->auth_display, s->auth_proto,
1140 			    s->auth_data);
1141 			pclose(f);
1142 		} else {
1143 			fprintf(stderr, "Could not run %s\n",
1144 			    cmd);
1145 		}
1146 	}
1147 }
1148 
1149 static void
1150 do_nologin(struct passwd *pw)
1151 {
1152 	FILE *f = NULL;
1153 	char buf[1024];
1154 
1155 #ifdef HAVE_LOGIN_CAP
1156 	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1157 		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1158 		    _PATH_NOLOGIN), "r");
1159 #else
1160 	if (pw->pw_uid)
1161 		f = fopen(_PATH_NOLOGIN, "r");
1162 #endif
1163 	if (f) {
1164 		/* /etc/nologin exists.  Print its contents and exit. */
1165 		while (fgets(buf, sizeof(buf), f))
1166 			fputs(buf, stderr);
1167 		fclose(f);
1168 		exit(254);
1169 	}
1170 }
1171 
1172 /* Set login name, uid, gid, and groups. */
1173 void
1174 do_setusercontext(struct passwd *pw)
1175 {
1176 	char tty='\0';
1177 
1178 #ifdef HAVE_CYGWIN
1179 	if (is_winnt) {
1180 #else /* HAVE_CYGWIN */
1181 	if (getuid() == 0 || geteuid() == 0) {
1182 #endif /* HAVE_CYGWIN */
1183 #ifdef HAVE_SETPCRED
1184 		setpcred(pw->pw_name);
1185 #endif /* HAVE_SETPCRED */
1186 #ifdef HAVE_LOGIN_CAP
1187 #ifdef __bsdi__
1188 		setpgid(0, 0);
1189 #endif
1190 		if (setusercontext(lc, pw, pw->pw_uid,
1191 		    (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1192 			perror("unable to set user context");
1193 			exit(1);
1194 		}
1195 #else
1196 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1197 		/* Sets login uid for accounting */
1198 		if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1199 			error("setluid: %s", strerror(errno));
1200 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1201 
1202 		if (setlogin(pw->pw_name) < 0)
1203 			error("setlogin failed: %s", strerror(errno));
1204 		if (setgid(pw->pw_gid) < 0) {
1205 			perror("setgid");
1206 			exit(1);
1207 		}
1208 		/* Initialize the group list. */
1209 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1210 			perror("initgroups");
1211 			exit(1);
1212 		}
1213 		endgrent();
1214 # ifdef USE_PAM
1215 		/*
1216 		 * PAM credentials may take the form of supplementary groups.
1217 		 * These will have been wiped by the above initgroups() call.
1218 		 * Reestablish them here.
1219 		 */
1220 		do_pam_setcred(0);
1221 # endif /* USE_PAM */
1222 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1223 		irix_setusercontext(pw);
1224 #  endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1225 # ifdef _AIX
1226 		/* XXX: Disable tty setting.  Enabled if required later */
1227 		aix_usrinfo(pw, &tty, -1);
1228 # endif /* _AIX */
1229 		/* Permanently switch to the desired uid. */
1230 		permanently_set_uid(pw);
1231 #endif
1232 	}
1233 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1234 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1235 }
1236 
1237 static void
1238 launch_login(struct passwd *pw, const char *hostname)
1239 {
1240 	/* Launch login(1). */
1241 
1242 	execl(LOGIN_PROGRAM, "login", "-h", hostname,
1243 #ifdef xxxLOGIN_NEEDS_TERM
1244 		    (s->term ? s->term : "unknown"),
1245 #endif /* LOGIN_NEEDS_TERM */
1246 #ifdef LOGIN_NO_ENDOPT
1247 	    "-p", "-f", pw->pw_name, (char *)NULL);
1248 #else
1249 	    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1250 #endif
1251 
1252 	/* Login couldn't be executed, die. */
1253 
1254 	perror("login");
1255 	exit(1);
1256 }
1257 
1258 /*
1259  * Performs common processing for the child, such as setting up the
1260  * environment, closing extra file descriptors, setting the user and group
1261  * ids, and executing the command or shell.
1262  */
1263 void
1264 do_child(Session *s, const char *command)
1265 {
1266 	extern char **environ;
1267 	char **env;
1268 	char *argv[10];
1269 	const char *shell, *shell0, *hostname = NULL;
1270 	struct passwd *pw = s->pw;
1271 	u_int i;
1272 
1273 	/* remove hostkey from the child's memory */
1274 	destroy_sensitive_data();
1275 
1276 	/* login(1) is only called if we execute the login shell */
1277 	if (options.use_login && command != NULL)
1278 		options.use_login = 0;
1279 
1280 	/*
1281 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1282 	 * switch, so we let login(1) to this for us.
1283 	 */
1284 	if (!options.use_login) {
1285 #ifdef HAVE_OSF_SIA
1286 		session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1287 		if (!check_quietlogin(s, command))
1288 			do_motd();
1289 #else /* HAVE_OSF_SIA */
1290 		do_nologin(pw);
1291 		do_setusercontext(pw);
1292 #endif /* HAVE_OSF_SIA */
1293 	}
1294 
1295 	/*
1296 	 * Get the shell from the password data.  An empty shell field is
1297 	 * legal, and means /bin/sh.
1298 	 */
1299 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1300 #ifdef HAVE_LOGIN_CAP
1301 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1302 #endif
1303 
1304 	env = do_setup_env(s, shell);
1305 
1306 	/* we have to stash the hostname before we close our socket. */
1307 	if (options.use_login)
1308 		hostname = get_remote_name_or_ip(utmp_len,
1309 		    options.verify_reverse_mapping);
1310 	/*
1311 	 * Close the connection descriptors; note that this is the child, and
1312 	 * the server will still have the socket open, and it is important
1313 	 * that we do not shutdown it.  Note that the descriptors cannot be
1314 	 * closed before building the environment, as we call
1315 	 * get_remote_ipaddr there.
1316 	 */
1317 	if (packet_get_connection_in() == packet_get_connection_out())
1318 		close(packet_get_connection_in());
1319 	else {
1320 		close(packet_get_connection_in());
1321 		close(packet_get_connection_out());
1322 	}
1323 	/*
1324 	 * Close all descriptors related to channels.  They will still remain
1325 	 * open in the parent.
1326 	 */
1327 	/* XXX better use close-on-exec? -markus */
1328 	channel_close_all();
1329 
1330 	/*
1331 	 * Close any extra file descriptors.  Note that there may still be
1332 	 * descriptors left by system functions.  They will be closed later.
1333 	 */
1334 	endpwent();
1335 
1336 	/*
1337 	 * Close any extra open file descriptors so that we don\'t have them
1338 	 * hanging around in clients.  Note that we want to do this after
1339 	 * initgroups, because at least on Solaris 2.3 it leaves file
1340 	 * descriptors open.
1341 	 */
1342 	for (i = 3; i < 64; i++)
1343 		close(i);
1344 
1345 	/*
1346 	 * Must take new environment into use so that .ssh/rc,
1347 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1348 	 */
1349 	environ = env;
1350 
1351 #ifdef AFS
1352 	/* Try to get AFS tokens for the local cell. */
1353 	if (k_hasafs()) {
1354 		char cell[64];
1355 
1356 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1357 			krb_afslog(cell, 0);
1358 
1359 		krb_afslog(0, 0);
1360 	}
1361 #endif /* AFS */
1362 
1363 	/* Change current directory to the user\'s home directory. */
1364 	if (chdir(pw->pw_dir) < 0) {
1365 		fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1366 		    pw->pw_dir, strerror(errno));
1367 #ifdef HAVE_LOGIN_CAP
1368 		if (login_getcapbool(lc, "requirehome", 0))
1369 			exit(1);
1370 #endif
1371 	}
1372 
1373 	if (!options.use_login)
1374 		do_rc_files(s, shell);
1375 
1376 	/* restore SIGPIPE for child */
1377 	signal(SIGPIPE,  SIG_DFL);
1378 
1379 	if (options.use_login) {
1380 		launch_login(pw, hostname);
1381 		/* NEVERREACHED */
1382 	}
1383 
1384 	/* Get the last component of the shell name. */
1385 	if ((shell0 = strrchr(shell, '/')) != NULL)
1386 		shell0++;
1387 	else
1388 		shell0 = shell;
1389 
1390 	/*
1391 	 * If we have no command, execute the shell.  In this case, the shell
1392 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1393 	 * this is a login shell.
1394 	 */
1395 	if (!command) {
1396 		char argv0[256];
1397 
1398 		/* Start the shell.  Set initial character to '-'. */
1399 		argv0[0] = '-';
1400 
1401 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1402 		    >= sizeof(argv0) - 1) {
1403 			errno = EINVAL;
1404 			perror(shell);
1405 			exit(1);
1406 		}
1407 
1408 		/* Execute the shell. */
1409 		argv[0] = argv0;
1410 		argv[1] = NULL;
1411 		execve(shell, argv, env);
1412 
1413 		/* Executing the shell failed. */
1414 		perror(shell);
1415 		exit(1);
1416 	}
1417 	/*
1418 	 * Execute the command using the user's shell.  This uses the -c
1419 	 * option to execute the command.
1420 	 */
1421 	argv[0] = (char *) shell0;
1422 	argv[1] = "-c";
1423 	argv[2] = (char *) command;
1424 	argv[3] = NULL;
1425 	execve(shell, argv, env);
1426 	perror(shell);
1427 	exit(1);
1428 }
1429 
1430 Session *
1431 session_new(void)
1432 {
1433 	int i;
1434 	static int did_init = 0;
1435 	if (!did_init) {
1436 		debug("session_new: init");
1437 		for (i = 0; i < MAX_SESSIONS; i++) {
1438 			sessions[i].used = 0;
1439 		}
1440 		did_init = 1;
1441 	}
1442 	for (i = 0; i < MAX_SESSIONS; i++) {
1443 		Session *s = &sessions[i];
1444 		if (! s->used) {
1445 			memset(s, 0, sizeof(*s));
1446 			s->chanid = -1;
1447 			s->ptyfd = -1;
1448 			s->ttyfd = -1;
1449 			s->used = 1;
1450 			s->self = i;
1451 			debug("session_new: session %d", i);
1452 			return s;
1453 		}
1454 	}
1455 	return NULL;
1456 }
1457 
1458 static void
1459 session_dump(void)
1460 {
1461 	int i;
1462 	for (i = 0; i < MAX_SESSIONS; i++) {
1463 		Session *s = &sessions[i];
1464 		debug("dump: used %d session %d %p channel %d pid %ld",
1465 		    s->used,
1466 		    s->self,
1467 		    s,
1468 		    s->chanid,
1469 		    (long)s->pid);
1470 	}
1471 }
1472 
1473 int
1474 session_open(Authctxt *authctxt, int chanid)
1475 {
1476 	Session *s = session_new();
1477 	debug("session_open: channel %d", chanid);
1478 	if (s == NULL) {
1479 		error("no more sessions");
1480 		return 0;
1481 	}
1482 	s->authctxt = authctxt;
1483 	s->pw = authctxt->pw;
1484 	if (s->pw == NULL)
1485 		fatal("no user for session %d", s->self);
1486 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1487 	s->chanid = chanid;
1488 	return 1;
1489 }
1490 
1491 Session *
1492 session_by_tty(char *tty)
1493 {
1494 	int i;
1495 	for (i = 0; i < MAX_SESSIONS; i++) {
1496 		Session *s = &sessions[i];
1497 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1498 			debug("session_by_tty: session %d tty %s", i, tty);
1499 			return s;
1500 		}
1501 	}
1502 	debug("session_by_tty: unknown tty %.100s", tty);
1503 	session_dump();
1504 	return NULL;
1505 }
1506 
1507 static Session *
1508 session_by_channel(int id)
1509 {
1510 	int i;
1511 	for (i = 0; i < MAX_SESSIONS; i++) {
1512 		Session *s = &sessions[i];
1513 		if (s->used && s->chanid == id) {
1514 			debug("session_by_channel: session %d channel %d", i, id);
1515 			return s;
1516 		}
1517 	}
1518 	debug("session_by_channel: unknown channel %d", id);
1519 	session_dump();
1520 	return NULL;
1521 }
1522 
1523 static Session *
1524 session_by_pid(pid_t pid)
1525 {
1526 	int i;
1527 	debug("session_by_pid: pid %ld", (long)pid);
1528 	for (i = 0; i < MAX_SESSIONS; i++) {
1529 		Session *s = &sessions[i];
1530 		if (s->used && s->pid == pid)
1531 			return s;
1532 	}
1533 	error("session_by_pid: unknown pid %ld", (long)pid);
1534 	session_dump();
1535 	return NULL;
1536 }
1537 
1538 static int
1539 session_window_change_req(Session *s)
1540 {
1541 	s->col = packet_get_int();
1542 	s->row = packet_get_int();
1543 	s->xpixel = packet_get_int();
1544 	s->ypixel = packet_get_int();
1545 	packet_check_eom();
1546 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1547 	return 1;
1548 }
1549 
1550 static int
1551 session_pty_req(Session *s)
1552 {
1553 	u_int len;
1554 	int n_bytes;
1555 
1556 	if (no_pty_flag) {
1557 		debug("Allocating a pty not permitted for this authentication.");
1558 		return 0;
1559 	}
1560 	if (s->ttyfd != -1) {
1561 		packet_disconnect("Protocol error: you already have a pty.");
1562 		return 0;
1563 	}
1564 	/* Get the time and hostname when the user last logged in. */
1565 	if (options.print_lastlog) {
1566 		s->hostname[0] = '\0';
1567 		s->last_login_time = get_last_login_time(s->pw->pw_uid,
1568 		    s->pw->pw_name, s->hostname, sizeof(s->hostname));
1569 	}
1570 
1571 	s->term = packet_get_string(&len);
1572 
1573 	if (compat20) {
1574 		s->col = packet_get_int();
1575 		s->row = packet_get_int();
1576 	} else {
1577 		s->row = packet_get_int();
1578 		s->col = packet_get_int();
1579 	}
1580 	s->xpixel = packet_get_int();
1581 	s->ypixel = packet_get_int();
1582 
1583 	if (strcmp(s->term, "") == 0) {
1584 		xfree(s->term);
1585 		s->term = NULL;
1586 	}
1587 
1588 	/* Allocate a pty and open it. */
1589 	debug("Allocating pty.");
1590 	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1591 		if (s->term)
1592 			xfree(s->term);
1593 		s->term = NULL;
1594 		s->ptyfd = -1;
1595 		s->ttyfd = -1;
1596 		error("session_pty_req: session %d alloc failed", s->self);
1597 		return 0;
1598 	}
1599 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1600 
1601 	/* for SSH1 the tty modes length is not given */
1602 	if (!compat20)
1603 		n_bytes = packet_remaining();
1604 	tty_parse_modes(s->ttyfd, &n_bytes);
1605 
1606 	/*
1607 	 * Add a cleanup function to clear the utmp entry and record logout
1608 	 * time in case we call fatal() (e.g., the connection gets closed).
1609 	 */
1610 	fatal_add_cleanup(session_pty_cleanup, (void *)s);
1611 	if (!use_privsep)
1612 		pty_setowner(s->pw, s->tty);
1613 
1614 	/* Set window size from the packet. */
1615 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1616 
1617 	packet_check_eom();
1618 	session_proctitle(s);
1619 	return 1;
1620 }
1621 
1622 static int
1623 session_subsystem_req(Session *s)
1624 {
1625 	struct stat st;
1626 	u_int len;
1627 	int success = 0;
1628 	char *cmd, *subsys = packet_get_string(&len);
1629 	int i;
1630 
1631 	packet_check_eom();
1632 	log("subsystem request for %.100s", subsys);
1633 
1634 	for (i = 0; i < options.num_subsystems; i++) {
1635 		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1636 			cmd = options.subsystem_command[i];
1637 			if (stat(cmd, &st) < 0) {
1638 				error("subsystem: cannot stat %s: %s", cmd,
1639 				    strerror(errno));
1640 				break;
1641 			}
1642 			debug("subsystem: exec() %s", cmd);
1643 			s->is_subsystem = 1;
1644 			do_exec(s, cmd);
1645 			success = 1;
1646 			break;
1647 		}
1648 	}
1649 
1650 	if (!success)
1651 		log("subsystem request for %.100s failed, subsystem not found",
1652 		    subsys);
1653 
1654 	xfree(subsys);
1655 	return success;
1656 }
1657 
1658 static int
1659 session_x11_req(Session *s)
1660 {
1661 	int success;
1662 
1663 	s->single_connection = packet_get_char();
1664 	s->auth_proto = packet_get_string(NULL);
1665 	s->auth_data = packet_get_string(NULL);
1666 	s->screen = packet_get_int();
1667 	packet_check_eom();
1668 
1669 	success = session_setup_x11fwd(s);
1670 	if (!success) {
1671 		xfree(s->auth_proto);
1672 		xfree(s->auth_data);
1673 		s->auth_proto = NULL;
1674 		s->auth_data = NULL;
1675 	}
1676 	return success;
1677 }
1678 
1679 static int
1680 session_shell_req(Session *s)
1681 {
1682 	packet_check_eom();
1683 	do_exec(s, NULL);
1684 	return 1;
1685 }
1686 
1687 static int
1688 session_exec_req(Session *s)
1689 {
1690 	u_int len;
1691 	char *command = packet_get_string(&len);
1692 	packet_check_eom();
1693 	do_exec(s, command);
1694 	xfree(command);
1695 	return 1;
1696 }
1697 
1698 static int
1699 session_auth_agent_req(Session *s)
1700 {
1701 	static int called = 0;
1702 	packet_check_eom();
1703 	if (no_agent_forwarding_flag) {
1704 		debug("session_auth_agent_req: no_agent_forwarding_flag");
1705 		return 0;
1706 	}
1707 	if (called) {
1708 		return 0;
1709 	} else {
1710 		called = 1;
1711 		return auth_input_request_forwarding(s->pw);
1712 	}
1713 }
1714 
1715 int
1716 session_input_channel_req(Channel *c, const char *rtype)
1717 {
1718 	int success = 0;
1719 	Session *s;
1720 
1721 	if ((s = session_by_channel(c->self)) == NULL) {
1722 		log("session_input_channel_req: no session %d req %.100s",
1723 		    c->self, rtype);
1724 		return 0;
1725 	}
1726 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
1727 
1728 	/*
1729 	 * a session is in LARVAL state until a shell, a command
1730 	 * or a subsystem is executed
1731 	 */
1732 	if (c->type == SSH_CHANNEL_LARVAL) {
1733 		if (strcmp(rtype, "shell") == 0) {
1734 			success = session_shell_req(s);
1735 		} else if (strcmp(rtype, "exec") == 0) {
1736 			success = session_exec_req(s);
1737 		} else if (strcmp(rtype, "pty-req") == 0) {
1738 			success =  session_pty_req(s);
1739 		} else if (strcmp(rtype, "x11-req") == 0) {
1740 			success = session_x11_req(s);
1741 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1742 			success = session_auth_agent_req(s);
1743 		} else if (strcmp(rtype, "subsystem") == 0) {
1744 			success = session_subsystem_req(s);
1745 		}
1746 	}
1747 	if (strcmp(rtype, "window-change") == 0) {
1748 		success = session_window_change_req(s);
1749 	}
1750 	return success;
1751 }
1752 
1753 void
1754 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1755 {
1756 	if (!compat20)
1757 		fatal("session_set_fds: called for proto != 2.0");
1758 	/*
1759 	 * now that have a child and a pipe to the child,
1760 	 * we can activate our channel and register the fd's
1761 	 */
1762 	if (s->chanid == -1)
1763 		fatal("no channel for session %d", s->self);
1764 	channel_set_fds(s->chanid,
1765 	    fdout, fdin, fderr,
1766 	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1767 	    1,
1768 	    CHAN_SES_WINDOW_DEFAULT);
1769 }
1770 
1771 /*
1772  * Function to perform pty cleanup. Also called if we get aborted abnormally
1773  * (e.g., due to a dropped connection).
1774  */
1775 void
1776 session_pty_cleanup2(void *session)
1777 {
1778 	Session *s = session;
1779 
1780 	if (s == NULL) {
1781 		error("session_pty_cleanup: no session");
1782 		return;
1783 	}
1784 	if (s->ttyfd == -1)
1785 		return;
1786 
1787 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1788 
1789 	/* Record that the user has logged out. */
1790 	if (s->pid != 0)
1791 		record_logout(s->pid, s->tty, s->pw->pw_name);
1792 
1793 	/* Release the pseudo-tty. */
1794 	if (getuid() == 0)
1795 		pty_release(s->tty);
1796 
1797 	/*
1798 	 * Close the server side of the socket pairs.  We must do this after
1799 	 * the pty cleanup, so that another process doesn't get this pty
1800 	 * while we're still cleaning up.
1801 	 */
1802 	if (close(s->ptymaster) < 0)
1803 		error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1804 
1805 	/* unlink pty from session */
1806 	s->ttyfd = -1;
1807 }
1808 
1809 void
1810 session_pty_cleanup(void *session)
1811 {
1812 	PRIVSEP(session_pty_cleanup2(session));
1813 }
1814 
1815 static void
1816 session_exit_message(Session *s, int status)
1817 {
1818 	Channel *c;
1819 
1820 	if ((c = channel_lookup(s->chanid)) == NULL)
1821 		fatal("session_exit_message: session %d: no channel %d",
1822 		    s->self, s->chanid);
1823 	debug("session_exit_message: session %d channel %d pid %ld",
1824 	    s->self, s->chanid, (long)s->pid);
1825 
1826 	if (WIFEXITED(status)) {
1827 		channel_request_start(s->chanid, "exit-status", 0);
1828 		packet_put_int(WEXITSTATUS(status));
1829 		packet_send();
1830 	} else if (WIFSIGNALED(status)) {
1831 		channel_request_start(s->chanid, "exit-signal", 0);
1832 		packet_put_int(WTERMSIG(status));
1833 #ifdef WCOREDUMP
1834 		packet_put_char(WCOREDUMP(status));
1835 #else /* WCOREDUMP */
1836 		packet_put_char(0);
1837 #endif /* WCOREDUMP */
1838 		packet_put_cstring("");
1839 		packet_put_cstring("");
1840 		packet_send();
1841 	} else {
1842 		/* Some weird exit cause.  Just exit. */
1843 		packet_disconnect("wait returned status %04x.", status);
1844 	}
1845 
1846 	/* disconnect channel */
1847 	debug("session_exit_message: release channel %d", s->chanid);
1848 	channel_cancel_cleanup(s->chanid);
1849 	/*
1850 	 * emulate a write failure with 'chan_write_failed', nobody will be
1851 	 * interested in data we write.
1852 	 * Note that we must not call 'chan_read_failed', since there could
1853 	 * be some more data waiting in the pipe.
1854 	 */
1855 	if (c->ostate != CHAN_OUTPUT_CLOSED)
1856 		chan_write_failed(c);
1857 	s->chanid = -1;
1858 }
1859 
1860 void
1861 session_close(Session *s)
1862 {
1863 	debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1864 	if (s->ttyfd != -1) {
1865 		fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1866 		session_pty_cleanup(s);
1867 	}
1868 	if (s->term)
1869 		xfree(s->term);
1870 	if (s->display)
1871 		xfree(s->display);
1872 	if (s->auth_display)
1873 		xfree(s->auth_display);
1874 	if (s->auth_data)
1875 		xfree(s->auth_data);
1876 	if (s->auth_proto)
1877 		xfree(s->auth_proto);
1878 	s->used = 0;
1879 	session_proctitle(s);
1880 }
1881 
1882 void
1883 session_close_by_pid(pid_t pid, int status)
1884 {
1885 	Session *s = session_by_pid(pid);
1886 	if (s == NULL) {
1887 		debug("session_close_by_pid: no session for pid %ld",
1888 		    (long)pid);
1889 		return;
1890 	}
1891 	if (s->chanid != -1)
1892 		session_exit_message(s, status);
1893 	session_close(s);
1894 }
1895 
1896 /*
1897  * this is called when a channel dies before
1898  * the session 'child' itself dies
1899  */
1900 void
1901 session_close_by_channel(int id, void *arg)
1902 {
1903 	Session *s = session_by_channel(id);
1904 	if (s == NULL) {
1905 		debug("session_close_by_channel: no session for id %d", id);
1906 		return;
1907 	}
1908 	debug("session_close_by_channel: channel %d child %ld",
1909 	    id, (long)s->pid);
1910 	if (s->pid != 0) {
1911 		debug("session_close_by_channel: channel %d: has child", id);
1912 		/*
1913 		 * delay detach of session, but release pty, since
1914 		 * the fd's to the child are already closed
1915 		 */
1916 		if (s->ttyfd != -1) {
1917 			fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1918 			session_pty_cleanup(s);
1919 		}
1920 		return;
1921 	}
1922 	/* detach by removing callback */
1923 	channel_cancel_cleanup(s->chanid);
1924 	s->chanid = -1;
1925 	session_close(s);
1926 }
1927 
1928 void
1929 session_destroy_all(void (*closefunc)(Session *))
1930 {
1931 	int i;
1932 	for (i = 0; i < MAX_SESSIONS; i++) {
1933 		Session *s = &sessions[i];
1934 		if (s->used) {
1935 			if (closefunc != NULL)
1936 				closefunc(s);
1937 			else
1938 				session_close(s);
1939 		}
1940 	}
1941 }
1942 
1943 static char *
1944 session_tty_list(void)
1945 {
1946 	static char buf[1024];
1947 	int i;
1948 	buf[0] = '\0';
1949 	for (i = 0; i < MAX_SESSIONS; i++) {
1950 		Session *s = &sessions[i];
1951 		if (s->used && s->ttyfd != -1) {
1952 			if (buf[0] != '\0')
1953 				strlcat(buf, ",", sizeof buf);
1954 			strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1955 		}
1956 	}
1957 	if (buf[0] == '\0')
1958 		strlcpy(buf, "notty", sizeof buf);
1959 	return buf;
1960 }
1961 
1962 void
1963 session_proctitle(Session *s)
1964 {
1965 	if (s->pw == NULL)
1966 		error("no user for session %d", s->self);
1967 	else
1968 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1969 }
1970 
1971 int
1972 session_setup_x11fwd(Session *s)
1973 {
1974 	struct stat st;
1975 	char display[512], auth_display[512];
1976 	char hostname[MAXHOSTNAMELEN];
1977 
1978 	if (no_x11_forwarding_flag) {
1979 		packet_send_debug("X11 forwarding disabled in user configuration file.");
1980 		return 0;
1981 	}
1982 	if (!options.x11_forwarding) {
1983 		debug("X11 forwarding disabled in server configuration file.");
1984 		return 0;
1985 	}
1986 	if (!options.xauth_location ||
1987 	    (stat(options.xauth_location, &st) == -1)) {
1988 		packet_send_debug("No xauth program; cannot forward with spoofing.");
1989 		return 0;
1990 	}
1991 	if (options.use_login) {
1992 		packet_send_debug("X11 forwarding disabled; "
1993 		    "not compatible with UseLogin=yes.");
1994 		return 0;
1995 	}
1996 	if (s->display != NULL) {
1997 		debug("X11 display already set.");
1998 		return 0;
1999 	}
2000 	if (x11_create_display_inet(options.x11_display_offset,
2001 	    options.x11_use_localhost, s->single_connection,
2002 	    &s->display_number) == -1) {
2003 		debug("x11_create_display_inet failed.");
2004 		return 0;
2005 	}
2006 
2007 	/* Set up a suitable value for the DISPLAY variable. */
2008 	if (gethostname(hostname, sizeof(hostname)) < 0)
2009 		fatal("gethostname: %.100s", strerror(errno));
2010 	/*
2011 	 * auth_display must be used as the displayname when the
2012 	 * authorization entry is added with xauth(1).  This will be
2013 	 * different than the DISPLAY string for localhost displays.
2014 	 */
2015 	if (options.x11_use_localhost) {
2016 		snprintf(display, sizeof display, "localhost:%u.%u",
2017 		    s->display_number, s->screen);
2018 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2019 		    s->display_number, s->screen);
2020 		s->display = xstrdup(display);
2021 		s->auth_display = xstrdup(auth_display);
2022 	} else {
2023 #ifdef IPADDR_IN_DISPLAY
2024 		struct hostent *he;
2025 		struct in_addr my_addr;
2026 
2027 		he = gethostbyname(hostname);
2028 		if (he == NULL) {
2029 			error("Can't get IP address for X11 DISPLAY.");
2030 			packet_send_debug("Can't get IP address for X11 DISPLAY.");
2031 			return 0;
2032 		}
2033 		memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2034 		snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2035 		    s->display_number, s->screen);
2036 #else
2037 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2038 		    s->display_number, s->screen);
2039 #endif
2040 		s->display = xstrdup(display);
2041 		s->auth_display = xstrdup(display);
2042 	}
2043 
2044 	return 1;
2045 }
2046 
2047 static void
2048 do_authenticated2(Authctxt *authctxt)
2049 {
2050 	server_loop2(authctxt);
2051 }
2052