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