1 /* $OpenBSD: session.c,v 1.292 2017/09/12 06:32:07 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"
100 #if defined(KRB5) && defined(USE_AFS)
105 #include <selinux/selinux.h>
108 #define IS_INTERNAL_SFTP(c) \
109 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
110 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
111 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
112 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
116 Session *session_new(void);
117 void session_set_fds(struct ssh *, Session *, int, int, int, int, int);
118 void session_pty_cleanup(Session *);
119 void session_proctitle(Session *);
120 int session_setup_x11fwd(struct ssh *, Session *);
121 int do_exec_pty(struct ssh *, Session *, const char *);
122 int do_exec_no_pty(struct ssh *, Session *, const char *);
123 int do_exec(struct ssh *, Session *, const char *);
124 void do_login(struct ssh *, Session *, const char *);
125 void do_child(struct ssh *, Session *, const char *);
126 #ifdef LOGIN_NEEDS_UTMPX
127 static void do_pre_login(Session *s);
130 int check_quietlogin(Session *, const char *);
132 static void do_authenticated2(struct ssh *, Authctxt *);
134 static int session_pty_req(struct ssh *, Session *);
137 extern ServerOptions options;
138 extern char *__progname;
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 /* File containing userauth info, if ExposeAuthInfo set */
166 static char *auth_info_file = NULL;
168 /* Name and directory of socket for authentication agent forwarding. */
169 static char *auth_sock_name = NULL;
170 static char *auth_sock_dir = NULL;
172 /* removes the agent forwarding socket */
175 auth_sock_cleanup_proc(struct passwd *pw)
177 if (auth_sock_name != NULL) {
178 temporarily_use_uid(pw);
179 unlink(auth_sock_name);
180 rmdir(auth_sock_dir);
181 auth_sock_name = NULL;
187 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
192 if (auth_sock_name != NULL) {
193 error("authentication forwarding requested twice.");
197 /* Temporarily drop privileged uid for mkdir/bind. */
198 temporarily_use_uid(pw);
200 /* Allocate a buffer for the socket name, and format the name. */
201 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
203 /* Create private directory for socket */
204 if (mkdtemp(auth_sock_dir) == NULL) {
205 packet_send_debug("Agent forwarding disabled: "
206 "mkdtemp() failed: %.100s", strerror(errno));
209 auth_sock_dir = NULL;
213 xasprintf(&auth_sock_name, "%s/agent.%ld",
214 auth_sock_dir, (long) getpid());
216 /* Start a Unix listener on auth_sock_name. */
217 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
219 /* Restore the privileged uid. */
222 /* Check for socket/bind/listen failure. */
226 /* Allocate a channel for the authentication agent socket. */
227 nc = channel_new(ssh, "auth socket",
228 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
229 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
230 0, "auth socket", 1);
231 nc->path = xstrdup(auth_sock_name);
235 free(auth_sock_name);
236 if (auth_sock_dir != NULL) {
237 rmdir(auth_sock_dir);
242 auth_sock_name = NULL;
243 auth_sock_dir = NULL;
248 display_loginmsg(void)
250 if (buffer_len(&loginmsg) > 0) {
251 buffer_append(&loginmsg, "\0", 1);
252 printf("%s", (char *)buffer_ptr(&loginmsg));
253 buffer_clear(&loginmsg);
258 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
260 int fd = -1, success = 0;
262 if (!options.expose_userauth_info || info == NULL)
265 temporarily_use_uid(pw);
266 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
267 if ((fd = mkstemp(auth_info_file)) == -1) {
268 error("%s: mkstemp: %s", __func__, strerror(errno));
271 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
272 sshbuf_len(info)) != sshbuf_len(info)) {
273 error("%s: write: %s", __func__, strerror(errno));
276 if (close(fd) != 0) {
277 error("%s: close: %s", __func__, strerror(errno));
285 free(auth_info_file);
286 auth_info_file = NULL;
292 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
294 setproctitle("%s", authctxt->pw->pw_name);
296 /* setup the channel layer */
297 /* XXX - streamlocal? */
298 if (no_port_forwarding_flag || options.disable_forwarding ||
299 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
300 channel_disable_adm_local_opens(ssh);
302 channel_permit_all_opens(ssh);
306 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
308 do_authenticated2(ssh, authctxt);
310 do_cleanup(ssh, authctxt);
313 /* Check untrusted xauth strings for metacharacters */
315 xauth_valid_string(const char *s)
319 for (i = 0; s[i] != '\0'; i++) {
320 if (!isalnum((u_char)s[i]) &&
321 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
322 s[i] != '-' && s[i] != '_')
330 * This is called to fork and execute a command when we have no tty. This
331 * will call do_child from the child, and server_loop from the parent after
332 * setting up file descriptors and such.
335 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
340 int pin[2], pout[2], perr[2];
343 fatal("do_exec_no_pty: no session");
345 /* Allocate pipes for communicating with the program. */
347 error("%s: pipe in: %.100s", __func__, strerror(errno));
350 if (pipe(pout) < 0) {
351 error("%s: pipe out: %.100s", __func__, strerror(errno));
356 if (pipe(perr) < 0) {
357 error("%s: pipe err: %.100s", __func__,
366 int inout[2], err[2];
369 fatal("do_exec_no_pty: no session");
371 /* Uses socket pairs to communicate with the program. */
372 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
373 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
376 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
377 error("%s: socketpair #2: %.100s", __func__,
385 session_proctitle(s);
387 /* Fork the child. */
388 switch ((pid = fork())) {
390 error("%s: fork: %.100s", __func__, strerror(errno));
409 * Create a new session and process group since the 4.4BSD
410 * setlogin() affects the entire process group.
413 error("setsid failed: %.100s", strerror(errno));
417 * Redirect stdin. We close the parent side of the socket
418 * pair, and make the child side the standard input.
421 if (dup2(pin[0], 0) < 0)
422 perror("dup2 stdin");
425 /* Redirect stdout. */
427 if (dup2(pout[1], 1) < 0)
428 perror("dup2 stdout");
431 /* Redirect stderr. */
433 if (dup2(perr[1], 2) < 0)
434 perror("dup2 stderr");
438 * Redirect stdin, stdout, and stderr. Stdin and stdout will
439 * use the same socket, as some programs (particularly rdist)
440 * seem to depend on it.
444 if (dup2(inout[0], 0) < 0) /* stdin */
445 perror("dup2 stdin");
446 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
447 perror("dup2 stdout");
449 if (dup2(err[0], 2) < 0) /* stderr */
450 perror("dup2 stderr");
456 cray_init_job(s->pw); /* set up cray jid and tmpdir */
459 /* Do processing for the child (exec command etc). */
460 do_child(ssh, s, command);
467 signal(WJSIGNAL, cray_job_termination_handler);
470 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
474 /* Set interactive/non-interactive mode. */
475 packet_set_interactive(s->display != NULL,
476 options.ip_qos_interactive, options.ip_qos_bulk);
479 * Clear loginmsg, since it's the child's responsibility to display
480 * it to the user, otherwise multiple sessions may accumulate
481 * multiple copies of the login messages.
483 buffer_clear(&loginmsg);
486 /* We are the parent. Close the child sides of the pipes. */
491 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
494 /* We are the parent. Close the child sides of the socket pairs. */
499 * Enter the interactive session. Note: server_loop must be able to
500 * handle the case that fdin and fdout are the same.
502 session_set_fds(s, inout[1], inout[1], err[1],
509 * This is called to fork and execute a command when we have a tty. This
510 * will call do_child from the child, and server_loop from the parent after
511 * setting up file descriptors, controlling tty, updating wtmp, utmp,
512 * lastlog, and other such operations.
515 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
517 int fdout, ptyfd, ttyfd, ptymaster;
521 fatal("do_exec_pty: no session");
526 * Create another descriptor of the pty master side for use as the
527 * standard input. We could use the original descriptor, but this
528 * simplifies code in server_loop. The descriptor is bidirectional.
529 * Do this before forking (and cleanup in the child) so as to
530 * detect and gracefully fail out-of-fd conditions.
532 if ((fdout = dup(ptyfd)) < 0) {
533 error("%s: dup #1: %s", __func__, strerror(errno));
538 /* we keep a reference to the pty master */
539 if ((ptymaster = dup(ptyfd)) < 0) {
540 error("%s: dup #2: %s", __func__, strerror(errno));
547 /* Fork the child. */
548 switch ((pid = fork())) {
550 error("%s: fork: %.100s", __func__, strerror(errno));
562 /* Close the master side of the pseudo tty. */
565 /* Make the pseudo tty our controlling tty. */
566 pty_make_controlling_tty(&ttyfd, s->tty);
568 /* Redirect stdin/stdout/stderr from the pseudo tty. */
569 if (dup2(ttyfd, 0) < 0)
570 error("dup2 stdin: %s", strerror(errno));
571 if (dup2(ttyfd, 1) < 0)
572 error("dup2 stdout: %s", strerror(errno));
573 if (dup2(ttyfd, 2) < 0)
574 error("dup2 stderr: %s", strerror(errno));
576 /* Close the extra descriptor for the pseudo tty. */
579 /* record login, etc. similar to login(1) */
581 cray_init_job(s->pw); /* set up cray jid and tmpdir */
584 do_login(ssh, s, command);
587 * Do common processing for the child, such as execing
590 do_child(ssh, s, command);
597 signal(WJSIGNAL, cray_job_termination_handler);
600 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
605 /* Parent. Close the slave side of the pseudo tty. */
608 /* Enter interactive session. */
609 s->ptymaster = ptymaster;
610 packet_set_interactive(1,
611 options.ip_qos_interactive, options.ip_qos_bulk);
612 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
616 #ifdef LOGIN_NEEDS_UTMPX
618 do_pre_login(Session *s)
620 struct ssh *ssh = active_state; /* XXX */
622 struct sockaddr_storage from;
623 pid_t pid = getpid();
626 * Get IP address of client. If the connection is not a socket, let
627 * the address be 0.0.0.0.
629 memset(&from, 0, sizeof(from));
630 fromlen = sizeof(from);
631 if (packet_connection_is_on_socket()) {
632 if (getpeername(packet_get_connection_in(),
633 (struct sockaddr *)&from, &fromlen) < 0) {
634 debug("getpeername: %.100s", strerror(errno));
639 record_utmp_only(pid, s->tty, s->pw->pw_name,
640 session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
641 (struct sockaddr *)&from, fromlen);
646 * This is called to fork and execute a command. If another command is
647 * to be forced, execute that instead.
650 do_exec(struct ssh *ssh, Session *s, const char *command)
653 const char *forced = NULL, *tty = NULL;
654 char session_type[1024];
656 if (options.adm_forced_command) {
657 original_command = command;
658 command = options.adm_forced_command;
660 } else if (forced_command) {
661 original_command = command;
662 command = forced_command;
663 forced = "(key-option)";
665 if (forced != NULL) {
666 if (IS_INTERNAL_SFTP(command)) {
667 s->is_subsystem = s->is_subsystem ?
668 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
669 } else if (s->is_subsystem)
670 s->is_subsystem = SUBSYSTEM_EXT;
671 snprintf(session_type, sizeof(session_type),
672 "forced-command %s '%.900s'", forced, command);
673 } else if (s->is_subsystem) {
674 snprintf(session_type, sizeof(session_type),
675 "subsystem '%.900s'", s->subsys);
676 } else if (command == NULL) {
677 snprintf(session_type, sizeof(session_type), "shell");
679 /* NB. we don't log unforced commands to preserve privacy */
680 snprintf(session_type, sizeof(session_type), "command");
683 if (s->ttyfd != -1) {
685 if (strncmp(tty, "/dev/", 5) == 0)
689 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
691 tty == NULL ? "" : " on ",
692 tty == NULL ? "" : tty,
694 ssh_remote_ipaddr(ssh),
695 ssh_remote_port(ssh),
698 #ifdef SSH_AUDIT_EVENTS
700 PRIVSEP(audit_run_command(command));
701 else if (s->ttyfd == -1) {
702 char *shell = s->pw->pw_shell;
704 if (shell[0] == '\0') /* empty shell means /bin/sh */
706 PRIVSEP(audit_run_command(shell));
710 ret = do_exec_pty(ssh, s, command);
712 ret = do_exec_no_pty(ssh, s, command);
714 original_command = NULL;
717 * Clear loginmsg: it's the child's responsibility to display
718 * it to the user, otherwise multiple sessions may accumulate
719 * multiple copies of the login messages.
721 buffer_clear(&loginmsg);
726 /* administrative, login(1)-like work */
728 do_login(struct ssh *ssh, Session *s, const char *command)
731 struct sockaddr_storage from;
732 struct passwd * pw = s->pw;
733 pid_t pid = getpid();
736 * Get IP address of client. If the connection is not a socket, let
737 * the address be 0.0.0.0.
739 memset(&from, 0, sizeof(from));
740 fromlen = sizeof(from);
741 if (packet_connection_is_on_socket()) {
742 if (getpeername(packet_get_connection_in(),
743 (struct sockaddr *)&from, &fromlen) < 0) {
744 debug("getpeername: %.100s", strerror(errno));
749 /* Record that there was a login on that tty from the remote host. */
751 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
752 session_get_remote_name_or_ip(ssh, utmp_len,
754 (struct sockaddr *)&from, fromlen);
758 * If password change is needed, do it now.
759 * This needs to occur before the ~/.hushlogin check.
761 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
764 s->authctxt->force_pwchange = 0;
765 /* XXX - signal [net] parent to enable forwardings */
769 if (check_quietlogin(s, command))
778 * Display the message of the day.
786 if (options.print_motd) {
787 #ifdef HAVE_LOGIN_CAP
788 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
791 f = fopen("/etc/motd", "r");
794 while (fgets(buf, sizeof(buf), f))
803 * Check for quiet login, either .hushlogin or command given.
806 check_quietlogin(Session *s, const char *command)
809 struct passwd *pw = s->pw;
812 /* Return 1 if .hushlogin exists or a command given. */
815 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
816 #ifdef HAVE_LOGIN_CAP
817 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
820 if (stat(buf, &st) >= 0)
827 * Reads environment variables from the given file and adds/overrides them
828 * into the environment. If the file does not exist, this does nothing.
829 * Otherwise, it must consist of empty lines, comments (line starts with '#')
830 * and assignments of the form name=value. No other forms are allowed.
833 read_environment_file(char ***env, u_int *envsize,
834 const char *filename)
841 f = fopen(filename, "r");
845 while (fgets(buf, sizeof(buf), f)) {
847 fatal("Too many lines in environment file %s", filename);
848 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
850 if (!*cp || *cp == '#' || *cp == '\n')
853 cp[strcspn(cp, "\n")] = '\0';
855 value = strchr(cp, '=');
857 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
862 * Replace the equals sign by nul, and advance value to
867 child_set_env(env, envsize, cp, value);
872 #ifdef HAVE_ETC_DEFAULT_LOGIN
874 * Return named variable from specified environment, or NULL if not present.
877 child_get_env(char **env, const char *name)
883 for (i=0; env[i] != NULL; i++)
884 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
885 return(env[i] + len + 1);
890 * Read /etc/default/login.
891 * We pick up the PATH (or SUPATH for root) and UMASK.
894 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
896 char **tmpenv = NULL, *var;
897 u_int i, tmpenvsize = 0;
901 * We don't want to copy the whole file to the child's environment,
902 * so we use a temporary environment and copy the variables we're
905 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
911 var = child_get_env(tmpenv, "SUPATH");
913 var = child_get_env(tmpenv, "PATH");
915 child_set_env(env, envsize, "PATH", var);
917 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
918 if (sscanf(var, "%5lo", &mask) == 1)
921 for (i = 0; tmpenv[i] != NULL; i++)
925 #endif /* HAVE_ETC_DEFAULT_LOGIN */
928 copy_environment_blacklist(char **source, char ***env, u_int *envsize,
929 const char *blacklist)
931 char *var_name, *var_val;
937 for(i = 0; source[i] != NULL; i++) {
938 var_name = xstrdup(source[i]);
939 if ((var_val = strstr(var_name, "=")) == NULL) {
945 if (blacklist == NULL ||
946 match_pattern_list(var_name, blacklist, 0) != 1) {
947 debug3("Copy environment: %s=%s", var_name, var_val);
948 child_set_env(env, envsize, var_name, var_val);
956 copy_environment(char **source, char ***env, u_int *envsize)
958 copy_environment_blacklist(source, env, envsize, NULL);
962 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
967 struct passwd *pw = s->pw;
968 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
971 extern char **environ;
972 char **senv, **var, *val;
975 /* Initialize the environment. */
977 env = xcalloc(envsize, sizeof(char *));
982 * The Windows environment contains some setting which are
983 * important for a running system. They must not be dropped.
988 p = fetch_windows_environment();
989 copy_environment(p, &env, &envsize);
990 free_windows_environment(p);
995 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
998 /* Allow any GSSAPI methods that we've used to alter
999 * the childs environment as they see fit
1001 ssh_gssapi_do_child(&env, &envsize);
1004 /* Set basic environment. */
1005 for (i = 0; i < s->num_env; i++)
1006 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1008 child_set_env(&env, &envsize, "USER", pw->pw_name);
1009 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1011 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1013 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1014 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1015 child_set_env(&env, &envsize, "MAIL", buf);
1016 #ifdef HAVE_LOGIN_CAP
1017 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1018 child_set_env(&env, &envsize, "TERM", "su");
1020 * Temporarily swap out our real environment with an empty one,
1021 * let setusercontext() apply any environment variables defined
1022 * for the user's login class, copy those variables to the child,
1023 * free the temporary environment, and restore the original.
1026 environ = xmalloc(sizeof(*environ));
1028 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1029 for (var = environ; *var != NULL; ++var) {
1030 if ((val = strchr(*var, '=')) != NULL) {
1032 child_set_env(&env, &envsize, *var, val);
1038 #else /* HAVE_LOGIN_CAP */
1039 # ifndef HAVE_CYGWIN
1041 * There's no standard path on Windows. The path contains
1042 * important components pointing to the system directories,
1043 * needed for loading shared libraries. So the path better
1044 * remains intact here.
1046 # ifdef HAVE_ETC_DEFAULT_LOGIN
1047 read_etc_default_login(&env, &envsize, pw->pw_uid);
1048 path = child_get_env(env, "PATH");
1049 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1050 if (path == NULL || *path == '\0') {
1051 child_set_env(&env, &envsize, "PATH",
1052 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1054 # endif /* HAVE_CYGWIN */
1055 #endif /* HAVE_LOGIN_CAP */
1057 /* Normal systems set SHELL by default. */
1058 child_set_env(&env, &envsize, "SHELL", shell);
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);
1090 if (auth_info_file != NULL)
1091 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1093 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1095 child_set_env(&env, &envsize, "TERM", s->term);
1097 child_set_env(&env, &envsize, "DISPLAY", s->display);
1098 if (original_command)
1099 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1103 if (cray_tmpdir[0] != '\0')
1104 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1105 #endif /* _UNICOS */
1108 * Since we clear KRB5CCNAME at startup, if it's set now then it
1109 * must have been set by a native authentication method (eg AIX or
1110 * SIA), so copy it to the child.
1115 if ((cp = getenv("KRB5CCNAME")) != NULL)
1116 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1123 if ((cp = getenv("AUTHSTATE")) != NULL)
1124 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1125 read_environment_file(&env, &envsize, "/etc/environment");
1129 if (s->authctxt->krb5_ccname)
1130 child_set_env(&env, &envsize, "KRB5CCNAME",
1131 s->authctxt->krb5_ccname);
1135 * Pull in any environment variables that may have
1138 if (options.use_pam) {
1142 * Don't allow SSH_AUTH_INFO variables posted to PAM to leak
1143 * back into the environment.
1145 p = fetch_pam_child_environment();
1146 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1147 free_pam_environment(p);
1149 p = fetch_pam_environment();
1150 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1151 free_pam_environment(p);
1153 #endif /* USE_PAM */
1155 if (auth_sock_name != NULL)
1156 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1159 /* read $HOME/.ssh/environment. */
1160 if (options.permit_user_env) {
1161 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1162 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1163 read_environment_file(&env, &envsize, buf);
1166 /* dump the environment */
1167 fprintf(stderr, "Environment:\n");
1168 for (i = 0; env[i]; i++)
1169 fprintf(stderr, " %.200s\n", env[i]);
1175 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1176 * first in this order).
1179 do_rc_files(Session *s, const char *shell)
1187 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1189 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1190 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1191 !no_user_rc && options.permit_user_rc &&
1192 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1193 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1194 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1196 fprintf(stderr, "Running %s\n", cmd);
1197 f = popen(cmd, "w");
1200 fprintf(f, "%s %s\n", s->auth_proto,
1204 fprintf(stderr, "Could not run %s\n",
1206 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1208 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1209 _PATH_SSH_SYSTEM_RC);
1210 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1213 fprintf(f, "%s %s\n", s->auth_proto,
1217 fprintf(stderr, "Could not run %s\n",
1218 _PATH_SSH_SYSTEM_RC);
1219 } else if (do_xauth && options.xauth_location != NULL) {
1220 /* Add authority data to .Xauthority if appropriate. */
1223 "Running %.500s remove %.100s\n",
1224 options.xauth_location, s->auth_display);
1226 "%.500s add %.100s %.100s %.100s\n",
1227 options.xauth_location, s->auth_display,
1228 s->auth_proto, s->auth_data);
1230 snprintf(cmd, sizeof cmd, "%s -q -",
1231 options.xauth_location);
1232 f = popen(cmd, "w");
1234 fprintf(f, "remove %s\n",
1236 fprintf(f, "add %s %s %s\n",
1237 s->auth_display, s->auth_proto,
1241 fprintf(stderr, "Could not run %s\n",
1248 do_nologin(struct passwd *pw)
1252 char buf[1024], *def_nl = _PATH_NOLOGIN;
1255 #ifdef HAVE_LOGIN_CAP
1256 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1258 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1260 if (pw->pw_uid == 0)
1264 if (stat(nl, &sb) == -1)
1267 /* /etc/nologin exists. Print its contents if we can and exit. */
1268 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1269 if ((f = fopen(nl, "r")) != NULL) {
1270 while (fgets(buf, sizeof(buf), f))
1278 * Chroot into a directory after checking it for safety: all path components
1279 * must be root-owned directories with strict permissions.
1282 safely_chroot(const char *path, uid_t uid)
1285 char component[PATH_MAX];
1289 fatal("chroot path does not begin at root");
1290 if (strlen(path) >= sizeof(component))
1291 fatal("chroot path too long");
1294 * Descend the path, checking that each component is a
1295 * root-owned directory with strict permissions.
1297 for (cp = path; cp != NULL;) {
1298 if ((cp = strchr(cp, '/')) == NULL)
1299 strlcpy(component, path, sizeof(component));
1302 memcpy(component, path, cp - path);
1303 component[cp - path] = '\0';
1306 debug3("%s: checking '%s'", __func__, component);
1308 if (stat(component, &st) != 0)
1309 fatal("%s: stat(\"%s\"): %s", __func__,
1310 component, strerror(errno));
1311 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1312 fatal("bad ownership or modes for chroot "
1313 "directory %s\"%s\"",
1314 cp == NULL ? "" : "component ", component);
1315 if (!S_ISDIR(st.st_mode))
1316 fatal("chroot path %s\"%s\" is not a directory",
1317 cp == NULL ? "" : "component ", component);
1321 if (chdir(path) == -1)
1322 fatal("Unable to chdir to chroot path \"%s\": "
1323 "%s", path, strerror(errno));
1324 if (chroot(path) == -1)
1325 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1326 if (chdir("/") == -1)
1327 fatal("%s: chdir(/) after chroot: %s",
1328 __func__, strerror(errno));
1329 verbose("Changed root directory to \"%s\"", path);
1332 /* Set login name, uid, gid, and groups. */
1334 do_setusercontext(struct passwd *pw)
1336 char *chroot_path, *tmp;
1338 platform_setusercontext(pw);
1340 if (platform_privileged_uidswap()) {
1341 #ifdef HAVE_LOGIN_CAP
1342 if (setusercontext(lc, pw, pw->pw_uid,
1343 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1344 perror("unable to set user context");
1348 if (setlogin(pw->pw_name) < 0)
1349 error("setlogin failed: %s", strerror(errno));
1350 if (setgid(pw->pw_gid) < 0) {
1354 /* Initialize the group list. */
1355 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1356 perror("initgroups");
1362 platform_setusercontext_post_groups(pw);
1364 if (!in_chroot && options.chroot_directory != NULL &&
1365 strcasecmp(options.chroot_directory, "none") != 0) {
1366 tmp = tilde_expand_filename(options.chroot_directory,
1368 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1369 "u", pw->pw_name, (char *)NULL);
1370 safely_chroot(chroot_path, pw->pw_uid);
1373 /* Make sure we don't attempt to chroot again */
1374 free(options.chroot_directory);
1375 options.chroot_directory = NULL;
1379 #ifdef HAVE_LOGIN_CAP
1380 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1381 perror("unable to set user context (setuser)");
1385 * FreeBSD's setusercontext() will not apply the user's
1386 * own umask setting unless running with the user's UID.
1388 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1392 * In a chroot environment, the set_id() will always fail;
1393 * typically because of the lack of necessary authentication
1394 * services and runtime such as ./usr/lib/libiaf.so,
1395 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1396 * internal sftp chroot case. We'll lose auditing and ACLs but
1397 * permanently_set_uid will take care of the rest.
1399 if (!in_chroot && set_id(pw->pw_name) != 0)
1400 fatal("set_id(%s) Failed", pw->pw_name);
1401 # endif /* USE_LIBIAF */
1402 /* Permanently switch to the desired uid. */
1403 permanently_set_uid(pw);
1405 } else if (options.chroot_directory != NULL &&
1406 strcasecmp(options.chroot_directory, "none") != 0) {
1407 fatal("server lacks privileges to chroot to ChrootDirectory");
1410 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1411 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1415 do_pwchange(Session *s)
1418 fprintf(stderr, "WARNING: Your password has expired.\n");
1419 if (s->ttyfd != -1) {
1421 "You must change your password now and login again!\n");
1425 #ifdef PASSWD_NEEDS_USERNAME
1426 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1429 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1434 "Password change required but no TTY available.\n");
1440 child_close_fds(struct ssh *ssh)
1442 extern int auth_sock;
1444 if (auth_sock != -1) {
1449 if (packet_get_connection_in() == packet_get_connection_out())
1450 close(packet_get_connection_in());
1452 close(packet_get_connection_in());
1453 close(packet_get_connection_out());
1456 * Close all descriptors related to channels. They will still remain
1457 * open in the parent.
1459 /* XXX better use close-on-exec? -markus */
1460 channel_close_all(ssh);
1463 * Close any extra file descriptors. Note that there may still be
1464 * 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(struct ssh *ssh, 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();
1495 packet_clear_keys();
1497 /* Force a password change */
1498 if (s->authctxt->force_pwchange) {
1499 do_setusercontext(pw);
1500 child_close_fds(ssh);
1506 cray_setup(pw->pw_uid, pw->pw_name, command);
1507 #endif /* _UNICOS */
1510 * Login(1) does this as well, and it needs uid 0 for the "-h"
1511 * switch, so we let login(1) to this for us.
1514 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1515 if (!check_quietlogin(s, command))
1517 #else /* HAVE_OSF_SIA */
1518 /* When PAM is enabled we rely on it to do the nologin check */
1519 if (!options.use_pam)
1521 do_setusercontext(pw);
1523 * PAM session modules in do_setusercontext may have
1524 * generated messages, so if this in an interactive
1525 * login then display them too.
1527 if (!check_quietlogin(s, command))
1529 #endif /* HAVE_OSF_SIA */
1532 if (options.use_pam && !is_pam_session_open()) {
1533 debug3("PAM session not opened, exiting");
1540 * Get the shell from the password data. An empty shell field is
1541 * legal, and means /bin/sh.
1543 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1546 * Make sure $SHELL points to the shell from the password file,
1547 * even if shell is overridden from login.conf
1549 env = do_setup_env(ssh, s, shell);
1551 #ifdef HAVE_LOGIN_CAP
1552 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1556 * Close the connection descriptors; note that this is the child, and
1557 * the server will still have the socket open, and it is important
1558 * that we do not shutdown it. Note that the descriptors cannot be
1559 * closed before building the environment, as we call
1560 * ssh_remote_ipaddr there.
1562 child_close_fds(ssh);
1565 * Must take new environment into use so that .ssh/rc,
1566 * /etc/ssh/sshrc and xauth are run in the proper environment.
1570 #if defined(KRB5) && defined(USE_AFS)
1572 * At this point, we check to see if AFS is active and if we have
1573 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1574 * if we can (and need to) extend the ticket into an AFS token. If
1575 * we don't do this, we run into potential problems if the user's
1576 * home directory is in AFS and it's not world-readable.
1579 if (options.kerberos_get_afs_token && k_hasafs() &&
1580 (s->authctxt->krb5_ctx != NULL)) {
1583 debug("Getting AFS token");
1587 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1588 krb5_afslog(s->authctxt->krb5_ctx,
1589 s->authctxt->krb5_fwd_ccache, cell, NULL);
1591 krb5_afslog_home(s->authctxt->krb5_ctx,
1592 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1596 /* Change current directory to the user's home directory. */
1597 if (chdir(pw->pw_dir) < 0) {
1598 /* Suppress missing homedir warning for chroot case */
1599 #ifdef HAVE_LOGIN_CAP
1600 r = login_getcapbool(lc, "requirehome", 0);
1602 if (r || !in_chroot) {
1603 fprintf(stderr, "Could not chdir to home "
1604 "directory %s: %s\n", pw->pw_dir,
1611 closefrom(STDERR_FILENO + 1);
1613 do_rc_files(s, shell);
1615 /* restore SIGPIPE for child */
1616 signal(SIGPIPE, SIG_DFL);
1618 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1619 printf("This service allows sftp connections only.\n");
1622 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1623 extern int optind, optreset;
1627 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1628 args = xstrdup(command ? command : "sftp-server");
1629 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1630 if (i < ARGV_MAX - 1)
1633 optind = optreset = 1;
1634 __progname = argv[0];
1636 ssh_selinux_change_context("sftpd_t");
1638 exit(sftp_server_main(i, argv, s->pw));
1643 /* Get the last component of the shell name. */
1644 if ((shell0 = strrchr(shell, '/')) != NULL)
1650 * If we have no command, execute the shell. In this case, the shell
1651 * name to be passed in argv[0] is preceded by '-' to indicate that
1652 * this is a login shell.
1657 /* Start the shell. Set initial character to '-'. */
1660 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1661 >= sizeof(argv0) - 1) {
1667 /* Execute the shell. */
1670 execve(shell, argv, env);
1672 /* Executing the shell failed. */
1677 * Execute the command using the user's shell. This uses the -c
1678 * option to execute the command.
1680 argv[0] = (char *) shell0;
1682 argv[2] = (char *) command;
1684 execve(shell, argv, env);
1690 session_unused(int id)
1692 debug3("%s: session id %d unused", __func__, id);
1693 if (id >= options.max_sessions ||
1694 id >= sessions_nalloc) {
1695 fatal("%s: insane session id %d (max %d nalloc %d)",
1696 __func__, id, options.max_sessions, sessions_nalloc);
1698 memset(&sessions[id], 0, sizeof(*sessions));
1699 sessions[id].self = id;
1700 sessions[id].used = 0;
1701 sessions[id].chanid = -1;
1702 sessions[id].ptyfd = -1;
1703 sessions[id].ttyfd = -1;
1704 sessions[id].ptymaster = -1;
1705 sessions[id].x11_chanids = NULL;
1706 sessions[id].next_unused = sessions_first_unused;
1707 sessions_first_unused = id;
1715 if (sessions_first_unused == -1) {
1716 if (sessions_nalloc >= options.max_sessions)
1718 debug2("%s: allocate (allocated %d max %d)",
1719 __func__, sessions_nalloc, options.max_sessions);
1720 tmp = xrecallocarray(sessions, sessions_nalloc,
1721 sessions_nalloc + 1, sizeof(*sessions));
1723 error("%s: cannot allocate %d sessions",
1724 __func__, sessions_nalloc + 1);
1728 session_unused(sessions_nalloc++);
1731 if (sessions_first_unused >= sessions_nalloc ||
1732 sessions_first_unused < 0) {
1733 fatal("%s: insane first_unused %d max %d nalloc %d",
1734 __func__, sessions_first_unused, options.max_sessions,
1738 s = &sessions[sessions_first_unused];
1740 fatal("%s: session %d already used",
1741 __func__, sessions_first_unused);
1743 sessions_first_unused = s->next_unused;
1745 s->next_unused = -1;
1746 debug("session_new: session %d", s->self);
1755 for (i = 0; i < sessions_nalloc; i++) {
1756 Session *s = &sessions[i];
1758 debug("dump: used %d next_unused %d session %d %p "
1759 "channel %d pid %ld",
1770 session_open(Authctxt *authctxt, int chanid)
1772 Session *s = session_new();
1773 debug("session_open: channel %d", chanid);
1775 error("no more sessions");
1778 s->authctxt = authctxt;
1779 s->pw = authctxt->pw;
1780 if (s->pw == NULL || !authctxt->valid)
1781 fatal("no user for session %d", s->self);
1782 debug("session_open: session %d: link with channel %d", s->self, chanid);
1788 session_by_tty(char *tty)
1791 for (i = 0; i < sessions_nalloc; i++) {
1792 Session *s = &sessions[i];
1793 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1794 debug("session_by_tty: session %d tty %s", i, tty);
1798 debug("session_by_tty: unknown tty %.100s", tty);
1804 session_by_channel(int id)
1807 for (i = 0; i < sessions_nalloc; i++) {
1808 Session *s = &sessions[i];
1809 if (s->used && s->chanid == id) {
1810 debug("session_by_channel: session %d channel %d",
1815 debug("session_by_channel: unknown channel %d", id);
1821 session_by_x11_channel(int id)
1825 for (i = 0; i < sessions_nalloc; i++) {
1826 Session *s = &sessions[i];
1828 if (s->x11_chanids == NULL || !s->used)
1830 for (j = 0; s->x11_chanids[j] != -1; j++) {
1831 if (s->x11_chanids[j] == id) {
1832 debug("session_by_x11_channel: session %d "
1833 "channel %d", s->self, id);
1838 debug("session_by_x11_channel: unknown channel %d", id);
1844 session_by_pid(pid_t pid)
1847 debug("session_by_pid: pid %ld", (long)pid);
1848 for (i = 0; i < sessions_nalloc; i++) {
1849 Session *s = &sessions[i];
1850 if (s->used && s->pid == pid)
1853 error("session_by_pid: unknown pid %ld", (long)pid);
1859 session_window_change_req(struct ssh *ssh, Session *s)
1861 s->col = packet_get_int();
1862 s->row = packet_get_int();
1863 s->xpixel = packet_get_int();
1864 s->ypixel = packet_get_int();
1866 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1871 session_pty_req(struct ssh *ssh, Session *s)
1876 if (no_pty_flag || !options.permit_tty) {
1877 debug("Allocating a pty not permitted for this authentication.");
1880 if (s->ttyfd != -1) {
1881 packet_disconnect("Protocol error: you already have a pty.");
1885 s->term = packet_get_string(&len);
1886 s->col = packet_get_int();
1887 s->row = packet_get_int();
1888 s->xpixel = packet_get_int();
1889 s->ypixel = packet_get_int();
1891 if (strcmp(s->term, "") == 0) {
1896 /* Allocate a pty and open it. */
1897 debug("Allocating pty.");
1898 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1904 error("session_pty_req: session %d alloc failed", s->self);
1907 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1909 n_bytes = packet_remaining();
1910 tty_parse_modes(s->ttyfd, &n_bytes);
1913 pty_setowner(s->pw, s->tty);
1915 /* Set window size from the packet. */
1916 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1919 session_proctitle(s);
1924 session_subsystem_req(struct ssh *ssh, Session *s)
1932 s->subsys = packet_get_string(&len);
1934 debug2("subsystem request for %.100s by user %s", s->subsys,
1937 for (i = 0; i < options.num_subsystems; i++) {
1938 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1939 prog = options.subsystem_command[i];
1940 cmd = options.subsystem_args[i];
1941 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1942 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1943 debug("subsystem: %s", prog);
1945 if (stat(prog, &st) < 0)
1946 debug("subsystem: cannot stat %s: %s",
1947 prog, strerror(errno));
1948 s->is_subsystem = SUBSYSTEM_EXT;
1949 debug("subsystem: exec() %s", cmd);
1951 success = do_exec(ssh, s, cmd) == 0;
1957 logit("subsystem request for %.100s by user %s failed, "
1958 "subsystem not found", s->subsys, s->pw->pw_name);
1964 session_x11_req(struct ssh *ssh, Session *s)
1968 if (s->auth_proto != NULL || s->auth_data != NULL) {
1969 error("session_x11_req: session %d: "
1970 "x11 forwarding already active", s->self);
1973 s->single_connection = packet_get_char();
1974 s->auth_proto = packet_get_string(NULL);
1975 s->auth_data = packet_get_string(NULL);
1976 s->screen = packet_get_int();
1979 if (xauth_valid_string(s->auth_proto) &&
1980 xauth_valid_string(s->auth_data))
1981 success = session_setup_x11fwd(ssh, s);
1984 error("Invalid X11 forwarding data");
1987 free(s->auth_proto);
1989 s->auth_proto = NULL;
1990 s->auth_data = NULL;
1996 session_shell_req(struct ssh *ssh, Session *s)
1999 return do_exec(ssh, s, NULL) == 0;
2003 session_exec_req(struct ssh *ssh, Session *s)
2007 char *command = packet_get_string(&len);
2009 success = do_exec(ssh, s, command) == 0;
2015 session_break_req(struct ssh *ssh, Session *s)
2018 packet_get_int(); /* ignored */
2021 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2027 session_env_req(struct ssh *ssh, Session *s)
2030 u_int name_len, val_len, i;
2032 name = packet_get_cstring(&name_len);
2033 val = packet_get_cstring(&val_len);
2036 /* Don't set too many environment variables */
2037 if (s->num_env > 128) {
2038 debug2("Ignoring env request %s: too many env vars", name);
2042 for (i = 0; i < options.num_accept_env; i++) {
2043 if (match_pattern(name, options.accept_env[i])) {
2044 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2045 s->env = xrecallocarray(s->env, s->num_env,
2046 s->num_env + 1, sizeof(*s->env));
2047 s->env[s->num_env].name = name;
2048 s->env[s->num_env].val = val;
2053 debug2("Ignoring env request %s: disallowed name", name);
2062 session_auth_agent_req(struct ssh *ssh, Session *s)
2064 static int called = 0;
2066 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2067 debug("session_auth_agent_req: no_agent_forwarding_flag");
2074 return auth_input_request_forwarding(ssh, s->pw);
2079 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2084 if ((s = session_by_channel(c->self)) == NULL) {
2085 logit("%s: no session %d req %.100s", __func__, c->self, rtype);
2088 debug("%s: session %d req %s", __func__, 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(ssh, s);
2097 } else if (strcmp(rtype, "exec") == 0) {
2098 success = session_exec_req(ssh, s);
2099 } else if (strcmp(rtype, "pty-req") == 0) {
2100 success = session_pty_req(ssh, s);
2101 } else if (strcmp(rtype, "x11-req") == 0) {
2102 success = session_x11_req(ssh, s);
2103 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2104 success = session_auth_agent_req(ssh, s);
2105 } else if (strcmp(rtype, "subsystem") == 0) {
2106 success = session_subsystem_req(ssh, s);
2107 } else if (strcmp(rtype, "env") == 0) {
2108 success = session_env_req(ssh, s);
2111 if (strcmp(rtype, "window-change") == 0) {
2112 success = session_window_change_req(ssh, s);
2113 } else if (strcmp(rtype, "break") == 0) {
2114 success = session_break_req(ssh, s);
2121 session_set_fds(struct ssh *ssh, Session *s,
2122 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
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(ssh, 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(struct ssh *ssh, int id)
2205 if ((c = channel_by_id(ssh, id)) == NULL) {
2206 debug("%s: x11 channel %d missing", __func__, id);
2208 /* Detach X11 listener */
2209 debug("%s: detach x11 channel %d", __func__, id);
2210 channel_cancel_cleanup(ssh, id);
2211 if (c->ostate != CHAN_OUTPUT_CLOSED)
2212 chan_mark_dead(ssh, c);
2217 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2222 debug3("%s: channel %d", __func__, id);
2223 channel_cancel_cleanup(ssh, id);
2224 if ((s = session_by_x11_channel(id)) == NULL)
2225 fatal("%s: no x11 channel %d", __func__, id);
2226 for (i = 0; s->x11_chanids[i] != -1; i++) {
2227 debug("%s: session %d: closing channel %d",
2228 __func__, 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(ssh, 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(struct ssh *ssh, Session *s, int status)
2253 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2254 fatal("%s: session %d: no channel %d",
2255 __func__, s->self, s->chanid);
2256 debug("%s: session %d channel %d pid %ld",
2257 __func__, s->self, s->chanid, (long)s->pid);
2259 if (WIFEXITED(status)) {
2260 channel_request_start(ssh, s->chanid, "exit-status", 0);
2261 packet_put_int(WEXITSTATUS(status));
2263 } else if (WIFSIGNALED(status)) {
2264 channel_request_start(ssh, 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("%s: release channel %d", __func__, 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(ssh, 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(ssh, c);
2300 session_close(struct ssh *ssh, Session *s)
2304 verbose("Close session: user %s from %.200s port %d id %d",
2306 ssh_remote_ipaddr(ssh),
2307 ssh_remote_port(ssh),
2311 session_pty_cleanup(s);
2314 free(s->x11_chanids);
2315 free(s->auth_display);
2317 free(s->auth_proto);
2319 if (s->env != NULL) {
2320 for (i = 0; i < s->num_env; i++) {
2321 free(s->env[i].name);
2322 free(s->env[i].val);
2326 session_proctitle(s);
2327 session_unused(s->self);
2331 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2333 Session *s = session_by_pid(pid);
2335 debug("%s: no session for pid %ld", __func__, (long)pid);
2338 if (s->chanid != -1)
2339 session_exit_message(ssh, s, status);
2341 session_pty_cleanup(s);
2346 * this is called when a channel dies before
2347 * the session 'child' itself dies
2350 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2352 Session *s = session_by_channel(id);
2356 debug("%s: no session for id %d", __func__, id);
2359 debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
2361 debug("%s: channel %d: has child", __func__, id);
2363 * delay detach of session, but release pty, since
2364 * the fd's to the child are already closed
2367 session_pty_cleanup(s);
2370 /* detach by removing callback */
2371 channel_cancel_cleanup(ssh, s->chanid);
2373 /* Close any X11 listeners associated with this session */
2374 if (s->x11_chanids != NULL) {
2375 for (i = 0; s->x11_chanids[i] != -1; i++) {
2376 session_close_x11(ssh, s->x11_chanids[i]);
2377 s->x11_chanids[i] = -1;
2382 session_close(ssh, s);
2386 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2389 for (i = 0; i < sessions_nalloc; i++) {
2390 Session *s = &sessions[i];
2392 if (closefunc != NULL)
2395 session_close(ssh, s);
2401 session_tty_list(void)
2403 static char buf[1024];
2408 for (i = 0; i < sessions_nalloc; i++) {
2409 Session *s = &sessions[i];
2410 if (s->used && s->ttyfd != -1) {
2412 if (strncmp(s->tty, "/dev/", 5) != 0) {
2413 cp = strrchr(s->tty, '/');
2414 cp = (cp == NULL) ? s->tty : cp + 1;
2419 strlcat(buf, ",", sizeof buf);
2420 strlcat(buf, cp, sizeof buf);
2424 strlcpy(buf, "notty", sizeof buf);
2429 session_proctitle(Session *s)
2432 error("no user for session %d", s->self);
2434 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2438 session_setup_x11fwd(struct ssh *ssh, Session *s)
2441 char display[512], auth_display[512];
2442 char hostname[NI_MAXHOST];
2445 if (no_x11_forwarding_flag) {
2446 packet_send_debug("X11 forwarding disabled in user configuration file.");
2449 if (!options.x11_forwarding) {
2450 debug("X11 forwarding disabled in server configuration file.");
2453 if (options.xauth_location == NULL ||
2454 (stat(options.xauth_location, &st) == -1)) {
2455 packet_send_debug("No xauth program; cannot forward with spoofing.");
2458 if (s->display != NULL) {
2459 debug("X11 display already set.");
2462 if (x11_create_display_inet(ssh, options.x11_display_offset,
2463 options.x11_use_localhost, s->single_connection,
2464 &s->display_number, &s->x11_chanids) == -1) {
2465 debug("x11_create_display_inet failed.");
2468 for (i = 0; s->x11_chanids[i] != -1; i++) {
2469 channel_register_cleanup(ssh, s->x11_chanids[i],
2470 session_close_single_x11, 0);
2473 /* Set up a suitable value for the DISPLAY variable. */
2474 if (gethostname(hostname, sizeof(hostname)) < 0)
2475 fatal("gethostname: %.100s", strerror(errno));
2477 * auth_display must be used as the displayname when the
2478 * authorization entry is added with xauth(1). This will be
2479 * different than the DISPLAY string for localhost displays.
2481 if (options.x11_use_localhost) {
2482 snprintf(display, sizeof display, "localhost:%u.%u",
2483 s->display_number, s->screen);
2484 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2485 s->display_number, s->screen);
2486 s->display = xstrdup(display);
2487 s->auth_display = xstrdup(auth_display);
2489 #ifdef IPADDR_IN_DISPLAY
2491 struct in_addr my_addr;
2493 he = gethostbyname(hostname);
2495 error("Can't get IP address for X11 DISPLAY.");
2496 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2499 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2500 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2501 s->display_number, s->screen);
2503 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2504 s->display_number, s->screen);
2506 s->display = xstrdup(display);
2507 s->auth_display = xstrdup(display);
2514 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2516 server_loop2(ssh, authctxt);
2520 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2522 static int called = 0;
2524 debug("do_cleanup");
2526 /* no cleanup if we're in the child for login shell */
2530 /* avoid double cleanup */
2535 if (authctxt == NULL)
2539 if (options.use_pam) {
2541 sshpam_thread_cleanup();
2545 if (!authctxt->authenticated)
2549 if (options.kerberos_ticket_cleanup &&
2551 krb5_cleanup_proc(authctxt);
2555 if (options.gss_cleanup_creds)
2556 ssh_gssapi_cleanup_creds();
2559 /* remove agent socket */
2560 auth_sock_cleanup_proc(authctxt->pw);
2562 /* remove userauth info */
2563 if (auth_info_file != NULL) {
2564 temporarily_use_uid(authctxt->pw);
2565 unlink(auth_info_file);
2567 free(auth_info_file);
2568 auth_info_file = NULL;
2572 * Cleanup ptys/utmp only if privsep is disabled,
2573 * or if running in monitor.
2575 if (!use_privsep || mm_is_monitor())
2576 session_destroy_all(ssh, session_pty_cleanup2);
2579 /* Return a name for the remote host that fits inside utmp_size */
2582 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2584 const char *remote = "";
2587 remote = auth_get_canonical_hostname(ssh, use_dns);
2588 if (utmp_size == 0 || strlen(remote) > utmp_size)
2589 remote = ssh_remote_ipaddr(ssh);