1 /* $OpenBSD: session.c,v 1.286 2016/11/30 03:00:05 djm Exp $ */
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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".
12 * SSH2 support by Markus Friedl.
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
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.
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.
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
44 #include <sys/socket.h>
48 #include <arpa/inet.h>
67 #include "openbsd-compat/sys-queue.h"
85 #include "auth-options.h"
87 #include "pathnames.h"
92 #include "serverloop.h"
96 #include "monitor_wrap.h"
99 #if defined(KRB5) && defined(USE_AFS)
104 #include <selinux/selinux.h>
107 #define IS_INTERNAL_SFTP(c) \
108 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
109 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
110 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
111 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
115 Session *session_new(void);
116 void session_set_fds(Session *, int, int, int, int, int);
117 void session_pty_cleanup(Session *);
118 void session_proctitle(Session *);
119 int session_setup_x11fwd(Session *);
120 int do_exec_pty(Session *, const char *);
121 int do_exec_no_pty(Session *, const char *);
122 int do_exec(Session *, const char *);
123 void do_login(Session *, const char *);
124 #ifdef LOGIN_NEEDS_UTMPX
125 static void do_pre_login(Session *s);
127 void do_child(Session *, const char *);
129 int check_quietlogin(Session *, const char *);
131 static void do_authenticated2(Authctxt *);
133 static int session_pty_req(Session *);
136 extern ServerOptions options;
137 extern char *__progname;
138 extern int log_stderr;
139 extern int debug_flag;
140 extern u_int utmp_len;
141 extern int startup_pipe;
142 extern void destroy_sensitive_data(void);
143 extern Buffer loginmsg;
145 /* original command from peer. */
146 const char *original_command = NULL;
149 static int sessions_first_unused = -1;
150 static int sessions_nalloc = 0;
151 static Session *sessions = NULL;
153 #define SUBSYSTEM_NONE 0
154 #define SUBSYSTEM_EXT 1
155 #define SUBSYSTEM_INT_SFTP 2
156 #define SUBSYSTEM_INT_SFTP_ERROR 3
158 #ifdef HAVE_LOGIN_CAP
162 static int is_child = 0;
163 static int in_chroot = 0;
165 /* Name and directory of socket for authentication agent forwarding. */
166 static char *auth_sock_name = NULL;
167 static char *auth_sock_dir = NULL;
169 /* removes the agent forwarding socket */
172 auth_sock_cleanup_proc(struct passwd *pw)
174 if (auth_sock_name != NULL) {
175 temporarily_use_uid(pw);
176 unlink(auth_sock_name);
177 rmdir(auth_sock_dir);
178 auth_sock_name = NULL;
184 auth_input_request_forwarding(struct passwd * pw)
189 if (auth_sock_name != NULL) {
190 error("authentication forwarding requested twice.");
194 /* Temporarily drop privileged uid for mkdir/bind. */
195 temporarily_use_uid(pw);
197 /* Allocate a buffer for the socket name, and format the name. */
198 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
200 /* Create private directory for socket */
201 if (mkdtemp(auth_sock_dir) == NULL) {
202 packet_send_debug("Agent forwarding disabled: "
203 "mkdtemp() failed: %.100s", strerror(errno));
206 auth_sock_dir = NULL;
210 xasprintf(&auth_sock_name, "%s/agent.%ld",
211 auth_sock_dir, (long) getpid());
213 /* Start a Unix listener on auth_sock_name. */
214 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
216 /* Restore the privileged uid. */
219 /* Check for socket/bind/listen failure. */
223 /* Allocate a channel for the authentication agent socket. */
224 nc = channel_new("auth socket",
225 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
226 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
227 0, "auth socket", 1);
228 nc->path = xstrdup(auth_sock_name);
232 free(auth_sock_name);
233 if (auth_sock_dir != NULL) {
234 rmdir(auth_sock_dir);
239 auth_sock_name = NULL;
240 auth_sock_dir = NULL;
245 display_loginmsg(void)
247 if (buffer_len(&loginmsg) > 0) {
248 buffer_append(&loginmsg, "\0", 1);
249 printf("%s", (char *)buffer_ptr(&loginmsg));
250 buffer_clear(&loginmsg);
255 do_authenticated(Authctxt *authctxt)
257 setproctitle("%s", authctxt->pw->pw_name);
259 /* setup the channel layer */
260 /* XXX - streamlocal? */
261 if (no_port_forwarding_flag || options.disable_forwarding ||
262 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
263 channel_disable_adm_local_opens();
265 channel_permit_all_opens();
269 do_authenticated2(authctxt);
270 do_cleanup(authctxt);
273 /* Check untrusted xauth strings for metacharacters */
275 xauth_valid_string(const char *s)
279 for (i = 0; s[i] != '\0'; i++) {
280 if (!isalnum((u_char)s[i]) &&
281 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
282 s[i] != '-' && s[i] != '_')
290 * This is called to fork and execute a command when we have no tty. This
291 * will call do_child from the child, and server_loop from the parent after
292 * setting up file descriptors and such.
295 do_exec_no_pty(Session *s, const char *command)
300 int pin[2], pout[2], perr[2];
303 fatal("do_exec_no_pty: no session");
305 /* Allocate pipes for communicating with the program. */
307 error("%s: pipe in: %.100s", __func__, strerror(errno));
310 if (pipe(pout) < 0) {
311 error("%s: pipe out: %.100s", __func__, strerror(errno));
316 if (pipe(perr) < 0) {
317 error("%s: pipe err: %.100s", __func__,
326 int inout[2], err[2];
329 fatal("do_exec_no_pty: no session");
331 /* Uses socket pairs to communicate with the program. */
332 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
333 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
336 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
337 error("%s: socketpair #2: %.100s", __func__,
345 session_proctitle(s);
347 /* Fork the child. */
348 switch ((pid = fork())) {
350 error("%s: fork: %.100s", __func__, strerror(errno));
368 /* Child. Reinitialize the log since the pid has changed. */
369 log_init(__progname, options.log_level,
370 options.log_facility, log_stderr);
373 * Create a new session and process group since the 4.4BSD
374 * setlogin() affects the entire process group.
377 error("setsid failed: %.100s", strerror(errno));
381 * Redirect stdin. We close the parent side of the socket
382 * pair, and make the child side the standard input.
385 if (dup2(pin[0], 0) < 0)
386 perror("dup2 stdin");
389 /* Redirect stdout. */
391 if (dup2(pout[1], 1) < 0)
392 perror("dup2 stdout");
395 /* Redirect stderr. */
397 if (dup2(perr[1], 2) < 0)
398 perror("dup2 stderr");
402 * Redirect stdin, stdout, and stderr. Stdin and stdout will
403 * use the same socket, as some programs (particularly rdist)
404 * seem to depend on it.
408 if (dup2(inout[0], 0) < 0) /* stdin */
409 perror("dup2 stdin");
410 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
411 perror("dup2 stdout");
413 if (dup2(err[0], 2) < 0) /* stderr */
414 perror("dup2 stderr");
420 cray_init_job(s->pw); /* set up cray jid and tmpdir */
423 /* Do processing for the child (exec command etc). */
424 do_child(s, command);
431 signal(WJSIGNAL, cray_job_termination_handler);
434 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
438 /* Set interactive/non-interactive mode. */
439 packet_set_interactive(s->display != NULL,
440 options.ip_qos_interactive, options.ip_qos_bulk);
443 * Clear loginmsg, since it's the child's responsibility to display
444 * it to the user, otherwise multiple sessions may accumulate
445 * multiple copies of the login messages.
447 buffer_clear(&loginmsg);
450 /* We are the parent. Close the child sides of the pipes. */
455 session_set_fds(s, pin[1], pout[0], perr[0],
458 /* We are the parent. Close the child sides of the socket pairs. */
463 * Enter the interactive session. Note: server_loop must be able to
464 * handle the case that fdin and fdout are the same.
466 session_set_fds(s, inout[1], inout[1], err[1],
473 * This is called to fork and execute a command when we have a tty. This
474 * will call do_child from the child, and server_loop from the parent after
475 * setting up file descriptors, controlling tty, updating wtmp, utmp,
476 * lastlog, and other such operations.
479 do_exec_pty(Session *s, const char *command)
481 int fdout, ptyfd, ttyfd, ptymaster;
485 fatal("do_exec_pty: no session");
490 * Create another descriptor of the pty master side for use as the
491 * standard input. We could use the original descriptor, but this
492 * simplifies code in server_loop. The descriptor is bidirectional.
493 * Do this before forking (and cleanup in the child) so as to
494 * detect and gracefully fail out-of-fd conditions.
496 if ((fdout = dup(ptyfd)) < 0) {
497 error("%s: dup #1: %s", __func__, strerror(errno));
502 /* we keep a reference to the pty master */
503 if ((ptymaster = dup(ptyfd)) < 0) {
504 error("%s: dup #2: %s", __func__, strerror(errno));
511 /* Fork the child. */
512 switch ((pid = fork())) {
514 error("%s: fork: %.100s", __func__, strerror(errno));
526 /* Child. Reinitialize the log because the pid has changed. */
527 log_init(__progname, options.log_level,
528 options.log_facility, log_stderr);
529 /* Close the master side of the pseudo tty. */
532 /* Make the pseudo tty our controlling tty. */
533 pty_make_controlling_tty(&ttyfd, s->tty);
535 /* Redirect stdin/stdout/stderr from the pseudo tty. */
536 if (dup2(ttyfd, 0) < 0)
537 error("dup2 stdin: %s", strerror(errno));
538 if (dup2(ttyfd, 1) < 0)
539 error("dup2 stdout: %s", strerror(errno));
540 if (dup2(ttyfd, 2) < 0)
541 error("dup2 stderr: %s", strerror(errno));
543 /* Close the extra descriptor for the pseudo tty. */
546 /* record login, etc. similar to login(1) */
548 cray_init_job(s->pw); /* set up cray jid and tmpdir */
551 do_login(s, command);
554 * Do common processing for the child, such as execing
557 do_child(s, command);
564 signal(WJSIGNAL, cray_job_termination_handler);
567 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
572 /* Parent. Close the slave side of the pseudo tty. */
575 /* Enter interactive session. */
576 s->ptymaster = ptymaster;
577 packet_set_interactive(1,
578 options.ip_qos_interactive, options.ip_qos_bulk);
579 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
583 #ifdef LOGIN_NEEDS_UTMPX
585 do_pre_login(Session *s)
587 struct ssh *ssh = active_state; /* XXX */
589 struct sockaddr_storage from;
590 pid_t pid = getpid();
593 * Get IP address of client. If the connection is not a socket, let
594 * the address be 0.0.0.0.
596 memset(&from, 0, sizeof(from));
597 fromlen = sizeof(from);
598 if (packet_connection_is_on_socket()) {
599 if (getpeername(packet_get_connection_in(),
600 (struct sockaddr *)&from, &fromlen) < 0) {
601 debug("getpeername: %.100s", strerror(errno));
606 record_utmp_only(pid, s->tty, s->pw->pw_name,
607 session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
608 (struct sockaddr *)&from, fromlen);
613 * This is called to fork and execute a command. If another command is
614 * to be forced, execute that instead.
617 do_exec(Session *s, const char *command)
619 struct ssh *ssh = active_state; /* XXX */
621 const char *forced = NULL, *tty = NULL;
622 char session_type[1024];
624 if (options.adm_forced_command) {
625 original_command = command;
626 command = options.adm_forced_command;
628 } else if (forced_command) {
629 original_command = command;
630 command = forced_command;
631 forced = "(key-option)";
633 if (forced != NULL) {
634 if (IS_INTERNAL_SFTP(command)) {
635 s->is_subsystem = s->is_subsystem ?
636 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
637 } else if (s->is_subsystem)
638 s->is_subsystem = SUBSYSTEM_EXT;
639 snprintf(session_type, sizeof(session_type),
640 "forced-command %s '%.900s'", forced, command);
641 } else if (s->is_subsystem) {
642 snprintf(session_type, sizeof(session_type),
643 "subsystem '%.900s'", s->subsys);
644 } else if (command == NULL) {
645 snprintf(session_type, sizeof(session_type), "shell");
647 /* NB. we don't log unforced commands to preserve privacy */
648 snprintf(session_type, sizeof(session_type), "command");
651 if (s->ttyfd != -1) {
653 if (strncmp(tty, "/dev/", 5) == 0)
657 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
659 tty == NULL ? "" : " on ",
660 tty == NULL ? "" : tty,
662 ssh_remote_ipaddr(ssh),
663 ssh_remote_port(ssh),
666 #ifdef SSH_AUDIT_EVENTS
668 PRIVSEP(audit_run_command(command));
669 else if (s->ttyfd == -1) {
670 char *shell = s->pw->pw_shell;
672 if (shell[0] == '\0') /* empty shell means /bin/sh */
674 PRIVSEP(audit_run_command(shell));
678 ret = do_exec_pty(s, command);
680 ret = do_exec_no_pty(s, command);
682 original_command = NULL;
685 * Clear loginmsg: it's the child's responsibility to display
686 * it to the user, otherwise multiple sessions may accumulate
687 * multiple copies of the login messages.
689 buffer_clear(&loginmsg);
694 /* administrative, login(1)-like work */
696 do_login(Session *s, const char *command)
698 struct ssh *ssh = active_state; /* XXX */
700 struct sockaddr_storage from;
701 struct passwd * pw = s->pw;
702 pid_t pid = getpid();
705 * Get IP address of client. If the connection is not a socket, let
706 * the address be 0.0.0.0.
708 memset(&from, 0, sizeof(from));
709 fromlen = sizeof(from);
710 if (packet_connection_is_on_socket()) {
711 if (getpeername(packet_get_connection_in(),
712 (struct sockaddr *)&from, &fromlen) < 0) {
713 debug("getpeername: %.100s", strerror(errno));
718 /* Record that there was a login on that tty from the remote host. */
720 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
721 session_get_remote_name_or_ip(ssh, utmp_len,
723 (struct sockaddr *)&from, fromlen);
727 * If password change is needed, do it now.
728 * This needs to occur before the ~/.hushlogin check.
730 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
733 s->authctxt->force_pwchange = 0;
734 /* XXX - signal [net] parent to enable forwardings */
738 if (check_quietlogin(s, command))
747 * Display the message of the day.
755 if (options.print_motd) {
756 #ifdef HAVE_LOGIN_CAP
757 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
760 f = fopen("/etc/motd", "r");
763 while (fgets(buf, sizeof(buf), f))
772 * Check for quiet login, either .hushlogin or command given.
775 check_quietlogin(Session *s, const char *command)
778 struct passwd *pw = s->pw;
781 /* Return 1 if .hushlogin exists or a command given. */
784 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
785 #ifdef HAVE_LOGIN_CAP
786 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
789 if (stat(buf, &st) >= 0)
796 * Sets the value of the given variable in the environment. If the variable
797 * already exists, its value is overridden.
800 child_set_env(char ***envp, u_int *envsizep, const char *name,
807 if (strchr(name, '=') != NULL) {
808 error("Invalid environment variable \"%.100s\"", name);
813 * If we're passed an uninitialized list, allocate a single null
814 * entry before continuing.
816 if (*envp == NULL && *envsizep == 0) {
817 *envp = xmalloc(sizeof(char *));
823 * Find the slot where the value should be stored. If the variable
824 * already exists, we reuse the slot; otherwise we append a new slot
825 * at the end of the array, expanding if necessary.
828 namelen = strlen(name);
829 for (i = 0; env[i]; i++)
830 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
833 /* Reuse the slot. */
836 /* New variable. Expand if necessary. */
838 if (i >= envsize - 1) {
840 fatal("child_set_env: too many env vars");
842 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
845 /* Need to set the NULL pointer at end of array beyond the new slot. */
849 /* Allocate space and format the variable in the appropriate slot. */
850 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
851 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
855 * Reads environment variables from the given file and adds/overrides them
856 * into the environment. If the file does not exist, this does nothing.
857 * Otherwise, it must consist of empty lines, comments (line starts with '#')
858 * and assignments of the form name=value. No other forms are allowed.
861 read_environment_file(char ***env, u_int *envsize,
862 const char *filename)
869 f = fopen(filename, "r");
873 while (fgets(buf, sizeof(buf), f)) {
875 fatal("Too many lines in environment file %s", filename);
876 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
878 if (!*cp || *cp == '#' || *cp == '\n')
881 cp[strcspn(cp, "\n")] = '\0';
883 value = strchr(cp, '=');
885 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
890 * Replace the equals sign by nul, and advance value to
895 child_set_env(env, envsize, cp, value);
900 #ifdef HAVE_ETC_DEFAULT_LOGIN
902 * Return named variable from specified environment, or NULL if not present.
905 child_get_env(char **env, const char *name)
911 for (i=0; env[i] != NULL; i++)
912 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
913 return(env[i] + len + 1);
918 * Read /etc/default/login.
919 * We pick up the PATH (or SUPATH for root) and UMASK.
922 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
924 char **tmpenv = NULL, *var;
925 u_int i, tmpenvsize = 0;
929 * We don't want to copy the whole file to the child's environment,
930 * so we use a temporary environment and copy the variables we're
933 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
939 var = child_get_env(tmpenv, "SUPATH");
941 var = child_get_env(tmpenv, "PATH");
943 child_set_env(env, envsize, "PATH", var);
945 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
946 if (sscanf(var, "%5lo", &mask) == 1)
949 for (i = 0; tmpenv[i] != NULL; i++)
953 #endif /* HAVE_ETC_DEFAULT_LOGIN */
956 copy_environment(char **source, char ***env, u_int *envsize)
958 char *var_name, *var_val;
964 for(i = 0; source[i] != NULL; i++) {
965 var_name = xstrdup(source[i]);
966 if ((var_val = strstr(var_name, "=")) == NULL) {
972 debug3("Copy environment: %s=%s", var_name, var_val);
973 child_set_env(env, envsize, var_name, var_val);
980 do_setup_env(Session *s, const char *shell)
982 struct ssh *ssh = active_state; /* XXX */
986 struct passwd *pw = s->pw;
987 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
990 extern char **environ;
991 char **senv, **var, *val;
994 /* Initialize the environment. */
996 env = xcalloc(envsize, sizeof(char *));
1001 * The Windows environment contains some setting which are
1002 * important for a running system. They must not be dropped.
1007 p = fetch_windows_environment();
1008 copy_environment(p, &env, &envsize);
1009 free_windows_environment(p);
1014 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1017 /* Allow any GSSAPI methods that we've used to alter
1018 * the childs environment as they see fit
1020 ssh_gssapi_do_child(&env, &envsize);
1023 /* Set basic environment. */
1024 for (i = 0; i < s->num_env; i++)
1025 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1027 child_set_env(&env, &envsize, "USER", pw->pw_name);
1028 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1030 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1032 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1033 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1034 child_set_env(&env, &envsize, "MAIL", buf);
1035 #ifdef HAVE_LOGIN_CAP
1036 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1037 child_set_env(&env, &envsize, "TERM", "su");
1039 * Temporarily swap out our real environment with an empty one,
1040 * let setusercontext() apply any environment variables defined
1041 * for the user's login class, copy those variables to the child,
1042 * free the temporary environment, and restore the original.
1045 environ = xmalloc(sizeof(*environ));
1047 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1048 for (var = environ; *var != NULL; ++var) {
1049 if ((val = strchr(*var, '=')) != NULL) {
1051 child_set_env(&env, &envsize, *var, val);
1057 #else /* HAVE_LOGIN_CAP */
1058 # ifndef HAVE_CYGWIN
1060 * There's no standard path on Windows. The path contains
1061 * important components pointing to the system directories,
1062 * needed for loading shared libraries. So the path better
1063 * remains intact here.
1065 # ifdef HAVE_ETC_DEFAULT_LOGIN
1066 read_etc_default_login(&env, &envsize, pw->pw_uid);
1067 path = child_get_env(env, "PATH");
1068 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1069 if (path == NULL || *path == '\0') {
1070 child_set_env(&env, &envsize, "PATH",
1071 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1073 # endif /* HAVE_CYGWIN */
1074 #endif /* HAVE_LOGIN_CAP */
1076 /* Normal systems set SHELL by default. */
1077 child_set_env(&env, &envsize, "SHELL", shell);
1080 /* Set custom environment options from RSA authentication. */
1081 while (custom_environment) {
1082 struct envstring *ce = custom_environment;
1085 for (i = 0; str[i] != '=' && str[i]; i++)
1087 if (str[i] == '=') {
1089 child_set_env(&env, &envsize, str, str + i + 1);
1091 custom_environment = ce->next;
1096 /* SSH_CLIENT deprecated */
1097 snprintf(buf, sizeof buf, "%.50s %d %d",
1098 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1099 ssh_local_port(ssh));
1100 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1102 laddr = get_local_ipaddr(packet_get_connection_in());
1103 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1104 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1105 laddr, ssh_local_port(ssh));
1107 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1110 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1112 child_set_env(&env, &envsize, "TERM", s->term);
1114 child_set_env(&env, &envsize, "DISPLAY", s->display);
1115 if (original_command)
1116 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1120 if (cray_tmpdir[0] != '\0')
1121 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1122 #endif /* _UNICOS */
1125 * Since we clear KRB5CCNAME at startup, if it's set now then it
1126 * must have been set by a native authentication method (eg AIX or
1127 * SIA), so copy it to the child.
1132 if ((cp = getenv("KRB5CCNAME")) != NULL)
1133 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1140 if ((cp = getenv("AUTHSTATE")) != NULL)
1141 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1142 read_environment_file(&env, &envsize, "/etc/environment");
1146 if (s->authctxt->krb5_ccname)
1147 child_set_env(&env, &envsize, "KRB5CCNAME",
1148 s->authctxt->krb5_ccname);
1152 * Pull in any environment variables that may have
1155 if (options.use_pam) {
1158 p = fetch_pam_child_environment();
1159 copy_environment(p, &env, &envsize);
1160 free_pam_environment(p);
1162 p = fetch_pam_environment();
1163 copy_environment(p, &env, &envsize);
1164 free_pam_environment(p);
1166 #endif /* USE_PAM */
1168 if (auth_sock_name != NULL)
1169 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1172 /* read $HOME/.ssh/environment. */
1173 if (options.permit_user_env) {
1174 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1175 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1176 read_environment_file(&env, &envsize, buf);
1179 /* dump the environment */
1180 fprintf(stderr, "Environment:\n");
1181 for (i = 0; env[i]; i++)
1182 fprintf(stderr, " %.200s\n", env[i]);
1188 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1189 * first in this order).
1192 do_rc_files(Session *s, const char *shell)
1200 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1202 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1203 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1204 !no_user_rc && options.permit_user_rc &&
1205 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1206 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1207 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1209 fprintf(stderr, "Running %s\n", cmd);
1210 f = popen(cmd, "w");
1213 fprintf(f, "%s %s\n", s->auth_proto,
1217 fprintf(stderr, "Could not run %s\n",
1219 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1221 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1222 _PATH_SSH_SYSTEM_RC);
1223 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1226 fprintf(f, "%s %s\n", s->auth_proto,
1230 fprintf(stderr, "Could not run %s\n",
1231 _PATH_SSH_SYSTEM_RC);
1232 } else if (do_xauth && options.xauth_location != NULL) {
1233 /* Add authority data to .Xauthority if appropriate. */
1236 "Running %.500s remove %.100s\n",
1237 options.xauth_location, s->auth_display);
1239 "%.500s add %.100s %.100s %.100s\n",
1240 options.xauth_location, s->auth_display,
1241 s->auth_proto, s->auth_data);
1243 snprintf(cmd, sizeof cmd, "%s -q -",
1244 options.xauth_location);
1245 f = popen(cmd, "w");
1247 fprintf(f, "remove %s\n",
1249 fprintf(f, "add %s %s %s\n",
1250 s->auth_display, s->auth_proto,
1254 fprintf(stderr, "Could not run %s\n",
1261 do_nologin(struct passwd *pw)
1265 char buf[1024], *def_nl = _PATH_NOLOGIN;
1268 #ifdef HAVE_LOGIN_CAP
1269 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1271 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1273 if (pw->pw_uid == 0)
1277 if (stat(nl, &sb) == -1)
1280 /* /etc/nologin exists. Print its contents if we can and exit. */
1281 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1282 if ((f = fopen(nl, "r")) != NULL) {
1283 while (fgets(buf, sizeof(buf), f))
1291 * Chroot into a directory after checking it for safety: all path components
1292 * must be root-owned directories with strict permissions.
1295 safely_chroot(const char *path, uid_t uid)
1298 char component[PATH_MAX];
1302 fatal("chroot path does not begin at root");
1303 if (strlen(path) >= sizeof(component))
1304 fatal("chroot path too long");
1307 * Descend the path, checking that each component is a
1308 * root-owned directory with strict permissions.
1310 for (cp = path; cp != NULL;) {
1311 if ((cp = strchr(cp, '/')) == NULL)
1312 strlcpy(component, path, sizeof(component));
1315 memcpy(component, path, cp - path);
1316 component[cp - path] = '\0';
1319 debug3("%s: checking '%s'", __func__, component);
1321 if (stat(component, &st) != 0)
1322 fatal("%s: stat(\"%s\"): %s", __func__,
1323 component, strerror(errno));
1324 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1325 fatal("bad ownership or modes for chroot "
1326 "directory %s\"%s\"",
1327 cp == NULL ? "" : "component ", component);
1328 if (!S_ISDIR(st.st_mode))
1329 fatal("chroot path %s\"%s\" is not a directory",
1330 cp == NULL ? "" : "component ", component);
1334 if (chdir(path) == -1)
1335 fatal("Unable to chdir to chroot path \"%s\": "
1336 "%s", path, strerror(errno));
1337 if (chroot(path) == -1)
1338 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1339 if (chdir("/") == -1)
1340 fatal("%s: chdir(/) after chroot: %s",
1341 __func__, strerror(errno));
1342 verbose("Changed root directory to \"%s\"", path);
1345 /* Set login name, uid, gid, and groups. */
1347 do_setusercontext(struct passwd *pw)
1349 char *chroot_path, *tmp;
1351 platform_setusercontext(pw);
1353 if (platform_privileged_uidswap()) {
1354 #ifdef HAVE_LOGIN_CAP
1355 if (setusercontext(lc, pw, pw->pw_uid,
1356 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1357 perror("unable to set user context");
1361 if (setlogin(pw->pw_name) < 0)
1362 error("setlogin failed: %s", strerror(errno));
1363 if (setgid(pw->pw_gid) < 0) {
1367 /* Initialize the group list. */
1368 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1369 perror("initgroups");
1375 platform_setusercontext_post_groups(pw);
1377 if (!in_chroot && options.chroot_directory != NULL &&
1378 strcasecmp(options.chroot_directory, "none") != 0) {
1379 tmp = tilde_expand_filename(options.chroot_directory,
1381 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1382 "u", pw->pw_name, (char *)NULL);
1383 safely_chroot(chroot_path, pw->pw_uid);
1386 /* Make sure we don't attempt to chroot again */
1387 free(options.chroot_directory);
1388 options.chroot_directory = NULL;
1392 #ifdef HAVE_LOGIN_CAP
1393 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1394 perror("unable to set user context (setuser)");
1398 * FreeBSD's setusercontext() will not apply the user's
1399 * own umask setting unless running with the user's UID.
1401 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1405 * In a chroot environment, the set_id() will always fail;
1406 * typically because of the lack of necessary authentication
1407 * services and runtime such as ./usr/lib/libiaf.so,
1408 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1409 * internal sftp chroot case. We'll lose auditing and ACLs but
1410 * permanently_set_uid will take care of the rest.
1412 if (!in_chroot && set_id(pw->pw_name) != 0)
1413 fatal("set_id(%s) Failed", pw->pw_name);
1414 # endif /* USE_LIBIAF */
1415 /* Permanently switch to the desired uid. */
1416 permanently_set_uid(pw);
1418 } else if (options.chroot_directory != NULL &&
1419 strcasecmp(options.chroot_directory, "none") != 0) {
1420 fatal("server lacks privileges to chroot to ChrootDirectory");
1423 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1424 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1428 do_pwchange(Session *s)
1431 fprintf(stderr, "WARNING: Your password has expired.\n");
1432 if (s->ttyfd != -1) {
1434 "You must change your password now and login again!\n");
1438 #ifdef PASSWD_NEEDS_USERNAME
1439 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1442 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1447 "Password change required but no TTY available.\n");
1453 child_close_fds(void)
1455 extern int auth_sock;
1457 if (auth_sock != -1) {
1462 if (packet_get_connection_in() == packet_get_connection_out())
1463 close(packet_get_connection_in());
1465 close(packet_get_connection_in());
1466 close(packet_get_connection_out());
1469 * Close all descriptors related to channels. They will still remain
1470 * open in the parent.
1472 /* XXX better use close-on-exec? -markus */
1473 channel_close_all();
1476 * Close any extra file descriptors. Note that there may still be
1477 * descriptors left by system functions. They will be closed later.
1482 * Close any extra open file descriptors so that we don't have them
1483 * hanging around in clients. Note that we want to do this after
1484 * initgroups, because at least on Solaris 2.3 it leaves file
1487 closefrom(STDERR_FILENO + 1);
1491 * Performs common processing for the child, such as setting up the
1492 * environment, closing extra file descriptors, setting the user and group
1493 * ids, and executing the command or shell.
1497 do_child(Session *s, const char *command)
1499 extern char **environ;
1501 char *argv[ARGV_MAX];
1502 const char *shell, *shell0;
1503 struct passwd *pw = s->pw;
1506 /* remove hostkey from the child's memory */
1507 destroy_sensitive_data();
1509 /* Force a password change */
1510 if (s->authctxt->force_pwchange) {
1511 do_setusercontext(pw);
1518 cray_setup(pw->pw_uid, pw->pw_name, command);
1519 #endif /* _UNICOS */
1522 * Login(1) does this as well, and it needs uid 0 for the "-h"
1523 * switch, so we let login(1) to this for us.
1526 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1527 if (!check_quietlogin(s, command))
1529 #else /* HAVE_OSF_SIA */
1530 /* When PAM is enabled we rely on it to do the nologin check */
1531 if (!options.use_pam)
1533 do_setusercontext(pw);
1535 * PAM session modules in do_setusercontext may have
1536 * generated messages, so if this in an interactive
1537 * login then display them too.
1539 if (!check_quietlogin(s, command))
1541 #endif /* HAVE_OSF_SIA */
1544 if (options.use_pam && !is_pam_session_open()) {
1545 debug3("PAM session not opened, exiting");
1552 * Get the shell from the password data. An empty shell field is
1553 * legal, and means /bin/sh.
1555 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1558 * Make sure $SHELL points to the shell from the password file,
1559 * even if shell is overridden from login.conf
1561 env = do_setup_env(s, shell);
1563 #ifdef HAVE_LOGIN_CAP
1564 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1568 * Close the connection descriptors; note that this is the child, and
1569 * the server will still have the socket open, and it is important
1570 * that we do not shutdown it. Note that the descriptors cannot be
1571 * closed before building the environment, as we call
1572 * ssh_remote_ipaddr there.
1577 * Must take new environment into use so that .ssh/rc,
1578 * /etc/ssh/sshrc and xauth are run in the proper environment.
1582 #if defined(KRB5) && defined(USE_AFS)
1584 * At this point, we check to see if AFS is active and if we have
1585 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1586 * if we can (and need to) extend the ticket into an AFS token. If
1587 * we don't do this, we run into potential problems if the user's
1588 * home directory is in AFS and it's not world-readable.
1591 if (options.kerberos_get_afs_token && k_hasafs() &&
1592 (s->authctxt->krb5_ctx != NULL)) {
1595 debug("Getting AFS token");
1599 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1600 krb5_afslog(s->authctxt->krb5_ctx,
1601 s->authctxt->krb5_fwd_ccache, cell, NULL);
1603 krb5_afslog_home(s->authctxt->krb5_ctx,
1604 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1608 /* Change current directory to the user's home directory. */
1609 if (chdir(pw->pw_dir) < 0) {
1610 /* Suppress missing homedir warning for chroot case */
1611 #ifdef HAVE_LOGIN_CAP
1612 r = login_getcapbool(lc, "requirehome", 0);
1614 if (r || !in_chroot) {
1615 fprintf(stderr, "Could not chdir to home "
1616 "directory %s: %s\n", pw->pw_dir,
1623 closefrom(STDERR_FILENO + 1);
1625 do_rc_files(s, shell);
1627 /* restore SIGPIPE for child */
1628 signal(SIGPIPE, SIG_DFL);
1630 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1631 printf("This service allows sftp connections only.\n");
1634 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1635 extern int optind, optreset;
1639 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1640 args = xstrdup(command ? command : "sftp-server");
1641 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1642 if (i < ARGV_MAX - 1)
1645 optind = optreset = 1;
1646 __progname = argv[0];
1648 ssh_selinux_change_context("sftpd_t");
1650 exit(sftp_server_main(i, argv, s->pw));
1655 /* Get the last component of the shell name. */
1656 if ((shell0 = strrchr(shell, '/')) != NULL)
1662 * If we have no command, execute the shell. In this case, the shell
1663 * name to be passed in argv[0] is preceded by '-' to indicate that
1664 * this is a login shell.
1669 /* Start the shell. Set initial character to '-'. */
1672 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1673 >= sizeof(argv0) - 1) {
1679 /* Execute the shell. */
1682 execve(shell, argv, env);
1684 /* Executing the shell failed. */
1689 * Execute the command using the user's shell. This uses the -c
1690 * option to execute the command.
1692 argv[0] = (char *) shell0;
1694 argv[2] = (char *) command;
1696 execve(shell, argv, env);
1702 session_unused(int id)
1704 debug3("%s: session id %d unused", __func__, id);
1705 if (id >= options.max_sessions ||
1706 id >= sessions_nalloc) {
1707 fatal("%s: insane session id %d (max %d nalloc %d)",
1708 __func__, id, options.max_sessions, sessions_nalloc);
1710 memset(&sessions[id], 0, sizeof(*sessions));
1711 sessions[id].self = id;
1712 sessions[id].used = 0;
1713 sessions[id].chanid = -1;
1714 sessions[id].ptyfd = -1;
1715 sessions[id].ttyfd = -1;
1716 sessions[id].ptymaster = -1;
1717 sessions[id].x11_chanids = NULL;
1718 sessions[id].next_unused = sessions_first_unused;
1719 sessions_first_unused = id;
1727 if (sessions_first_unused == -1) {
1728 if (sessions_nalloc >= options.max_sessions)
1730 debug2("%s: allocate (allocated %d max %d)",
1731 __func__, sessions_nalloc, options.max_sessions);
1732 tmp = xreallocarray(sessions, sessions_nalloc + 1,
1735 error("%s: cannot allocate %d sessions",
1736 __func__, sessions_nalloc + 1);
1740 session_unused(sessions_nalloc++);
1743 if (sessions_first_unused >= sessions_nalloc ||
1744 sessions_first_unused < 0) {
1745 fatal("%s: insane first_unused %d max %d nalloc %d",
1746 __func__, sessions_first_unused, options.max_sessions,
1750 s = &sessions[sessions_first_unused];
1752 fatal("%s: session %d already used",
1753 __func__, sessions_first_unused);
1755 sessions_first_unused = s->next_unused;
1757 s->next_unused = -1;
1758 debug("session_new: session %d", s->self);
1767 for (i = 0; i < sessions_nalloc; i++) {
1768 Session *s = &sessions[i];
1770 debug("dump: used %d next_unused %d session %d %p "
1771 "channel %d pid %ld",
1782 session_open(Authctxt *authctxt, int chanid)
1784 Session *s = session_new();
1785 debug("session_open: channel %d", chanid);
1787 error("no more sessions");
1790 s->authctxt = authctxt;
1791 s->pw = authctxt->pw;
1792 if (s->pw == NULL || !authctxt->valid)
1793 fatal("no user for session %d", s->self);
1794 debug("session_open: session %d: link with channel %d", s->self, chanid);
1800 session_by_tty(char *tty)
1803 for (i = 0; i < sessions_nalloc; i++) {
1804 Session *s = &sessions[i];
1805 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1806 debug("session_by_tty: session %d tty %s", i, tty);
1810 debug("session_by_tty: unknown tty %.100s", tty);
1816 session_by_channel(int id)
1819 for (i = 0; i < sessions_nalloc; i++) {
1820 Session *s = &sessions[i];
1821 if (s->used && s->chanid == id) {
1822 debug("session_by_channel: session %d channel %d",
1827 debug("session_by_channel: unknown channel %d", id);
1833 session_by_x11_channel(int id)
1837 for (i = 0; i < sessions_nalloc; i++) {
1838 Session *s = &sessions[i];
1840 if (s->x11_chanids == NULL || !s->used)
1842 for (j = 0; s->x11_chanids[j] != -1; j++) {
1843 if (s->x11_chanids[j] == id) {
1844 debug("session_by_x11_channel: session %d "
1845 "channel %d", s->self, id);
1850 debug("session_by_x11_channel: unknown channel %d", id);
1856 session_by_pid(pid_t pid)
1859 debug("session_by_pid: pid %ld", (long)pid);
1860 for (i = 0; i < sessions_nalloc; i++) {
1861 Session *s = &sessions[i];
1862 if (s->used && s->pid == pid)
1865 error("session_by_pid: unknown pid %ld", (long)pid);
1871 session_window_change_req(Session *s)
1873 s->col = packet_get_int();
1874 s->row = packet_get_int();
1875 s->xpixel = packet_get_int();
1876 s->ypixel = packet_get_int();
1878 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1883 session_pty_req(Session *s)
1888 if (no_pty_flag || !options.permit_tty) {
1889 debug("Allocating a pty not permitted for this authentication.");
1892 if (s->ttyfd != -1) {
1893 packet_disconnect("Protocol error: you already have a pty.");
1897 s->term = packet_get_string(&len);
1898 s->col = packet_get_int();
1899 s->row = packet_get_int();
1900 s->xpixel = packet_get_int();
1901 s->ypixel = packet_get_int();
1903 if (strcmp(s->term, "") == 0) {
1908 /* Allocate a pty and open it. */
1909 debug("Allocating pty.");
1910 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1916 error("session_pty_req: session %d alloc failed", s->self);
1919 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1921 n_bytes = packet_remaining();
1922 tty_parse_modes(s->ttyfd, &n_bytes);
1925 pty_setowner(s->pw, s->tty);
1927 /* Set window size from the packet. */
1928 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1931 session_proctitle(s);
1936 session_subsystem_req(Session *s)
1944 s->subsys = packet_get_string(&len);
1946 debug2("subsystem request for %.100s by user %s", s->subsys,
1949 for (i = 0; i < options.num_subsystems; i++) {
1950 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1951 prog = options.subsystem_command[i];
1952 cmd = options.subsystem_args[i];
1953 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1954 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1955 debug("subsystem: %s", prog);
1957 if (stat(prog, &st) < 0)
1958 debug("subsystem: cannot stat %s: %s",
1959 prog, strerror(errno));
1960 s->is_subsystem = SUBSYSTEM_EXT;
1961 debug("subsystem: exec() %s", cmd);
1963 success = do_exec(s, cmd) == 0;
1969 logit("subsystem request for %.100s by user %s failed, "
1970 "subsystem not found", s->subsys, s->pw->pw_name);
1976 session_x11_req(Session *s)
1980 if (s->auth_proto != NULL || s->auth_data != NULL) {
1981 error("session_x11_req: session %d: "
1982 "x11 forwarding already active", s->self);
1985 s->single_connection = packet_get_char();
1986 s->auth_proto = packet_get_string(NULL);
1987 s->auth_data = packet_get_string(NULL);
1988 s->screen = packet_get_int();
1991 if (xauth_valid_string(s->auth_proto) &&
1992 xauth_valid_string(s->auth_data))
1993 success = session_setup_x11fwd(s);
1996 error("Invalid X11 forwarding data");
1999 free(s->auth_proto);
2001 s->auth_proto = NULL;
2002 s->auth_data = NULL;
2008 session_shell_req(Session *s)
2011 return do_exec(s, NULL) == 0;
2015 session_exec_req(Session *s)
2019 char *command = packet_get_string(&len);
2021 success = do_exec(s, command) == 0;
2027 session_break_req(Session *s)
2030 packet_get_int(); /* ignored */
2033 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2039 session_env_req(Session *s)
2042 u_int name_len, val_len, i;
2044 name = packet_get_cstring(&name_len);
2045 val = packet_get_cstring(&val_len);
2048 /* Don't set too many environment variables */
2049 if (s->num_env > 128) {
2050 debug2("Ignoring env request %s: too many env vars", name);
2054 for (i = 0; i < options.num_accept_env; i++) {
2055 if (match_pattern(name, options.accept_env[i])) {
2056 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2057 s->env = xreallocarray(s->env, s->num_env + 1,
2059 s->env[s->num_env].name = name;
2060 s->env[s->num_env].val = val;
2065 debug2("Ignoring env request %s: disallowed name", name);
2074 session_auth_agent_req(Session *s)
2076 static int called = 0;
2078 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2079 debug("session_auth_agent_req: no_agent_forwarding_flag");
2086 return auth_input_request_forwarding(s->pw);
2091 session_input_channel_req(Channel *c, const char *rtype)
2096 if ((s = session_by_channel(c->self)) == NULL) {
2097 logit("session_input_channel_req: no session %d req %.100s",
2101 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2104 * a session is in LARVAL state until a shell, a command
2105 * or a subsystem is executed
2107 if (c->type == SSH_CHANNEL_LARVAL) {
2108 if (strcmp(rtype, "shell") == 0) {
2109 success = session_shell_req(s);
2110 } else if (strcmp(rtype, "exec") == 0) {
2111 success = session_exec_req(s);
2112 } else if (strcmp(rtype, "pty-req") == 0) {
2113 success = session_pty_req(s);
2114 } else if (strcmp(rtype, "x11-req") == 0) {
2115 success = session_x11_req(s);
2116 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2117 success = session_auth_agent_req(s);
2118 } else if (strcmp(rtype, "subsystem") == 0) {
2119 success = session_subsystem_req(s);
2120 } else if (strcmp(rtype, "env") == 0) {
2121 success = session_env_req(s);
2124 if (strcmp(rtype, "window-change") == 0) {
2125 success = session_window_change_req(s);
2126 } else if (strcmp(rtype, "break") == 0) {
2127 success = session_break_req(s);
2134 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2138 * now that have a child and a pipe to the child,
2139 * we can activate our channel and register the fd's
2141 if (s->chanid == -1)
2142 fatal("no channel for session %d", s->self);
2143 channel_set_fds(s->chanid,
2145 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2146 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2150 * Function to perform pty cleanup. Also called if we get aborted abnormally
2151 * (e.g., due to a dropped connection).
2154 session_pty_cleanup2(Session *s)
2157 error("session_pty_cleanup: no session");
2163 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2165 /* Record that the user has logged out. */
2167 record_logout(s->pid, s->tty, s->pw->pw_name);
2169 /* Release the pseudo-tty. */
2171 pty_release(s->tty);
2174 * Close the server side of the socket pairs. We must do this after
2175 * the pty cleanup, so that another process doesn't get this pty
2176 * while we're still cleaning up.
2178 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2179 error("close(s->ptymaster/%d): %s",
2180 s->ptymaster, strerror(errno));
2182 /* unlink pty from session */
2187 session_pty_cleanup(Session *s)
2189 PRIVSEP(session_pty_cleanup2(s));
2195 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2210 return "SIG@openssh.com";
2214 session_close_x11(int id)
2218 if ((c = channel_by_id(id)) == NULL) {
2219 debug("session_close_x11: x11 channel %d missing", id);
2221 /* Detach X11 listener */
2222 debug("session_close_x11: detach x11 channel %d", id);
2223 channel_cancel_cleanup(id);
2224 if (c->ostate != CHAN_OUTPUT_CLOSED)
2230 session_close_single_x11(int id, void *arg)
2235 debug3("session_close_single_x11: channel %d", id);
2236 channel_cancel_cleanup(id);
2237 if ((s = session_by_x11_channel(id)) == NULL)
2238 fatal("session_close_single_x11: no x11 channel %d", id);
2239 for (i = 0; s->x11_chanids[i] != -1; i++) {
2240 debug("session_close_single_x11: session %d: "
2241 "closing channel %d", s->self, s->x11_chanids[i]);
2243 * The channel "id" is already closing, but make sure we
2244 * close all of its siblings.
2246 if (s->x11_chanids[i] != id)
2247 session_close_x11(s->x11_chanids[i]);
2249 free(s->x11_chanids);
2250 s->x11_chanids = NULL;
2253 free(s->auth_proto);
2254 s->auth_proto = NULL;
2256 s->auth_data = NULL;
2257 free(s->auth_display);
2258 s->auth_display = NULL;
2262 session_exit_message(Session *s, int status)
2266 if ((c = channel_lookup(s->chanid)) == NULL)
2267 fatal("session_exit_message: session %d: no channel %d",
2268 s->self, s->chanid);
2269 debug("session_exit_message: session %d channel %d pid %ld",
2270 s->self, s->chanid, (long)s->pid);
2272 if (WIFEXITED(status)) {
2273 channel_request_start(s->chanid, "exit-status", 0);
2274 packet_put_int(WEXITSTATUS(status));
2276 } else if (WIFSIGNALED(status)) {
2277 channel_request_start(s->chanid, "exit-signal", 0);
2278 packet_put_cstring(sig2name(WTERMSIG(status)));
2280 packet_put_char(WCOREDUMP(status)? 1 : 0);
2281 #else /* WCOREDUMP */
2283 #endif /* WCOREDUMP */
2284 packet_put_cstring("");
2285 packet_put_cstring("");
2288 /* Some weird exit cause. Just exit. */
2289 packet_disconnect("wait returned status %04x.", status);
2292 /* disconnect channel */
2293 debug("session_exit_message: release channel %d", s->chanid);
2296 * Adjust cleanup callback attachment to send close messages when
2297 * the channel gets EOF. The session will be then be closed
2298 * by session_close_by_channel when the childs close their fds.
2300 channel_register_cleanup(c->self, session_close_by_channel, 1);
2303 * emulate a write failure with 'chan_write_failed', nobody will be
2304 * interested in data we write.
2305 * Note that we must not call 'chan_read_failed', since there could
2306 * be some more data waiting in the pipe.
2308 if (c->ostate != CHAN_OUTPUT_CLOSED)
2309 chan_write_failed(c);
2313 session_close(Session *s)
2315 struct ssh *ssh = active_state; /* XXX */
2318 verbose("Close session: user %s from %.200s port %d id %d",
2320 ssh_remote_ipaddr(ssh),
2321 ssh_remote_port(ssh),
2325 session_pty_cleanup(s);
2328 free(s->x11_chanids);
2329 free(s->auth_display);
2331 free(s->auth_proto);
2333 if (s->env != NULL) {
2334 for (i = 0; i < s->num_env; i++) {
2335 free(s->env[i].name);
2336 free(s->env[i].val);
2340 session_proctitle(s);
2341 session_unused(s->self);
2345 session_close_by_pid(pid_t pid, int status)
2347 Session *s = session_by_pid(pid);
2349 debug("session_close_by_pid: no session for pid %ld",
2353 if (s->chanid != -1)
2354 session_exit_message(s, status);
2356 session_pty_cleanup(s);
2361 * this is called when a channel dies before
2362 * the session 'child' itself dies
2365 session_close_by_channel(int id, void *arg)
2367 Session *s = session_by_channel(id);
2371 debug("session_close_by_channel: no session for id %d", id);
2374 debug("session_close_by_channel: channel %d child %ld",
2377 debug("session_close_by_channel: channel %d: has child", id);
2379 * delay detach of session, but release pty, since
2380 * the fd's to the child are already closed
2383 session_pty_cleanup(s);
2386 /* detach by removing callback */
2387 channel_cancel_cleanup(s->chanid);
2389 /* Close any X11 listeners associated with this session */
2390 if (s->x11_chanids != NULL) {
2391 for (i = 0; s->x11_chanids[i] != -1; i++) {
2392 session_close_x11(s->x11_chanids[i]);
2393 s->x11_chanids[i] = -1;
2402 session_destroy_all(void (*closefunc)(Session *))
2405 for (i = 0; i < sessions_nalloc; i++) {
2406 Session *s = &sessions[i];
2408 if (closefunc != NULL)
2417 session_tty_list(void)
2419 static char buf[1024];
2424 for (i = 0; i < sessions_nalloc; i++) {
2425 Session *s = &sessions[i];
2426 if (s->used && s->ttyfd != -1) {
2428 if (strncmp(s->tty, "/dev/", 5) != 0) {
2429 cp = strrchr(s->tty, '/');
2430 cp = (cp == NULL) ? s->tty : cp + 1;
2435 strlcat(buf, ",", sizeof buf);
2436 strlcat(buf, cp, sizeof buf);
2440 strlcpy(buf, "notty", sizeof buf);
2445 session_proctitle(Session *s)
2448 error("no user for session %d", s->self);
2450 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2454 session_setup_x11fwd(Session *s)
2457 char display[512], auth_display[512];
2458 char hostname[NI_MAXHOST];
2461 if (no_x11_forwarding_flag) {
2462 packet_send_debug("X11 forwarding disabled in user configuration file.");
2465 if (!options.x11_forwarding) {
2466 debug("X11 forwarding disabled in server configuration file.");
2469 if (options.xauth_location == NULL ||
2470 (stat(options.xauth_location, &st) == -1)) {
2471 packet_send_debug("No xauth program; cannot forward with spoofing.");
2474 if (s->display != NULL) {
2475 debug("X11 display already set.");
2478 if (x11_create_display_inet(options.x11_display_offset,
2479 options.x11_use_localhost, s->single_connection,
2480 &s->display_number, &s->x11_chanids) == -1) {
2481 debug("x11_create_display_inet failed.");
2484 for (i = 0; s->x11_chanids[i] != -1; i++) {
2485 channel_register_cleanup(s->x11_chanids[i],
2486 session_close_single_x11, 0);
2489 /* Set up a suitable value for the DISPLAY variable. */
2490 if (gethostname(hostname, sizeof(hostname)) < 0)
2491 fatal("gethostname: %.100s", strerror(errno));
2493 * auth_display must be used as the displayname when the
2494 * authorization entry is added with xauth(1). This will be
2495 * different than the DISPLAY string for localhost displays.
2497 if (options.x11_use_localhost) {
2498 snprintf(display, sizeof display, "localhost:%u.%u",
2499 s->display_number, s->screen);
2500 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2501 s->display_number, s->screen);
2502 s->display = xstrdup(display);
2503 s->auth_display = xstrdup(auth_display);
2505 #ifdef IPADDR_IN_DISPLAY
2507 struct in_addr my_addr;
2509 he = gethostbyname(hostname);
2511 error("Can't get IP address for X11 DISPLAY.");
2512 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2515 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2516 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2517 s->display_number, s->screen);
2519 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2520 s->display_number, s->screen);
2522 s->display = xstrdup(display);
2523 s->auth_display = xstrdup(display);
2530 do_authenticated2(Authctxt *authctxt)
2532 server_loop2(authctxt);
2536 do_cleanup(Authctxt *authctxt)
2538 static int called = 0;
2540 debug("do_cleanup");
2542 /* no cleanup if we're in the child for login shell */
2546 /* avoid double cleanup */
2551 if (authctxt == NULL)
2555 if (options.use_pam) {
2557 sshpam_thread_cleanup();
2561 if (!authctxt->authenticated)
2565 if (options.kerberos_ticket_cleanup &&
2567 krb5_cleanup_proc(authctxt);
2571 if (options.gss_cleanup_creds)
2572 ssh_gssapi_cleanup_creds();
2575 /* remove agent socket */
2576 auth_sock_cleanup_proc(authctxt->pw);
2579 * Cleanup ptys/utmp only if privsep is disabled,
2580 * or if running in monitor.
2582 if (!use_privsep || mm_is_monitor())
2583 session_destroy_all(session_pty_cleanup2);
2586 /* Return a name for the remote host that fits inside utmp_size */
2589 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2591 const char *remote = "";
2594 remote = auth_get_canonical_hostname(ssh, use_dns);
2595 if (utmp_size == 0 || strlen(remote) > utmp_size)
2596 remote = ssh_remote_ipaddr(ssh);