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