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