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.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
43 #include <sys/socket.h>
47 #include <arpa/inet.h>
66 #include "openbsd-compat/sys-queue.h"
84 #include "auth-options.h"
86 #include "pathnames.h"
91 #include "serverloop.h"
95 #include "monitor_wrap.h"
98 #if defined(KRB5) && defined(USE_AFS)
103 #include <selinux/selinux.h>
106 #define IS_INTERNAL_SFTP(c) \
107 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
108 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
109 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
110 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
114 Session *session_new(void);
115 void session_set_fds(Session *, int, int, int, int, int);
116 void session_pty_cleanup(Session *);
117 void session_proctitle(Session *);
118 int session_setup_x11fwd(Session *);
119 int do_exec_pty(Session *, const char *);
120 int do_exec_no_pty(Session *, const char *);
121 int do_exec(Session *, const char *);
122 void do_login(Session *, const char *);
123 #ifdef LOGIN_NEEDS_UTMPX
124 static void do_pre_login(Session *s);
126 void do_child(Session *, const char *);
128 int check_quietlogin(Session *, const char *);
130 static void do_authenticated2(Authctxt *);
132 static int session_pty_req(Session *);
135 extern ServerOptions options;
136 extern char *__progname;
137 extern int log_stderr;
138 extern int debug_flag;
139 extern u_int utmp_len;
140 extern int startup_pipe;
141 extern void destroy_sensitive_data(void);
142 extern Buffer loginmsg;
144 /* original command from peer. */
145 const char *original_command = NULL;
148 static int sessions_first_unused = -1;
149 static int sessions_nalloc = 0;
150 static Session *sessions = NULL;
152 #define SUBSYSTEM_NONE 0
153 #define SUBSYSTEM_EXT 1
154 #define SUBSYSTEM_INT_SFTP 2
155 #define SUBSYSTEM_INT_SFTP_ERROR 3
157 #ifdef HAVE_LOGIN_CAP
161 static int is_child = 0;
162 static int in_chroot = 0;
164 /* Name and directory of socket for authentication agent forwarding. */
165 static char *auth_sock_name = NULL;
166 static char *auth_sock_dir = NULL;
168 /* removes the agent forwarding socket */
171 auth_sock_cleanup_proc(struct passwd *pw)
173 if (auth_sock_name != NULL) {
174 temporarily_use_uid(pw);
175 unlink(auth_sock_name);
176 rmdir(auth_sock_dir);
177 auth_sock_name = NULL;
183 auth_input_request_forwarding(struct passwd * pw)
188 if (auth_sock_name != NULL) {
189 error("authentication forwarding requested twice.");
193 /* Temporarily drop privileged uid for mkdir/bind. */
194 temporarily_use_uid(pw);
196 /* Allocate a buffer for the socket name, and format the name. */
197 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
199 /* Create private directory for socket */
200 if (mkdtemp(auth_sock_dir) == NULL) {
201 packet_send_debug("Agent forwarding disabled: "
202 "mkdtemp() failed: %.100s", strerror(errno));
205 auth_sock_dir = NULL;
209 xasprintf(&auth_sock_name, "%s/agent.%ld",
210 auth_sock_dir, (long) getpid());
212 /* Start a Unix listener on auth_sock_name. */
213 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
215 /* Restore the privileged uid. */
218 /* Check for socket/bind/listen failure. */
222 /* Allocate a channel for the authentication agent socket. */
223 nc = channel_new("auth socket",
224 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
225 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
226 0, "auth socket", 1);
227 nc->path = xstrdup(auth_sock_name);
231 free(auth_sock_name);
232 if (auth_sock_dir != NULL) {
233 rmdir(auth_sock_dir);
238 auth_sock_name = NULL;
239 auth_sock_dir = NULL;
244 display_loginmsg(void)
246 if (buffer_len(&loginmsg) > 0) {
247 buffer_append(&loginmsg, "\0", 1);
248 printf("%s", (char *)buffer_ptr(&loginmsg));
249 buffer_clear(&loginmsg);
254 do_authenticated(Authctxt *authctxt)
256 setproctitle("%s", authctxt->pw->pw_name);
258 /* setup the channel layer */
259 /* XXX - streamlocal? */
260 if (no_port_forwarding_flag || options.disable_forwarding ||
261 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
262 channel_disable_adm_local_opens();
264 channel_permit_all_opens();
268 do_authenticated2(authctxt);
269 do_cleanup(authctxt);
272 /* Check untrusted xauth strings for metacharacters */
274 xauth_valid_string(const char *s)
278 for (i = 0; s[i] != '\0'; i++) {
279 if (!isalnum((u_char)s[i]) &&
280 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
281 s[i] != '-' && s[i] != '_')
289 * This is called to fork and execute a command when we have no tty. This
290 * will call do_child from the child, and server_loop from the parent after
291 * setting up file descriptors and such.
294 do_exec_no_pty(Session *s, const char *command)
299 int pin[2], pout[2], perr[2];
302 fatal("do_exec_no_pty: no session");
304 /* Allocate pipes for communicating with the program. */
306 error("%s: pipe in: %.100s", __func__, strerror(errno));
309 if (pipe(pout) < 0) {
310 error("%s: pipe out: %.100s", __func__, strerror(errno));
315 if (pipe(perr) < 0) {
316 error("%s: pipe err: %.100s", __func__,
325 int inout[2], err[2];
328 fatal("do_exec_no_pty: no session");
330 /* Uses socket pairs to communicate with the program. */
331 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
332 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
335 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
336 error("%s: socketpair #2: %.100s", __func__,
344 session_proctitle(s);
346 /* Fork the child. */
347 switch ((pid = fork())) {
349 error("%s: fork: %.100s", __func__, strerror(errno));
367 /* Child. Reinitialize the log since the pid has changed. */
368 log_init(__progname, options.log_level,
369 options.log_facility, log_stderr);
372 * Create a new session and process group since the 4.4BSD
373 * setlogin() affects the entire process group.
376 error("setsid failed: %.100s", strerror(errno));
380 * Redirect stdin. We close the parent side of the socket
381 * pair, and make the child side the standard input.
384 if (dup2(pin[0], 0) < 0)
385 perror("dup2 stdin");
388 /* Redirect stdout. */
390 if (dup2(pout[1], 1) < 0)
391 perror("dup2 stdout");
394 /* Redirect stderr. */
396 if (dup2(perr[1], 2) < 0)
397 perror("dup2 stderr");
401 * Redirect stdin, stdout, and stderr. Stdin and stdout will
402 * use the same socket, as some programs (particularly rdist)
403 * seem to depend on it.
407 if (dup2(inout[0], 0) < 0) /* stdin */
408 perror("dup2 stdin");
409 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
410 perror("dup2 stdout");
412 if (dup2(err[0], 2) < 0) /* stderr */
413 perror("dup2 stderr");
419 cray_init_job(s->pw); /* set up cray jid and tmpdir */
422 /* Do processing for the child (exec command etc). */
423 do_child(s, command);
430 signal(WJSIGNAL, cray_job_termination_handler);
433 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
437 /* Set interactive/non-interactive mode. */
438 packet_set_interactive(s->display != NULL,
439 options.ip_qos_interactive, options.ip_qos_bulk);
442 * Clear loginmsg, since it's the child's responsibility to display
443 * it to the user, otherwise multiple sessions may accumulate
444 * multiple copies of the login messages.
446 buffer_clear(&loginmsg);
449 /* We are the parent. Close the child sides of the pipes. */
454 session_set_fds(s, pin[1], pout[0], perr[0],
457 /* We are the parent. Close the child sides of the socket pairs. */
462 * Enter the interactive session. Note: server_loop must be able to
463 * handle the case that fdin and fdout are the same.
465 session_set_fds(s, inout[1], inout[1], err[1],
472 * This is called to fork and execute a command when we have a tty. This
473 * will call do_child from the child, and server_loop from the parent after
474 * setting up file descriptors, controlling tty, updating wtmp, utmp,
475 * lastlog, and other such operations.
478 do_exec_pty(Session *s, const char *command)
480 int fdout, ptyfd, ttyfd, ptymaster;
484 fatal("do_exec_pty: no session");
489 * Create another descriptor of the pty master side for use as the
490 * standard input. We could use the original descriptor, but this
491 * simplifies code in server_loop. The descriptor is bidirectional.
492 * Do this before forking (and cleanup in the child) so as to
493 * detect and gracefully fail out-of-fd conditions.
495 if ((fdout = dup(ptyfd)) < 0) {
496 error("%s: dup #1: %s", __func__, strerror(errno));
501 /* we keep a reference to the pty master */
502 if ((ptymaster = dup(ptyfd)) < 0) {
503 error("%s: dup #2: %s", __func__, strerror(errno));
510 /* Fork the child. */
511 switch ((pid = fork())) {
513 error("%s: fork: %.100s", __func__, strerror(errno));
525 /* Child. Reinitialize the log because the pid has changed. */
526 log_init(__progname, options.log_level,
527 options.log_facility, log_stderr);
528 /* Close the master side of the pseudo tty. */
531 /* Make the pseudo tty our controlling tty. */
532 pty_make_controlling_tty(&ttyfd, s->tty);
534 /* Redirect stdin/stdout/stderr from the pseudo tty. */
535 if (dup2(ttyfd, 0) < 0)
536 error("dup2 stdin: %s", strerror(errno));
537 if (dup2(ttyfd, 1) < 0)
538 error("dup2 stdout: %s", strerror(errno));
539 if (dup2(ttyfd, 2) < 0)
540 error("dup2 stderr: %s", strerror(errno));
542 /* Close the extra descriptor for the pseudo tty. */
545 /* record login, etc. similar to login(1) */
547 cray_init_job(s->pw); /* set up cray jid and tmpdir */
550 do_login(s, command);
553 * Do common processing for the child, such as execing
556 do_child(s, command);
563 signal(WJSIGNAL, cray_job_termination_handler);
566 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
571 /* Parent. Close the slave side of the pseudo tty. */
574 /* Enter interactive session. */
575 s->ptymaster = ptymaster;
576 packet_set_interactive(1,
577 options.ip_qos_interactive, options.ip_qos_bulk);
578 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
582 #ifdef LOGIN_NEEDS_UTMPX
584 do_pre_login(Session *s)
586 struct ssh *ssh = active_state; /* XXX */
588 struct sockaddr_storage from;
589 pid_t pid = getpid();
592 * Get IP address of client. If the connection is not a socket, let
593 * the address be 0.0.0.0.
595 memset(&from, 0, sizeof(from));
596 fromlen = sizeof(from);
597 if (packet_connection_is_on_socket()) {
598 if (getpeername(packet_get_connection_in(),
599 (struct sockaddr *)&from, &fromlen) < 0) {
600 debug("getpeername: %.100s", strerror(errno));
605 record_utmp_only(pid, s->tty, s->pw->pw_name,
606 session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
607 (struct sockaddr *)&from, fromlen);
612 * This is called to fork and execute a command. If another command is
613 * to be forced, execute that instead.
616 do_exec(Session *s, const char *command)
618 struct ssh *ssh = active_state; /* XXX */
620 const char *forced = NULL, *tty = NULL;
621 char session_type[1024];
623 if (options.adm_forced_command) {
624 original_command = command;
625 command = options.adm_forced_command;
627 } else if (forced_command) {
628 original_command = command;
629 command = forced_command;
630 forced = "(key-option)";
632 if (forced != NULL) {
633 if (IS_INTERNAL_SFTP(command)) {
634 s->is_subsystem = s->is_subsystem ?
635 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
636 } else if (s->is_subsystem)
637 s->is_subsystem = SUBSYSTEM_EXT;
638 snprintf(session_type, sizeof(session_type),
639 "forced-command %s '%.900s'", forced, command);
640 } else if (s->is_subsystem) {
641 snprintf(session_type, sizeof(session_type),
642 "subsystem '%.900s'", s->subsys);
643 } else if (command == NULL) {
644 snprintf(session_type, sizeof(session_type), "shell");
646 /* NB. we don't log unforced commands to preserve privacy */
647 snprintf(session_type, sizeof(session_type), "command");
650 if (s->ttyfd != -1) {
652 if (strncmp(tty, "/dev/", 5) == 0)
656 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
658 tty == NULL ? "" : " on ",
659 tty == NULL ? "" : tty,
661 ssh_remote_ipaddr(ssh),
662 ssh_remote_port(ssh),
665 #ifdef SSH_AUDIT_EVENTS
667 PRIVSEP(audit_run_command(command));
668 else if (s->ttyfd == -1) {
669 char *shell = s->pw->pw_shell;
671 if (shell[0] == '\0') /* empty shell means /bin/sh */
673 PRIVSEP(audit_run_command(shell));
677 ret = do_exec_pty(s, command);
679 ret = do_exec_no_pty(s, command);
681 original_command = NULL;
684 * Clear loginmsg: it's the child's responsibility to display
685 * it to the user, otherwise multiple sessions may accumulate
686 * multiple copies of the login messages.
688 buffer_clear(&loginmsg);
693 /* administrative, login(1)-like work */
695 do_login(Session *s, const char *command)
697 struct ssh *ssh = active_state; /* XXX */
699 struct sockaddr_storage from;
700 struct passwd * pw = s->pw;
701 pid_t pid = getpid();
704 * Get IP address of client. If the connection is not a socket, let
705 * the address be 0.0.0.0.
707 memset(&from, 0, sizeof(from));
708 fromlen = sizeof(from);
709 if (packet_connection_is_on_socket()) {
710 if (getpeername(packet_get_connection_in(),
711 (struct sockaddr *)&from, &fromlen) < 0) {
712 debug("getpeername: %.100s", strerror(errno));
717 /* Record that there was a login on that tty from the remote host. */
719 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
720 session_get_remote_name_or_ip(ssh, utmp_len,
722 (struct sockaddr *)&from, fromlen);
726 * If password change is needed, do it now.
727 * This needs to occur before the ~/.hushlogin check.
729 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
732 s->authctxt->force_pwchange = 0;
733 /* XXX - signal [net] parent to enable forwardings */
737 if (check_quietlogin(s, command))
746 * Display the message of the day.
754 if (options.print_motd) {
755 #ifdef HAVE_LOGIN_CAP
756 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
759 f = fopen("/etc/motd", "r");
762 while (fgets(buf, sizeof(buf), f))
771 * Check for quiet login, either .hushlogin or command given.
774 check_quietlogin(Session *s, const char *command)
777 struct passwd *pw = s->pw;
780 /* Return 1 if .hushlogin exists or a command given. */
783 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
784 #ifdef HAVE_LOGIN_CAP
785 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
788 if (stat(buf, &st) >= 0)
795 * Sets the value of the given variable in the environment. If the variable
796 * already exists, its value is overridden.
799 child_set_env(char ***envp, u_int *envsizep, const char *name,
806 if (strchr(name, '=') != NULL) {
807 error("Invalid environment variable \"%.100s\"", name);
812 * If we're passed an uninitialized list, allocate a single null
813 * entry before continuing.
815 if (*envp == NULL && *envsizep == 0) {
816 *envp = xmalloc(sizeof(char *));
822 * Find the slot where the value should be stored. If the variable
823 * already exists, we reuse the slot; otherwise we append a new slot
824 * at the end of the array, expanding if necessary.
827 namelen = strlen(name);
828 for (i = 0; env[i]; i++)
829 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
832 /* Reuse the slot. */
835 /* New variable. Expand if necessary. */
837 if (i >= envsize - 1) {
839 fatal("child_set_env: too many env vars");
841 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
844 /* Need to set the NULL pointer at end of array beyond the new slot. */
848 /* Allocate space and format the variable in the appropriate slot. */
849 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
850 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
854 * Reads environment variables from the given file and adds/overrides them
855 * into the environment. If the file does not exist, this does nothing.
856 * Otherwise, it must consist of empty lines, comments (line starts with '#')
857 * and assignments of the form name=value. No other forms are allowed.
860 read_environment_file(char ***env, u_int *envsize,
861 const char *filename)
868 f = fopen(filename, "r");
872 while (fgets(buf, sizeof(buf), f)) {
874 fatal("Too many lines in environment file %s", filename);
875 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
877 if (!*cp || *cp == '#' || *cp == '\n')
880 cp[strcspn(cp, "\n")] = '\0';
882 value = strchr(cp, '=');
884 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
889 * Replace the equals sign by nul, and advance value to
894 child_set_env(env, envsize, cp, value);
899 #ifdef HAVE_ETC_DEFAULT_LOGIN
901 * Return named variable from specified environment, or NULL if not present.
904 child_get_env(char **env, const char *name)
910 for (i=0; env[i] != NULL; i++)
911 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
912 return(env[i] + len + 1);
917 * Read /etc/default/login.
918 * We pick up the PATH (or SUPATH for root) and UMASK.
921 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
923 char **tmpenv = NULL, *var;
924 u_int i, tmpenvsize = 0;
928 * We don't want to copy the whole file to the child's environment,
929 * so we use a temporary environment and copy the variables we're
932 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
938 var = child_get_env(tmpenv, "SUPATH");
940 var = child_get_env(tmpenv, "PATH");
942 child_set_env(env, envsize, "PATH", var);
944 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
945 if (sscanf(var, "%5lo", &mask) == 1)
948 for (i = 0; tmpenv[i] != NULL; i++)
952 #endif /* HAVE_ETC_DEFAULT_LOGIN */
955 copy_environment(char **source, char ***env, u_int *envsize)
957 char *var_name, *var_val;
963 for(i = 0; source[i] != NULL; i++) {
964 var_name = xstrdup(source[i]);
965 if ((var_val = strstr(var_name, "=")) == NULL) {
971 debug3("Copy environment: %s=%s", var_name, var_val);
972 child_set_env(env, envsize, var_name, var_val);
979 do_setup_env(Session *s, const char *shell)
981 struct ssh *ssh = active_state; /* XXX */
985 struct passwd *pw = s->pw;
986 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
990 /* Initialize the environment. */
992 env = xcalloc(envsize, sizeof(char *));
997 * The Windows environment contains some setting which are
998 * important for a running system. They must not be dropped.
1003 p = fetch_windows_environment();
1004 copy_environment(p, &env, &envsize);
1005 free_windows_environment(p);
1010 /* Allow any GSSAPI methods that we've used to alter
1011 * the childs environment as they see fit
1013 ssh_gssapi_do_child(&env, &envsize);
1016 /* Set basic environment. */
1017 for (i = 0; i < s->num_env; i++)
1018 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1020 child_set_env(&env, &envsize, "USER", pw->pw_name);
1021 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1023 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1025 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1026 #ifdef HAVE_LOGIN_CAP
1027 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1028 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1030 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1031 #else /* HAVE_LOGIN_CAP */
1032 # ifndef HAVE_CYGWIN
1034 * There's no standard path on Windows. The path contains
1035 * important components pointing to the system directories,
1036 * needed for loading shared libraries. So the path better
1037 * remains intact here.
1039 # ifdef HAVE_ETC_DEFAULT_LOGIN
1040 read_etc_default_login(&env, &envsize, pw->pw_uid);
1041 path = child_get_env(env, "PATH");
1042 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1043 if (path == NULL || *path == '\0') {
1044 child_set_env(&env, &envsize, "PATH",
1045 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1047 # endif /* HAVE_CYGWIN */
1048 #endif /* HAVE_LOGIN_CAP */
1051 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1052 child_set_env(&env, &envsize, "MAIL", buf);
1054 /* Normal systems set SHELL by default. */
1055 child_set_env(&env, &envsize, "SHELL", shell);
1059 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1061 /* Set custom environment options from RSA authentication. */
1062 while (custom_environment) {
1063 struct envstring *ce = custom_environment;
1066 for (i = 0; str[i] != '=' && str[i]; i++)
1068 if (str[i] == '=') {
1070 child_set_env(&env, &envsize, str, str + i + 1);
1072 custom_environment = ce->next;
1077 /* SSH_CLIENT deprecated */
1078 snprintf(buf, sizeof buf, "%.50s %d %d",
1079 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1080 ssh_local_port(ssh));
1081 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1083 laddr = get_local_ipaddr(packet_get_connection_in());
1084 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1085 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1086 laddr, ssh_local_port(ssh));
1088 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1091 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1093 child_set_env(&env, &envsize, "TERM", s->term);
1095 child_set_env(&env, &envsize, "DISPLAY", s->display);
1096 if (original_command)
1097 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1101 if (cray_tmpdir[0] != '\0')
1102 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1103 #endif /* _UNICOS */
1106 * Since we clear KRB5CCNAME at startup, if it's set now then it
1107 * must have been set by a native authentication method (eg AIX or
1108 * SIA), so copy it to the child.
1113 if ((cp = getenv("KRB5CCNAME")) != NULL)
1114 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1121 if ((cp = getenv("AUTHSTATE")) != NULL)
1122 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1123 read_environment_file(&env, &envsize, "/etc/environment");
1127 if (s->authctxt->krb5_ccname)
1128 child_set_env(&env, &envsize, "KRB5CCNAME",
1129 s->authctxt->krb5_ccname);
1133 * Pull in any environment variables that may have
1136 if (options.use_pam) {
1139 p = fetch_pam_child_environment();
1140 copy_environment(p, &env, &envsize);
1141 free_pam_environment(p);
1143 p = fetch_pam_environment();
1144 copy_environment(p, &env, &envsize);
1145 free_pam_environment(p);
1147 #endif /* USE_PAM */
1149 if (auth_sock_name != NULL)
1150 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1153 /* read $HOME/.ssh/environment. */
1154 if (options.permit_user_env) {
1155 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1156 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1157 read_environment_file(&env, &envsize, buf);
1160 /* dump the environment */
1161 fprintf(stderr, "Environment:\n");
1162 for (i = 0; env[i]; i++)
1163 fprintf(stderr, " %.200s\n", env[i]);
1169 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1170 * first in this order).
1173 do_rc_files(Session *s, const char *shell)
1181 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1183 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1184 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1185 !no_user_rc && options.permit_user_rc &&
1186 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1187 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1188 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1190 fprintf(stderr, "Running %s\n", cmd);
1191 f = popen(cmd, "w");
1194 fprintf(f, "%s %s\n", s->auth_proto,
1198 fprintf(stderr, "Could not run %s\n",
1200 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1202 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1203 _PATH_SSH_SYSTEM_RC);
1204 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1207 fprintf(f, "%s %s\n", s->auth_proto,
1211 fprintf(stderr, "Could not run %s\n",
1212 _PATH_SSH_SYSTEM_RC);
1213 } else if (do_xauth && options.xauth_location != NULL) {
1214 /* Add authority data to .Xauthority if appropriate. */
1217 "Running %.500s remove %.100s\n",
1218 options.xauth_location, s->auth_display);
1220 "%.500s add %.100s %.100s %.100s\n",
1221 options.xauth_location, s->auth_display,
1222 s->auth_proto, s->auth_data);
1224 snprintf(cmd, sizeof cmd, "%s -q -",
1225 options.xauth_location);
1226 f = popen(cmd, "w");
1228 fprintf(f, "remove %s\n",
1230 fprintf(f, "add %s %s %s\n",
1231 s->auth_display, s->auth_proto,
1235 fprintf(stderr, "Could not run %s\n",
1242 do_nologin(struct passwd *pw)
1245 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1248 #ifdef HAVE_LOGIN_CAP
1249 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1251 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1253 if (pw->pw_uid == 0)
1257 if (stat(nl, &sb) == -1) {
1263 /* /etc/nologin exists. Print its contents if we can and exit. */
1264 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1265 if ((f = fopen(nl, "r")) != NULL) {
1266 while (fgets(buf, sizeof(buf), f))
1274 * Chroot into a directory after checking it for safety: all path components
1275 * must be root-owned directories with strict permissions.
1278 safely_chroot(const char *path, uid_t uid)
1281 char component[PATH_MAX];
1285 fatal("chroot path does not begin at root");
1286 if (strlen(path) >= sizeof(component))
1287 fatal("chroot path too long");
1290 * Descend the path, checking that each component is a
1291 * root-owned directory with strict permissions.
1293 for (cp = path; cp != NULL;) {
1294 if ((cp = strchr(cp, '/')) == NULL)
1295 strlcpy(component, path, sizeof(component));
1298 memcpy(component, path, cp - path);
1299 component[cp - path] = '\0';
1302 debug3("%s: checking '%s'", __func__, component);
1304 if (stat(component, &st) != 0)
1305 fatal("%s: stat(\"%s\"): %s", __func__,
1306 component, strerror(errno));
1307 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1308 fatal("bad ownership or modes for chroot "
1309 "directory %s\"%s\"",
1310 cp == NULL ? "" : "component ", component);
1311 if (!S_ISDIR(st.st_mode))
1312 fatal("chroot path %s\"%s\" is not a directory",
1313 cp == NULL ? "" : "component ", component);
1317 if (chdir(path) == -1)
1318 fatal("Unable to chdir to chroot path \"%s\": "
1319 "%s", path, strerror(errno));
1320 if (chroot(path) == -1)
1321 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1322 if (chdir("/") == -1)
1323 fatal("%s: chdir(/) after chroot: %s",
1324 __func__, strerror(errno));
1325 verbose("Changed root directory to \"%s\"", path);
1328 /* Set login name, uid, gid, and groups. */
1330 do_setusercontext(struct passwd *pw)
1332 char *chroot_path, *tmp;
1334 platform_setusercontext(pw);
1336 if (platform_privileged_uidswap()) {
1337 #ifdef HAVE_LOGIN_CAP
1338 if (setusercontext(lc, pw, pw->pw_uid,
1339 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1340 perror("unable to set user context");
1344 if (setlogin(pw->pw_name) < 0)
1345 error("setlogin failed: %s", strerror(errno));
1346 if (setgid(pw->pw_gid) < 0) {
1350 /* Initialize the group list. */
1351 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1352 perror("initgroups");
1355 #if !defined(ANDROID)
1360 platform_setusercontext_post_groups(pw);
1362 if (!in_chroot && options.chroot_directory != NULL &&
1363 strcasecmp(options.chroot_directory, "none") != 0) {
1364 tmp = tilde_expand_filename(options.chroot_directory,
1366 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1367 "u", pw->pw_name, (char *)NULL);
1368 safely_chroot(chroot_path, pw->pw_uid);
1371 /* Make sure we don't attempt to chroot again */
1372 free(options.chroot_directory);
1373 options.chroot_directory = NULL;
1377 #ifdef HAVE_LOGIN_CAP
1378 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1379 perror("unable to set user context (setuser)");
1383 * FreeBSD's setusercontext() will not apply the user's
1384 * own umask setting unless running with the user's UID.
1386 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1390 * In a chroot environment, the set_id() will always fail;
1391 * typically because of the lack of necessary authentication
1392 * services and runtime such as ./usr/lib/libiaf.so,
1393 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1394 * internal sftp chroot case. We'll lose auditing and ACLs but
1395 * permanently_set_uid will take care of the rest.
1397 if (!in_chroot && set_id(pw->pw_name) != 0)
1398 fatal("set_id(%s) Failed", pw->pw_name);
1399 # endif /* USE_LIBIAF */
1400 /* Permanently switch to the desired uid. */
1401 permanently_set_uid(pw);
1403 } else if (options.chroot_directory != NULL &&
1404 strcasecmp(options.chroot_directory, "none") != 0) {
1405 fatal("server lacks privileges to chroot to ChrootDirectory");
1408 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1409 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1413 do_pwchange(Session *s)
1416 fprintf(stderr, "WARNING: Your password has expired.\n");
1417 if (s->ttyfd != -1) {
1419 "You must change your password now and login again!\n");
1423 #ifdef PASSWD_NEEDS_USERNAME
1424 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1427 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1432 "Password change required but no TTY available.\n");
1438 child_close_fds(void)
1440 extern int auth_sock;
1442 if (auth_sock != -1) {
1447 if (packet_get_connection_in() == packet_get_connection_out())
1448 close(packet_get_connection_in());
1450 close(packet_get_connection_in());
1451 close(packet_get_connection_out());
1454 * Close all descriptors related to channels. They will still remain
1455 * open in the parent.
1457 /* XXX better use close-on-exec? -markus */
1458 channel_close_all();
1460 #if !defined(ANDROID)
1462 * Close any extra file descriptors. Note that there may still be
1463 * descriptors left by system functions. They will be closed later.
1469 * Close any extra open file descriptors so that we don't have them
1470 * hanging around in clients. Note that we want to do this after
1471 * initgroups, because at least on Solaris 2.3 it leaves file
1474 closefrom(STDERR_FILENO + 1);
1478 * Performs common processing for the child, such as setting up the
1479 * environment, closing extra file descriptors, setting the user and group
1480 * ids, and executing the command or shell.
1484 do_child(Session *s, const char *command)
1486 extern char **environ;
1488 char *argv[ARGV_MAX];
1489 const char *shell, *shell0;
1490 struct passwd *pw = s->pw;
1493 /* remove hostkey from the child's memory */
1494 destroy_sensitive_data();
1496 /* Force a password change */
1497 if (s->authctxt->force_pwchange) {
1498 do_setusercontext(pw);
1505 cray_setup(pw->pw_uid, pw->pw_name, command);
1506 #endif /* _UNICOS */
1509 * Login(1) does this as well, and it needs uid 0 for the "-h"
1510 * switch, so we let login(1) to this for us.
1513 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1514 if (!check_quietlogin(s, command))
1516 #else /* HAVE_OSF_SIA */
1517 /* When PAM is enabled we rely on it to do the nologin check */
1518 if (!options.use_pam)
1520 do_setusercontext(pw);
1522 * PAM session modules in do_setusercontext may have
1523 * generated messages, so if this in an interactive
1524 * login then display them too.
1526 if (!check_quietlogin(s, command))
1528 #endif /* HAVE_OSF_SIA */
1531 if (options.use_pam && !is_pam_session_open()) {
1532 debug3("PAM session not opened, exiting");
1539 * Get the shell from the password data. An empty shell field is
1540 * legal, and means /bin/sh.
1542 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1545 * Make sure $SHELL points to the shell from the password file,
1546 * even if shell is overridden from login.conf
1548 env = do_setup_env(s, shell);
1550 #ifdef HAVE_LOGIN_CAP
1551 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1555 * Close the connection descriptors; note that this is the child, and
1556 * the server will still have the socket open, and it is important
1557 * that we do not shutdown it. Note that the descriptors cannot be
1558 * closed before building the environment, as we call
1559 * ssh_remote_ipaddr there.
1564 * Must take new environment into use so that .ssh/rc,
1565 * /etc/ssh/sshrc and xauth are run in the proper environment.
1569 #if defined(KRB5) && defined(USE_AFS)
1571 * At this point, we check to see if AFS is active and if we have
1572 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1573 * if we can (and need to) extend the ticket into an AFS token. If
1574 * we don't do this, we run into potential problems if the user's
1575 * home directory is in AFS and it's not world-readable.
1578 if (options.kerberos_get_afs_token && k_hasafs() &&
1579 (s->authctxt->krb5_ctx != NULL)) {
1582 debug("Getting AFS token");
1586 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1587 krb5_afslog(s->authctxt->krb5_ctx,
1588 s->authctxt->krb5_fwd_ccache, cell, NULL);
1590 krb5_afslog_home(s->authctxt->krb5_ctx,
1591 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1595 /* Change current directory to the user's home directory. */
1596 if (chdir(pw->pw_dir) < 0) {
1597 /* Suppress missing homedir warning for chroot case */
1598 #ifdef HAVE_LOGIN_CAP
1599 r = login_getcapbool(lc, "requirehome", 0);
1601 if (r || !in_chroot) {
1602 fprintf(stderr, "Could not chdir to home "
1603 "directory %s: %s\n", pw->pw_dir,
1610 closefrom(STDERR_FILENO + 1);
1612 do_rc_files(s, shell);
1614 /* restore SIGPIPE for child */
1615 signal(SIGPIPE, SIG_DFL);
1617 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1618 printf("This service allows sftp connections only.\n");
1621 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1622 extern int optind, optreset;
1626 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1627 args = xstrdup(command ? command : "sftp-server");
1628 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1629 if (i < ARGV_MAX - 1)
1632 optind = optreset = 1;
1633 __progname = argv[0];
1635 ssh_selinux_change_context("sftpd_t");
1637 exit(sftp_server_main(i, argv, s->pw));
1642 /* Get the last component of the shell name. */
1643 if ((shell0 = strrchr(shell, '/')) != NULL)
1649 * If we have no command, execute the shell. In this case, the shell
1650 * name to be passed in argv[0] is preceded by '-' to indicate that
1651 * this is a login shell.
1656 /* Start the shell. Set initial character to '-'. */
1659 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1660 >= sizeof(argv0) - 1) {
1666 /* Execute the shell. */
1669 execve(shell, argv, env);
1671 /* Executing the shell failed. */
1676 * Execute the command using the user's shell. This uses the -c
1677 * option to execute the command.
1679 argv[0] = (char *) shell0;
1681 argv[2] = (char *) command;
1683 execve(shell, argv, env);
1689 session_unused(int id)
1691 debug3("%s: session id %d unused", __func__, id);
1692 if (id >= options.max_sessions ||
1693 id >= sessions_nalloc) {
1694 fatal("%s: insane session id %d (max %d nalloc %d)",
1695 __func__, id, options.max_sessions, sessions_nalloc);
1697 memset(&sessions[id], 0, sizeof(*sessions));
1698 sessions[id].self = id;
1699 sessions[id].used = 0;
1700 sessions[id].chanid = -1;
1701 sessions[id].ptyfd = -1;
1702 sessions[id].ttyfd = -1;
1703 sessions[id].ptymaster = -1;
1704 sessions[id].x11_chanids = NULL;
1705 sessions[id].next_unused = sessions_first_unused;
1706 sessions_first_unused = id;
1714 if (sessions_first_unused == -1) {
1715 if (sessions_nalloc >= options.max_sessions)
1717 debug2("%s: allocate (allocated %d max %d)",
1718 __func__, sessions_nalloc, options.max_sessions);
1719 tmp = xreallocarray(sessions, sessions_nalloc + 1,
1722 error("%s: cannot allocate %d sessions",
1723 __func__, sessions_nalloc + 1);
1727 session_unused(sessions_nalloc++);
1730 if (sessions_first_unused >= sessions_nalloc ||
1731 sessions_first_unused < 0) {
1732 fatal("%s: insane first_unused %d max %d nalloc %d",
1733 __func__, sessions_first_unused, options.max_sessions,
1737 s = &sessions[sessions_first_unused];
1739 fatal("%s: session %d already used",
1740 __func__, sessions_first_unused);
1742 sessions_first_unused = s->next_unused;
1744 s->next_unused = -1;
1745 debug("session_new: session %d", s->self);
1754 for (i = 0; i < sessions_nalloc; i++) {
1755 Session *s = &sessions[i];
1757 debug("dump: used %d next_unused %d session %d %p "
1758 "channel %d pid %ld",
1769 session_open(Authctxt *authctxt, int chanid)
1771 Session *s = session_new();
1772 debug("session_open: channel %d", chanid);
1774 error("no more sessions");
1777 s->authctxt = authctxt;
1778 s->pw = authctxt->pw;
1779 if (s->pw == NULL || !authctxt->valid)
1780 fatal("no user for session %d", s->self);
1781 debug("session_open: session %d: link with channel %d", s->self, chanid);
1787 session_by_tty(char *tty)
1790 for (i = 0; i < sessions_nalloc; i++) {
1791 Session *s = &sessions[i];
1792 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1793 debug("session_by_tty: session %d tty %s", i, tty);
1797 debug("session_by_tty: unknown tty %.100s", tty);
1803 session_by_channel(int id)
1806 for (i = 0; i < sessions_nalloc; i++) {
1807 Session *s = &sessions[i];
1808 if (s->used && s->chanid == id) {
1809 debug("session_by_channel: session %d channel %d",
1814 debug("session_by_channel: unknown channel %d", id);
1820 session_by_x11_channel(int id)
1824 for (i = 0; i < sessions_nalloc; i++) {
1825 Session *s = &sessions[i];
1827 if (s->x11_chanids == NULL || !s->used)
1829 for (j = 0; s->x11_chanids[j] != -1; j++) {
1830 if (s->x11_chanids[j] == id) {
1831 debug("session_by_x11_channel: session %d "
1832 "channel %d", s->self, id);
1837 debug("session_by_x11_channel: unknown channel %d", id);
1843 session_by_pid(pid_t pid)
1846 debug("session_by_pid: pid %ld", (long)pid);
1847 for (i = 0; i < sessions_nalloc; i++) {
1848 Session *s = &sessions[i];
1849 if (s->used && s->pid == pid)
1852 error("session_by_pid: unknown pid %ld", (long)pid);
1858 session_window_change_req(Session *s)
1860 s->col = packet_get_int();
1861 s->row = packet_get_int();
1862 s->xpixel = packet_get_int();
1863 s->ypixel = packet_get_int();
1865 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1870 session_pty_req(Session *s)
1875 if (no_pty_flag || !options.permit_tty) {
1876 debug("Allocating a pty not permitted for this authentication.");
1879 if (s->ttyfd != -1) {
1880 packet_disconnect("Protocol error: you already have a pty.");
1884 s->term = packet_get_string(&len);
1885 s->col = packet_get_int();
1886 s->row = packet_get_int();
1887 s->xpixel = packet_get_int();
1888 s->ypixel = packet_get_int();
1890 if (strcmp(s->term, "") == 0) {
1895 /* Allocate a pty and open it. */
1896 debug("Allocating pty.");
1897 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1903 error("session_pty_req: session %d alloc failed", s->self);
1906 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1908 n_bytes = packet_remaining();
1909 tty_parse_modes(s->ttyfd, &n_bytes);
1912 pty_setowner(s->pw, s->tty);
1914 /* Set window size from the packet. */
1915 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1918 session_proctitle(s);
1923 session_subsystem_req(Session *s)
1931 s->subsys = packet_get_string(&len);
1933 debug2("subsystem request for %.100s by user %s", s->subsys,
1936 for (i = 0; i < options.num_subsystems; i++) {
1937 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1938 prog = options.subsystem_command[i];
1939 cmd = options.subsystem_args[i];
1940 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1941 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1942 debug("subsystem: %s", prog);
1944 if (stat(prog, &st) < 0)
1945 debug("subsystem: cannot stat %s: %s",
1946 prog, strerror(errno));
1947 s->is_subsystem = SUBSYSTEM_EXT;
1948 debug("subsystem: exec() %s", cmd);
1950 success = do_exec(s, cmd) == 0;
1956 logit("subsystem request for %.100s by user %s failed, "
1957 "subsystem not found", s->subsys, s->pw->pw_name);
1963 session_x11_req(Session *s)
1967 if (s->auth_proto != NULL || s->auth_data != NULL) {
1968 error("session_x11_req: session %d: "
1969 "x11 forwarding already active", s->self);
1972 s->single_connection = packet_get_char();
1973 s->auth_proto = packet_get_string(NULL);
1974 s->auth_data = packet_get_string(NULL);
1975 s->screen = packet_get_int();
1978 if (xauth_valid_string(s->auth_proto) &&
1979 xauth_valid_string(s->auth_data))
1980 success = session_setup_x11fwd(s);
1983 error("Invalid X11 forwarding data");
1986 free(s->auth_proto);
1988 s->auth_proto = NULL;
1989 s->auth_data = NULL;
1995 session_shell_req(Session *s)
1998 return do_exec(s, NULL) == 0;
2002 session_exec_req(Session *s)
2006 char *command = packet_get_string(&len);
2008 success = do_exec(s, command) == 0;
2014 session_break_req(Session *s)
2017 packet_get_int(); /* ignored */
2020 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2026 session_env_req(Session *s)
2029 u_int name_len, val_len, i;
2031 name = packet_get_cstring(&name_len);
2032 val = packet_get_cstring(&val_len);
2035 /* Don't set too many environment variables */
2036 if (s->num_env > 128) {
2037 debug2("Ignoring env request %s: too many env vars", name);
2041 for (i = 0; i < options.num_accept_env; i++) {
2042 if (match_pattern(name, options.accept_env[i])) {
2043 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2044 s->env = xreallocarray(s->env, s->num_env + 1,
2046 s->env[s->num_env].name = name;
2047 s->env[s->num_env].val = val;
2052 debug2("Ignoring env request %s: disallowed name", name);
2061 session_auth_agent_req(Session *s)
2063 static int called = 0;
2065 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2066 debug("session_auth_agent_req: no_agent_forwarding_flag");
2073 return auth_input_request_forwarding(s->pw);
2078 session_input_channel_req(Channel *c, const char *rtype)
2083 if ((s = session_by_channel(c->self)) == NULL) {
2084 logit("session_input_channel_req: no session %d req %.100s",
2088 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2091 * a session is in LARVAL state until a shell, a command
2092 * or a subsystem is executed
2094 if (c->type == SSH_CHANNEL_LARVAL) {
2095 if (strcmp(rtype, "shell") == 0) {
2096 success = session_shell_req(s);
2097 } else if (strcmp(rtype, "exec") == 0) {
2098 success = session_exec_req(s);
2099 } else if (strcmp(rtype, "pty-req") == 0) {
2100 success = session_pty_req(s);
2101 } else if (strcmp(rtype, "x11-req") == 0) {
2102 success = session_x11_req(s);
2103 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2104 success = session_auth_agent_req(s);
2105 } else if (strcmp(rtype, "subsystem") == 0) {
2106 success = session_subsystem_req(s);
2107 } else if (strcmp(rtype, "env") == 0) {
2108 success = session_env_req(s);
2111 if (strcmp(rtype, "window-change") == 0) {
2112 success = session_window_change_req(s);
2113 } else if (strcmp(rtype, "break") == 0) {
2114 success = session_break_req(s);
2121 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2125 * now that have a child and a pipe to the child,
2126 * we can activate our channel and register the fd's
2128 if (s->chanid == -1)
2129 fatal("no channel for session %d", s->self);
2130 channel_set_fds(s->chanid,
2132 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2133 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2137 * Function to perform pty cleanup. Also called if we get aborted abnormally
2138 * (e.g., due to a dropped connection).
2141 session_pty_cleanup2(Session *s)
2144 error("session_pty_cleanup: no session");
2150 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2152 /* Record that the user has logged out. */
2154 record_logout(s->pid, s->tty, s->pw->pw_name);
2156 /* Release the pseudo-tty. */
2158 pty_release(s->tty);
2161 * Close the server side of the socket pairs. We must do this after
2162 * the pty cleanup, so that another process doesn't get this pty
2163 * while we're still cleaning up.
2165 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2166 error("close(s->ptymaster/%d): %s",
2167 s->ptymaster, strerror(errno));
2169 /* unlink pty from session */
2174 session_pty_cleanup(Session *s)
2176 PRIVSEP(session_pty_cleanup2(s));
2182 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2197 return "SIG@openssh.com";
2201 session_close_x11(int id)
2205 if ((c = channel_by_id(id)) == NULL) {
2206 debug("session_close_x11: x11 channel %d missing", id);
2208 /* Detach X11 listener */
2209 debug("session_close_x11: detach x11 channel %d", id);
2210 channel_cancel_cleanup(id);
2211 if (c->ostate != CHAN_OUTPUT_CLOSED)
2217 session_close_single_x11(int id, void *arg)
2222 debug3("session_close_single_x11: channel %d", id);
2223 channel_cancel_cleanup(id);
2224 if ((s = session_by_x11_channel(id)) == NULL)
2225 fatal("session_close_single_x11: no x11 channel %d", id);
2226 for (i = 0; s->x11_chanids[i] != -1; i++) {
2227 debug("session_close_single_x11: session %d: "
2228 "closing channel %d", s->self, s->x11_chanids[i]);
2230 * The channel "id" is already closing, but make sure we
2231 * close all of its siblings.
2233 if (s->x11_chanids[i] != id)
2234 session_close_x11(s->x11_chanids[i]);
2236 free(s->x11_chanids);
2237 s->x11_chanids = NULL;
2240 free(s->auth_proto);
2241 s->auth_proto = NULL;
2243 s->auth_data = NULL;
2244 free(s->auth_display);
2245 s->auth_display = NULL;
2249 session_exit_message(Session *s, int status)
2253 if ((c = channel_lookup(s->chanid)) == NULL)
2254 fatal("session_exit_message: session %d: no channel %d",
2255 s->self, s->chanid);
2256 debug("session_exit_message: session %d channel %d pid %ld",
2257 s->self, s->chanid, (long)s->pid);
2259 if (WIFEXITED(status)) {
2260 channel_request_start(s->chanid, "exit-status", 0);
2261 packet_put_int(WEXITSTATUS(status));
2263 } else if (WIFSIGNALED(status)) {
2264 channel_request_start(s->chanid, "exit-signal", 0);
2265 packet_put_cstring(sig2name(WTERMSIG(status)));
2267 packet_put_char(WCOREDUMP(status)? 1 : 0);
2268 #else /* WCOREDUMP */
2270 #endif /* WCOREDUMP */
2271 packet_put_cstring("");
2272 packet_put_cstring("");
2275 /* Some weird exit cause. Just exit. */
2276 packet_disconnect("wait returned status %04x.", status);
2279 /* disconnect channel */
2280 debug("session_exit_message: release channel %d", s->chanid);
2283 * Adjust cleanup callback attachment to send close messages when
2284 * the channel gets EOF. The session will be then be closed
2285 * by session_close_by_channel when the childs close their fds.
2287 channel_register_cleanup(c->self, session_close_by_channel, 1);
2290 * emulate a write failure with 'chan_write_failed', nobody will be
2291 * interested in data we write.
2292 * Note that we must not call 'chan_read_failed', since there could
2293 * be some more data waiting in the pipe.
2295 if (c->ostate != CHAN_OUTPUT_CLOSED)
2296 chan_write_failed(c);
2300 session_close(Session *s)
2302 struct ssh *ssh = active_state; /* XXX */
2305 verbose("Close session: user %s from %.200s port %d id %d",
2307 ssh_remote_ipaddr(ssh),
2308 ssh_remote_port(ssh),
2312 session_pty_cleanup(s);
2315 free(s->x11_chanids);
2316 free(s->auth_display);
2318 free(s->auth_proto);
2320 if (s->env != NULL) {
2321 for (i = 0; i < s->num_env; i++) {
2322 free(s->env[i].name);
2323 free(s->env[i].val);
2327 session_proctitle(s);
2328 session_unused(s->self);
2332 session_close_by_pid(pid_t pid, int status)
2334 Session *s = session_by_pid(pid);
2336 debug("session_close_by_pid: no session for pid %ld",
2340 if (s->chanid != -1)
2341 session_exit_message(s, status);
2343 session_pty_cleanup(s);
2348 * this is called when a channel dies before
2349 * the session 'child' itself dies
2352 session_close_by_channel(int id, void *arg)
2354 Session *s = session_by_channel(id);
2358 debug("session_close_by_channel: no session for id %d", id);
2361 debug("session_close_by_channel: channel %d child %ld",
2364 debug("session_close_by_channel: channel %d: has child", id);
2366 * delay detach of session, but release pty, since
2367 * the fd's to the child are already closed
2370 session_pty_cleanup(s);
2373 /* detach by removing callback */
2374 channel_cancel_cleanup(s->chanid);
2376 /* Close any X11 listeners associated with this session */
2377 if (s->x11_chanids != NULL) {
2378 for (i = 0; s->x11_chanids[i] != -1; i++) {
2379 session_close_x11(s->x11_chanids[i]);
2380 s->x11_chanids[i] = -1;
2389 session_destroy_all(void (*closefunc)(Session *))
2392 for (i = 0; i < sessions_nalloc; i++) {
2393 Session *s = &sessions[i];
2395 if (closefunc != NULL)
2404 session_tty_list(void)
2406 static char buf[1024];
2411 for (i = 0; i < sessions_nalloc; i++) {
2412 Session *s = &sessions[i];
2413 if (s->used && s->ttyfd != -1) {
2415 if (strncmp(s->tty, "/dev/", 5) != 0) {
2416 cp = strrchr(s->tty, '/');
2417 cp = (cp == NULL) ? s->tty : cp + 1;
2422 strlcat(buf, ",", sizeof buf);
2423 strlcat(buf, cp, sizeof buf);
2427 strlcpy(buf, "notty", sizeof buf);
2432 session_proctitle(Session *s)
2435 error("no user for session %d", s->self);
2437 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2441 session_setup_x11fwd(Session *s)
2444 char display[512], auth_display[512];
2445 char hostname[NI_MAXHOST];
2448 if (no_x11_forwarding_flag) {
2449 packet_send_debug("X11 forwarding disabled in user configuration file.");
2452 if (!options.x11_forwarding) {
2453 debug("X11 forwarding disabled in server configuration file.");
2456 if (options.xauth_location == NULL ||
2457 (stat(options.xauth_location, &st) == -1)) {
2458 packet_send_debug("No xauth program; cannot forward with spoofing.");
2461 if (s->display != NULL) {
2462 debug("X11 display already set.");
2465 if (x11_create_display_inet(options.x11_display_offset,
2466 options.x11_use_localhost, s->single_connection,
2467 &s->display_number, &s->x11_chanids) == -1) {
2468 debug("x11_create_display_inet failed.");
2471 for (i = 0; s->x11_chanids[i] != -1; i++) {
2472 channel_register_cleanup(s->x11_chanids[i],
2473 session_close_single_x11, 0);
2476 /* Set up a suitable value for the DISPLAY variable. */
2477 if (gethostname(hostname, sizeof(hostname)) < 0)
2478 fatal("gethostname: %.100s", strerror(errno));
2480 * auth_display must be used as the displayname when the
2481 * authorization entry is added with xauth(1). This will be
2482 * different than the DISPLAY string for localhost displays.
2484 if (options.x11_use_localhost) {
2485 snprintf(display, sizeof display, "localhost:%u.%u",
2486 s->display_number, s->screen);
2487 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2488 s->display_number, s->screen);
2489 s->display = xstrdup(display);
2490 s->auth_display = xstrdup(auth_display);
2492 #ifdef IPADDR_IN_DISPLAY
2494 struct in_addr my_addr;
2496 he = gethostbyname(hostname);
2498 error("Can't get IP address for X11 DISPLAY.");
2499 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2502 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2503 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2504 s->display_number, s->screen);
2506 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2507 s->display_number, s->screen);
2509 s->display = xstrdup(display);
2510 s->auth_display = xstrdup(display);
2517 do_authenticated2(Authctxt *authctxt)
2519 server_loop2(authctxt);
2523 do_cleanup(Authctxt *authctxt)
2525 static int called = 0;
2527 debug("do_cleanup");
2529 /* no cleanup if we're in the child for login shell */
2533 /* avoid double cleanup */
2538 if (authctxt == NULL)
2542 if (options.use_pam) {
2544 sshpam_thread_cleanup();
2548 if (!authctxt->authenticated)
2552 if (options.kerberos_ticket_cleanup &&
2554 krb5_cleanup_proc(authctxt);
2558 if (options.gss_cleanup_creds)
2559 ssh_gssapi_cleanup_creds();
2562 /* remove agent socket */
2563 auth_sock_cleanup_proc(authctxt->pw);
2566 * Cleanup ptys/utmp only if privsep is disabled,
2567 * or if running in monitor.
2569 if (!use_privsep || mm_is_monitor())
2570 session_destroy_all(session_pty_cleanup2);
2573 /* Return a name for the remote host that fits inside utmp_size */
2576 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2578 const char *remote = "";
2581 remote = auth_get_canonical_hostname(ssh, use_dns);
2582 if (utmp_size == 0 || strlen(remote) > utmp_size)
2583 remote = ssh_remote_ipaddr(ssh);