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