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