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)
1264 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1267 #ifdef HAVE_LOGIN_CAP
1268 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1270 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1272 if (pw->pw_uid == 0)
1276 if (stat(nl, &sb) == -1) {
1282 /* /etc/nologin exists. Print its contents if we can and exit. */
1283 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1284 if ((f = fopen(nl, "r")) != NULL) {
1285 while (fgets(buf, sizeof(buf), f))
1293 * Chroot into a directory after checking it for safety: all path components
1294 * must be root-owned directories with strict permissions.
1297 safely_chroot(const char *path, uid_t uid)
1300 char component[PATH_MAX];
1304 fatal("chroot path does not begin at root");
1305 if (strlen(path) >= sizeof(component))
1306 fatal("chroot path too long");
1309 * Descend the path, checking that each component is a
1310 * root-owned directory with strict permissions.
1312 for (cp = path; cp != NULL;) {
1313 if ((cp = strchr(cp, '/')) == NULL)
1314 strlcpy(component, path, sizeof(component));
1317 memcpy(component, path, cp - path);
1318 component[cp - path] = '\0';
1321 debug3("%s: checking '%s'", __func__, component);
1323 if (stat(component, &st) != 0)
1324 fatal("%s: stat(\"%s\"): %s", __func__,
1325 component, strerror(errno));
1326 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1327 fatal("bad ownership or modes for chroot "
1328 "directory %s\"%s\"",
1329 cp == NULL ? "" : "component ", component);
1330 if (!S_ISDIR(st.st_mode))
1331 fatal("chroot path %s\"%s\" is not a directory",
1332 cp == NULL ? "" : "component ", component);
1336 if (chdir(path) == -1)
1337 fatal("Unable to chdir to chroot path \"%s\": "
1338 "%s", path, strerror(errno));
1339 if (chroot(path) == -1)
1340 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1341 if (chdir("/") == -1)
1342 fatal("%s: chdir(/) after chroot: %s",
1343 __func__, strerror(errno));
1344 verbose("Changed root directory to \"%s\"", path);
1347 /* Set login name, uid, gid, and groups. */
1349 do_setusercontext(struct passwd *pw)
1351 char *chroot_path, *tmp;
1353 platform_setusercontext(pw);
1355 if (platform_privileged_uidswap()) {
1356 #ifdef HAVE_LOGIN_CAP
1357 if (setusercontext(lc, pw, pw->pw_uid,
1358 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1359 perror("unable to set user context");
1363 if (setlogin(pw->pw_name) < 0)
1364 error("setlogin failed: %s", strerror(errno));
1365 if (setgid(pw->pw_gid) < 0) {
1369 /* Initialize the group list. */
1370 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1371 perror("initgroups");
1377 platform_setusercontext_post_groups(pw);
1379 if (!in_chroot && options.chroot_directory != NULL &&
1380 strcasecmp(options.chroot_directory, "none") != 0) {
1381 tmp = tilde_expand_filename(options.chroot_directory,
1383 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1384 "u", pw->pw_name, (char *)NULL);
1385 safely_chroot(chroot_path, pw->pw_uid);
1388 /* Make sure we don't attempt to chroot again */
1389 free(options.chroot_directory);
1390 options.chroot_directory = NULL;
1394 #ifdef HAVE_LOGIN_CAP
1395 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1396 perror("unable to set user context (setuser)");
1400 * FreeBSD's setusercontext() will not apply the user's
1401 * own umask setting unless running with the user's UID.
1403 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1407 * In a chroot environment, the set_id() will always fail;
1408 * typically because of the lack of necessary authentication
1409 * services and runtime such as ./usr/lib/libiaf.so,
1410 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1411 * internal sftp chroot case. We'll lose auditing and ACLs but
1412 * permanently_set_uid will take care of the rest.
1414 if (!in_chroot && set_id(pw->pw_name) != 0)
1415 fatal("set_id(%s) Failed", pw->pw_name);
1416 # endif /* USE_LIBIAF */
1417 /* Permanently switch to the desired uid. */
1418 permanently_set_uid(pw);
1420 } else if (options.chroot_directory != NULL &&
1421 strcasecmp(options.chroot_directory, "none") != 0) {
1422 fatal("server lacks privileges to chroot to ChrootDirectory");
1425 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1426 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1430 do_pwchange(Session *s)
1433 fprintf(stderr, "WARNING: Your password has expired.\n");
1434 if (s->ttyfd != -1) {
1436 "You must change your password now and login again!\n");
1440 #ifdef PASSWD_NEEDS_USERNAME
1441 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1444 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1449 "Password change required but no TTY available.\n");
1455 child_close_fds(void)
1457 extern int auth_sock;
1459 if (auth_sock != -1) {
1464 if (packet_get_connection_in() == packet_get_connection_out())
1465 close(packet_get_connection_in());
1467 close(packet_get_connection_in());
1468 close(packet_get_connection_out());
1471 * Close all descriptors related to channels. They will still remain
1472 * open in the parent.
1474 /* XXX better use close-on-exec? -markus */
1475 channel_close_all();
1478 * Close any extra file descriptors. Note that there may still be
1479 * descriptors left by system functions. They will be closed later.
1484 * Close any extra open file descriptors so that we don't have them
1485 * hanging around in clients. Note that we want to do this after
1486 * initgroups, because at least on Solaris 2.3 it leaves file
1489 closefrom(STDERR_FILENO + 1);
1493 * Performs common processing for the child, such as setting up the
1494 * environment, closing extra file descriptors, setting the user and group
1495 * ids, and executing the command or shell.
1499 do_child(Session *s, const char *command)
1501 extern char **environ;
1503 char *argv[ARGV_MAX];
1504 const char *shell, *shell0;
1505 struct passwd *pw = s->pw;
1508 /* remove hostkey from the child's memory */
1509 destroy_sensitive_data();
1511 /* Force a password change */
1512 if (s->authctxt->force_pwchange) {
1513 do_setusercontext(pw);
1520 cray_setup(pw->pw_uid, pw->pw_name, command);
1521 #endif /* _UNICOS */
1524 * Login(1) does this as well, and it needs uid 0 for the "-h"
1525 * switch, so we let login(1) to this for us.
1528 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1529 if (!check_quietlogin(s, command))
1531 #else /* HAVE_OSF_SIA */
1532 /* When PAM is enabled we rely on it to do the nologin check */
1533 if (!options.use_pam)
1535 do_setusercontext(pw);
1537 * PAM session modules in do_setusercontext may have
1538 * generated messages, so if this in an interactive
1539 * login then display them too.
1541 if (!check_quietlogin(s, command))
1543 #endif /* HAVE_OSF_SIA */
1546 if (options.use_pam && !is_pam_session_open()) {
1547 debug3("PAM session not opened, exiting");
1554 * Get the shell from the password data. An empty shell field is
1555 * legal, and means /bin/sh.
1557 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1560 * Make sure $SHELL points to the shell from the password file,
1561 * even if shell is overridden from login.conf
1563 env = do_setup_env(s, shell);
1565 #ifdef HAVE_LOGIN_CAP
1566 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1570 * Close the connection descriptors; note that this is the child, and
1571 * the server will still have the socket open, and it is important
1572 * that we do not shutdown it. Note that the descriptors cannot be
1573 * closed before building the environment, as we call
1574 * ssh_remote_ipaddr there.
1579 * Must take new environment into use so that .ssh/rc,
1580 * /etc/ssh/sshrc and xauth are run in the proper environment.
1584 #if defined(KRB5) && defined(USE_AFS)
1586 * At this point, we check to see if AFS is active and if we have
1587 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1588 * if we can (and need to) extend the ticket into an AFS token. If
1589 * we don't do this, we run into potential problems if the user's
1590 * home directory is in AFS and it's not world-readable.
1593 if (options.kerberos_get_afs_token && k_hasafs() &&
1594 (s->authctxt->krb5_ctx != NULL)) {
1597 debug("Getting AFS token");
1601 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1602 krb5_afslog(s->authctxt->krb5_ctx,
1603 s->authctxt->krb5_fwd_ccache, cell, NULL);
1605 krb5_afslog_home(s->authctxt->krb5_ctx,
1606 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1610 /* Change current directory to the user's home directory. */
1611 if (chdir(pw->pw_dir) < 0) {
1612 /* Suppress missing homedir warning for chroot case */
1613 #ifdef HAVE_LOGIN_CAP
1614 r = login_getcapbool(lc, "requirehome", 0);
1616 if (r || !in_chroot) {
1617 fprintf(stderr, "Could not chdir to home "
1618 "directory %s: %s\n", pw->pw_dir,
1625 closefrom(STDERR_FILENO + 1);
1627 do_rc_files(s, shell);
1629 /* restore SIGPIPE for child */
1630 signal(SIGPIPE, SIG_DFL);
1632 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1633 printf("This service allows sftp connections only.\n");
1636 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1637 extern int optind, optreset;
1641 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1642 args = xstrdup(command ? command : "sftp-server");
1643 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1644 if (i < ARGV_MAX - 1)
1647 optind = optreset = 1;
1648 __progname = argv[0];
1650 ssh_selinux_change_context("sftpd_t");
1652 exit(sftp_server_main(i, argv, s->pw));
1657 /* Get the last component of the shell name. */
1658 if ((shell0 = strrchr(shell, '/')) != NULL)
1664 * If we have no command, execute the shell. In this case, the shell
1665 * name to be passed in argv[0] is preceded by '-' to indicate that
1666 * this is a login shell.
1671 /* Start the shell. Set initial character to '-'. */
1674 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1675 >= sizeof(argv0) - 1) {
1681 /* Execute the shell. */
1684 execve(shell, argv, env);
1686 /* Executing the shell failed. */
1691 * Execute the command using the user's shell. This uses the -c
1692 * option to execute the command.
1694 argv[0] = (char *) shell0;
1696 argv[2] = (char *) command;
1698 execve(shell, argv, env);
1704 session_unused(int id)
1706 debug3("%s: session id %d unused", __func__, id);
1707 if (id >= options.max_sessions ||
1708 id >= sessions_nalloc) {
1709 fatal("%s: insane session id %d (max %d nalloc %d)",
1710 __func__, id, options.max_sessions, sessions_nalloc);
1712 memset(&sessions[id], 0, sizeof(*sessions));
1713 sessions[id].self = id;
1714 sessions[id].used = 0;
1715 sessions[id].chanid = -1;
1716 sessions[id].ptyfd = -1;
1717 sessions[id].ttyfd = -1;
1718 sessions[id].ptymaster = -1;
1719 sessions[id].x11_chanids = NULL;
1720 sessions[id].next_unused = sessions_first_unused;
1721 sessions_first_unused = id;
1729 if (sessions_first_unused == -1) {
1730 if (sessions_nalloc >= options.max_sessions)
1732 debug2("%s: allocate (allocated %d max %d)",
1733 __func__, sessions_nalloc, options.max_sessions);
1734 tmp = xreallocarray(sessions, sessions_nalloc + 1,
1737 error("%s: cannot allocate %d sessions",
1738 __func__, sessions_nalloc + 1);
1742 session_unused(sessions_nalloc++);
1745 if (sessions_first_unused >= sessions_nalloc ||
1746 sessions_first_unused < 0) {
1747 fatal("%s: insane first_unused %d max %d nalloc %d",
1748 __func__, sessions_first_unused, options.max_sessions,
1752 s = &sessions[sessions_first_unused];
1754 fatal("%s: session %d already used",
1755 __func__, sessions_first_unused);
1757 sessions_first_unused = s->next_unused;
1759 s->next_unused = -1;
1760 debug("session_new: session %d", s->self);
1769 for (i = 0; i < sessions_nalloc; i++) {
1770 Session *s = &sessions[i];
1772 debug("dump: used %d next_unused %d session %d %p "
1773 "channel %d pid %ld",
1784 session_open(Authctxt *authctxt, int chanid)
1786 Session *s = session_new();
1787 debug("session_open: channel %d", chanid);
1789 error("no more sessions");
1792 s->authctxt = authctxt;
1793 s->pw = authctxt->pw;
1794 if (s->pw == NULL || !authctxt->valid)
1795 fatal("no user for session %d", s->self);
1796 debug("session_open: session %d: link with channel %d", s->self, chanid);
1802 session_by_tty(char *tty)
1805 for (i = 0; i < sessions_nalloc; i++) {
1806 Session *s = &sessions[i];
1807 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1808 debug("session_by_tty: session %d tty %s", i, tty);
1812 debug("session_by_tty: unknown tty %.100s", tty);
1818 session_by_channel(int id)
1821 for (i = 0; i < sessions_nalloc; i++) {
1822 Session *s = &sessions[i];
1823 if (s->used && s->chanid == id) {
1824 debug("session_by_channel: session %d channel %d",
1829 debug("session_by_channel: unknown channel %d", id);
1835 session_by_x11_channel(int id)
1839 for (i = 0; i < sessions_nalloc; i++) {
1840 Session *s = &sessions[i];
1842 if (s->x11_chanids == NULL || !s->used)
1844 for (j = 0; s->x11_chanids[j] != -1; j++) {
1845 if (s->x11_chanids[j] == id) {
1846 debug("session_by_x11_channel: session %d "
1847 "channel %d", s->self, id);
1852 debug("session_by_x11_channel: unknown channel %d", id);
1858 session_by_pid(pid_t pid)
1861 debug("session_by_pid: pid %ld", (long)pid);
1862 for (i = 0; i < sessions_nalloc; i++) {
1863 Session *s = &sessions[i];
1864 if (s->used && s->pid == pid)
1867 error("session_by_pid: unknown pid %ld", (long)pid);
1873 session_window_change_req(Session *s)
1875 s->col = packet_get_int();
1876 s->row = packet_get_int();
1877 s->xpixel = packet_get_int();
1878 s->ypixel = packet_get_int();
1880 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1885 session_pty_req(Session *s)
1890 if (no_pty_flag || !options.permit_tty) {
1891 debug("Allocating a pty not permitted for this authentication.");
1894 if (s->ttyfd != -1) {
1895 packet_disconnect("Protocol error: you already have a pty.");
1899 s->term = packet_get_string(&len);
1900 s->col = packet_get_int();
1901 s->row = packet_get_int();
1902 s->xpixel = packet_get_int();
1903 s->ypixel = packet_get_int();
1905 if (strcmp(s->term, "") == 0) {
1910 /* Allocate a pty and open it. */
1911 debug("Allocating pty.");
1912 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1918 error("session_pty_req: session %d alloc failed", s->self);
1921 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1923 n_bytes = packet_remaining();
1924 tty_parse_modes(s->ttyfd, &n_bytes);
1927 pty_setowner(s->pw, s->tty);
1929 /* Set window size from the packet. */
1930 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1933 session_proctitle(s);
1938 session_subsystem_req(Session *s)
1946 s->subsys = packet_get_string(&len);
1948 debug2("subsystem request for %.100s by user %s", s->subsys,
1951 for (i = 0; i < options.num_subsystems; i++) {
1952 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1953 prog = options.subsystem_command[i];
1954 cmd = options.subsystem_args[i];
1955 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1956 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1957 debug("subsystem: %s", prog);
1959 if (stat(prog, &st) < 0)
1960 debug("subsystem: cannot stat %s: %s",
1961 prog, strerror(errno));
1962 s->is_subsystem = SUBSYSTEM_EXT;
1963 debug("subsystem: exec() %s", cmd);
1965 success = do_exec(s, cmd) == 0;
1971 logit("subsystem request for %.100s by user %s failed, "
1972 "subsystem not found", s->subsys, s->pw->pw_name);
1978 session_x11_req(Session *s)
1982 if (s->auth_proto != NULL || s->auth_data != NULL) {
1983 error("session_x11_req: session %d: "
1984 "x11 forwarding already active", s->self);
1987 s->single_connection = packet_get_char();
1988 s->auth_proto = packet_get_string(NULL);
1989 s->auth_data = packet_get_string(NULL);
1990 s->screen = packet_get_int();
1993 if (xauth_valid_string(s->auth_proto) &&
1994 xauth_valid_string(s->auth_data))
1995 success = session_setup_x11fwd(s);
1998 error("Invalid X11 forwarding data");
2001 free(s->auth_proto);
2003 s->auth_proto = NULL;
2004 s->auth_data = NULL;
2010 session_shell_req(Session *s)
2013 return do_exec(s, NULL) == 0;
2017 session_exec_req(Session *s)
2021 char *command = packet_get_string(&len);
2023 success = do_exec(s, command) == 0;
2029 session_break_req(Session *s)
2032 packet_get_int(); /* ignored */
2035 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2041 session_env_req(Session *s)
2044 u_int name_len, val_len, i;
2046 name = packet_get_cstring(&name_len);
2047 val = packet_get_cstring(&val_len);
2050 /* Don't set too many environment variables */
2051 if (s->num_env > 128) {
2052 debug2("Ignoring env request %s: too many env vars", name);
2056 for (i = 0; i < options.num_accept_env; i++) {
2057 if (match_pattern(name, options.accept_env[i])) {
2058 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2059 s->env = xreallocarray(s->env, s->num_env + 1,
2061 s->env[s->num_env].name = name;
2062 s->env[s->num_env].val = val;
2067 debug2("Ignoring env request %s: disallowed name", name);
2076 session_auth_agent_req(Session *s)
2078 static int called = 0;
2080 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2081 debug("session_auth_agent_req: no_agent_forwarding_flag");
2088 return auth_input_request_forwarding(s->pw);
2093 session_input_channel_req(Channel *c, const char *rtype)
2098 if ((s = session_by_channel(c->self)) == NULL) {
2099 logit("session_input_channel_req: no session %d req %.100s",
2103 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2106 * a session is in LARVAL state until a shell, a command
2107 * or a subsystem is executed
2109 if (c->type == SSH_CHANNEL_LARVAL) {
2110 if (strcmp(rtype, "shell") == 0) {
2111 success = session_shell_req(s);
2112 } else if (strcmp(rtype, "exec") == 0) {
2113 success = session_exec_req(s);
2114 } else if (strcmp(rtype, "pty-req") == 0) {
2115 success = session_pty_req(s);
2116 } else if (strcmp(rtype, "x11-req") == 0) {
2117 success = session_x11_req(s);
2118 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2119 success = session_auth_agent_req(s);
2120 } else if (strcmp(rtype, "subsystem") == 0) {
2121 success = session_subsystem_req(s);
2122 } else if (strcmp(rtype, "env") == 0) {
2123 success = session_env_req(s);
2126 if (strcmp(rtype, "window-change") == 0) {
2127 success = session_window_change_req(s);
2128 } else if (strcmp(rtype, "break") == 0) {
2129 success = session_break_req(s);
2136 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2140 * now that have a child and a pipe to the child,
2141 * we can activate our channel and register the fd's
2143 if (s->chanid == -1)
2144 fatal("no channel for session %d", s->self);
2145 channel_set_fds(s->chanid,
2147 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2148 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2152 * Function to perform pty cleanup. Also called if we get aborted abnormally
2153 * (e.g., due to a dropped connection).
2156 session_pty_cleanup2(Session *s)
2159 error("session_pty_cleanup: no session");
2165 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2167 /* Record that the user has logged out. */
2169 record_logout(s->pid, s->tty, s->pw->pw_name);
2171 /* Release the pseudo-tty. */
2173 pty_release(s->tty);
2176 * Close the server side of the socket pairs. We must do this after
2177 * the pty cleanup, so that another process doesn't get this pty
2178 * while we're still cleaning up.
2180 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2181 error("close(s->ptymaster/%d): %s",
2182 s->ptymaster, strerror(errno));
2184 /* unlink pty from session */
2189 session_pty_cleanup(Session *s)
2191 PRIVSEP(session_pty_cleanup2(s));
2197 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2212 return "SIG@openssh.com";
2216 session_close_x11(int id)
2220 if ((c = channel_by_id(id)) == NULL) {
2221 debug("session_close_x11: x11 channel %d missing", id);
2223 /* Detach X11 listener */
2224 debug("session_close_x11: detach x11 channel %d", id);
2225 channel_cancel_cleanup(id);
2226 if (c->ostate != CHAN_OUTPUT_CLOSED)
2232 session_close_single_x11(int id, void *arg)
2237 debug3("session_close_single_x11: channel %d", id);
2238 channel_cancel_cleanup(id);
2239 if ((s = session_by_x11_channel(id)) == NULL)
2240 fatal("session_close_single_x11: no x11 channel %d", id);
2241 for (i = 0; s->x11_chanids[i] != -1; i++) {
2242 debug("session_close_single_x11: session %d: "
2243 "closing channel %d", s->self, s->x11_chanids[i]);
2245 * The channel "id" is already closing, but make sure we
2246 * close all of its siblings.
2248 if (s->x11_chanids[i] != id)
2249 session_close_x11(s->x11_chanids[i]);
2251 free(s->x11_chanids);
2252 s->x11_chanids = NULL;
2255 free(s->auth_proto);
2256 s->auth_proto = NULL;
2258 s->auth_data = NULL;
2259 free(s->auth_display);
2260 s->auth_display = NULL;
2264 session_exit_message(Session *s, int status)
2268 if ((c = channel_lookup(s->chanid)) == NULL)
2269 fatal("session_exit_message: session %d: no channel %d",
2270 s->self, s->chanid);
2271 debug("session_exit_message: session %d channel %d pid %ld",
2272 s->self, s->chanid, (long)s->pid);
2274 if (WIFEXITED(status)) {
2275 channel_request_start(s->chanid, "exit-status", 0);
2276 packet_put_int(WEXITSTATUS(status));
2278 } else if (WIFSIGNALED(status)) {
2279 channel_request_start(s->chanid, "exit-signal", 0);
2280 packet_put_cstring(sig2name(WTERMSIG(status)));
2282 packet_put_char(WCOREDUMP(status)? 1 : 0);
2283 #else /* WCOREDUMP */
2285 #endif /* WCOREDUMP */
2286 packet_put_cstring("");
2287 packet_put_cstring("");
2290 /* Some weird exit cause. Just exit. */
2291 packet_disconnect("wait returned status %04x.", status);
2294 /* disconnect channel */
2295 debug("session_exit_message: release channel %d", s->chanid);
2298 * Adjust cleanup callback attachment to send close messages when
2299 * the channel gets EOF. The session will be then be closed
2300 * by session_close_by_channel when the childs close their fds.
2302 channel_register_cleanup(c->self, session_close_by_channel, 1);
2305 * emulate a write failure with 'chan_write_failed', nobody will be
2306 * interested in data we write.
2307 * Note that we must not call 'chan_read_failed', since there could
2308 * be some more data waiting in the pipe.
2310 if (c->ostate != CHAN_OUTPUT_CLOSED)
2311 chan_write_failed(c);
2315 session_close(Session *s)
2317 struct ssh *ssh = active_state; /* XXX */
2320 verbose("Close session: user %s from %.200s port %d id %d",
2322 ssh_remote_ipaddr(ssh),
2323 ssh_remote_port(ssh),
2327 session_pty_cleanup(s);
2330 free(s->x11_chanids);
2331 free(s->auth_display);
2333 free(s->auth_proto);
2335 if (s->env != NULL) {
2336 for (i = 0; i < s->num_env; i++) {
2337 free(s->env[i].name);
2338 free(s->env[i].val);
2342 session_proctitle(s);
2343 session_unused(s->self);
2347 session_close_by_pid(pid_t pid, int status)
2349 Session *s = session_by_pid(pid);
2351 debug("session_close_by_pid: no session for pid %ld",
2355 if (s->chanid != -1)
2356 session_exit_message(s, status);
2358 session_pty_cleanup(s);
2363 * this is called when a channel dies before
2364 * the session 'child' itself dies
2367 session_close_by_channel(int id, void *arg)
2369 Session *s = session_by_channel(id);
2373 debug("session_close_by_channel: no session for id %d", id);
2376 debug("session_close_by_channel: channel %d child %ld",
2379 debug("session_close_by_channel: channel %d: has child", id);
2381 * delay detach of session, but release pty, since
2382 * the fd's to the child are already closed
2385 session_pty_cleanup(s);
2388 /* detach by removing callback */
2389 channel_cancel_cleanup(s->chanid);
2391 /* Close any X11 listeners associated with this session */
2392 if (s->x11_chanids != NULL) {
2393 for (i = 0; s->x11_chanids[i] != -1; i++) {
2394 session_close_x11(s->x11_chanids[i]);
2395 s->x11_chanids[i] = -1;
2404 session_destroy_all(void (*closefunc)(Session *))
2407 for (i = 0; i < sessions_nalloc; i++) {
2408 Session *s = &sessions[i];
2410 if (closefunc != NULL)
2419 session_tty_list(void)
2421 static char buf[1024];
2426 for (i = 0; i < sessions_nalloc; i++) {
2427 Session *s = &sessions[i];
2428 if (s->used && s->ttyfd != -1) {
2430 if (strncmp(s->tty, "/dev/", 5) != 0) {
2431 cp = strrchr(s->tty, '/');
2432 cp = (cp == NULL) ? s->tty : cp + 1;
2437 strlcat(buf, ",", sizeof buf);
2438 strlcat(buf, cp, sizeof buf);
2442 strlcpy(buf, "notty", sizeof buf);
2447 session_proctitle(Session *s)
2450 error("no user for session %d", s->self);
2452 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2456 session_setup_x11fwd(Session *s)
2459 char display[512], auth_display[512];
2460 char hostname[NI_MAXHOST];
2463 if (no_x11_forwarding_flag) {
2464 packet_send_debug("X11 forwarding disabled in user configuration file.");
2467 if (!options.x11_forwarding) {
2468 debug("X11 forwarding disabled in server configuration file.");
2471 if (options.xauth_location == NULL ||
2472 (stat(options.xauth_location, &st) == -1)) {
2473 packet_send_debug("No xauth program; cannot forward with spoofing.");
2476 if (s->display != NULL) {
2477 debug("X11 display already set.");
2480 if (x11_create_display_inet(options.x11_display_offset,
2481 options.x11_use_localhost, s->single_connection,
2482 &s->display_number, &s->x11_chanids) == -1) {
2483 debug("x11_create_display_inet failed.");
2486 for (i = 0; s->x11_chanids[i] != -1; i++) {
2487 channel_register_cleanup(s->x11_chanids[i],
2488 session_close_single_x11, 0);
2491 /* Set up a suitable value for the DISPLAY variable. */
2492 if (gethostname(hostname, sizeof(hostname)) < 0)
2493 fatal("gethostname: %.100s", strerror(errno));
2495 * auth_display must be used as the displayname when the
2496 * authorization entry is added with xauth(1). This will be
2497 * different than the DISPLAY string for localhost displays.
2499 if (options.x11_use_localhost) {
2500 snprintf(display, sizeof display, "localhost:%u.%u",
2501 s->display_number, s->screen);
2502 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2503 s->display_number, s->screen);
2504 s->display = xstrdup(display);
2505 s->auth_display = xstrdup(auth_display);
2507 #ifdef IPADDR_IN_DISPLAY
2509 struct in_addr my_addr;
2511 he = gethostbyname(hostname);
2513 error("Can't get IP address for X11 DISPLAY.");
2514 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2517 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2518 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2519 s->display_number, s->screen);
2521 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2522 s->display_number, s->screen);
2524 s->display = xstrdup(display);
2525 s->auth_display = xstrdup(display);
2532 do_authenticated2(Authctxt *authctxt)
2534 server_loop2(authctxt);
2538 do_cleanup(Authctxt *authctxt)
2540 static int called = 0;
2542 debug("do_cleanup");
2544 /* no cleanup if we're in the child for login shell */
2548 /* avoid double cleanup */
2553 if (authctxt == NULL)
2557 if (options.use_pam) {
2559 sshpam_thread_cleanup();
2563 if (!authctxt->authenticated)
2567 if (options.kerberos_ticket_cleanup &&
2569 krb5_cleanup_proc(authctxt);
2573 if (options.gss_cleanup_creds)
2574 ssh_gssapi_cleanup_creds();
2577 /* remove agent socket */
2578 auth_sock_cleanup_proc(authctxt->pw);
2581 * Cleanup ptys/utmp only if privsep is disabled,
2582 * or if running in monitor.
2584 if (!use_privsep || mm_is_monitor())
2585 session_destroy_all(session_pty_cleanup2);
2588 /* Return a name for the remote host that fits inside utmp_size */
2591 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2593 const char *remote = "";
2596 remote = auth_get_canonical_hostname(ssh, use_dns);
2597 if (utmp_size == 0 || strlen(remote) > utmp_size)
2598 remote = ssh_remote_ipaddr(ssh);