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