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