1 /* $OpenBSD: session.c,v 1.294 2018/03/03 03:15:51 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;
144 extern struct sshauthopt *auth_opts;
145 char *tun_fwd_ifnames; /* serverloop.c */
147 /* original command from peer. */
148 const char *original_command = NULL;
151 static int sessions_first_unused = -1;
152 static int sessions_nalloc = 0;
153 static Session *sessions = NULL;
155 #define SUBSYSTEM_NONE 0
156 #define SUBSYSTEM_EXT 1
157 #define SUBSYSTEM_INT_SFTP 2
158 #define SUBSYSTEM_INT_SFTP_ERROR 3
160 #ifdef HAVE_LOGIN_CAP
164 static int is_child = 0;
165 static int in_chroot = 0;
167 /* File containing userauth info, if ExposeAuthInfo set */
168 static char *auth_info_file = NULL;
170 /* Name and directory of socket for authentication agent forwarding. */
171 static char *auth_sock_name = NULL;
172 static char *auth_sock_dir = NULL;
174 /* removes the agent forwarding socket */
177 auth_sock_cleanup_proc(struct passwd *pw)
179 if (auth_sock_name != NULL) {
180 temporarily_use_uid(pw);
181 unlink(auth_sock_name);
182 rmdir(auth_sock_dir);
183 auth_sock_name = NULL;
189 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
194 if (auth_sock_name != NULL) {
195 error("authentication forwarding requested twice.");
199 /* Temporarily drop privileged uid for mkdir/bind. */
200 temporarily_use_uid(pw);
202 /* Allocate a buffer for the socket name, and format the name. */
203 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
205 /* Create private directory for socket */
206 if (mkdtemp(auth_sock_dir) == NULL) {
207 packet_send_debug("Agent forwarding disabled: "
208 "mkdtemp() failed: %.100s", strerror(errno));
211 auth_sock_dir = NULL;
215 xasprintf(&auth_sock_name, "%s/agent.%ld",
216 auth_sock_dir, (long) getpid());
218 /* Start a Unix listener on auth_sock_name. */
219 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
221 /* Restore the privileged uid. */
224 /* Check for socket/bind/listen failure. */
228 /* Allocate a channel for the authentication agent socket. */
229 nc = channel_new(ssh, "auth socket",
230 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
231 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
232 0, "auth socket", 1);
233 nc->path = xstrdup(auth_sock_name);
237 free(auth_sock_name);
238 if (auth_sock_dir != NULL) {
239 rmdir(auth_sock_dir);
244 auth_sock_name = NULL;
245 auth_sock_dir = NULL;
250 display_loginmsg(void)
252 if (buffer_len(&loginmsg) > 0) {
253 buffer_append(&loginmsg, "\0", 1);
254 printf("%s", (char *)buffer_ptr(&loginmsg));
255 buffer_clear(&loginmsg);
260 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
262 int fd = -1, success = 0;
264 if (!options.expose_userauth_info || info == NULL)
267 temporarily_use_uid(pw);
268 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
269 if ((fd = mkstemp(auth_info_file)) == -1) {
270 error("%s: mkstemp: %s", __func__, strerror(errno));
273 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
274 sshbuf_len(info)) != sshbuf_len(info)) {
275 error("%s: write: %s", __func__, strerror(errno));
278 if (close(fd) != 0) {
279 error("%s: close: %s", __func__, strerror(errno));
287 free(auth_info_file);
288 auth_info_file = NULL;
294 set_permitopen_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
296 char *tmp, *cp, *host;
300 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
302 channel_clear_permitted_opens(ssh);
303 for (i = 0; i < auth_opts->npermitopen; i++) {
304 tmp = cp = xstrdup(auth_opts->permitopen[i]);
305 /* This shouldn't fail as it has already been checked */
306 if ((host = hpdelim(&cp)) == NULL)
307 fatal("%s: internal error: hpdelim", __func__);
308 host = cleanhostname(host);
309 if (cp == NULL || (port = permitopen_port(cp)) < 0)
310 fatal("%s: internal error: permitopen port",
312 channel_add_permitted_opens(ssh, host, port);
318 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
320 setproctitle("%s", authctxt->pw->pw_name);
322 auth_log_authopts("active", auth_opts, 0);
324 /* setup the channel layer */
325 /* XXX - streamlocal? */
326 set_permitopen_from_authopts(ssh, auth_opts);
327 if (!auth_opts->permit_port_forwarding_flag ||
328 options.disable_forwarding ||
329 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
330 channel_disable_adm_local_opens(ssh);
332 channel_permit_all_opens(ssh);
336 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
338 do_authenticated2(ssh, authctxt);
340 do_cleanup(ssh, authctxt);
343 /* Check untrusted xauth strings for metacharacters */
345 xauth_valid_string(const char *s)
349 for (i = 0; s[i] != '\0'; i++) {
350 if (!isalnum((u_char)s[i]) &&
351 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
352 s[i] != '-' && s[i] != '_')
360 * This is called to fork and execute a command when we have no tty. This
361 * will call do_child from the child, and server_loop from the parent after
362 * setting up file descriptors and such.
365 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
369 int pin[2], pout[2], perr[2];
372 fatal("do_exec_no_pty: no session");
374 /* Allocate pipes for communicating with the program. */
376 error("%s: pipe in: %.100s", __func__, strerror(errno));
379 if (pipe(pout) < 0) {
380 error("%s: pipe out: %.100s", __func__, strerror(errno));
385 if (pipe(perr) < 0) {
386 error("%s: pipe err: %.100s", __func__,
395 int inout[2], err[2];
398 fatal("do_exec_no_pty: no session");
400 /* Uses socket pairs to communicate with the program. */
401 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
402 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
405 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
406 error("%s: socketpair #2: %.100s", __func__,
414 session_proctitle(s);
416 /* Fork the child. */
417 switch ((pid = fork())) {
419 error("%s: fork: %.100s", __func__, strerror(errno));
438 * Create a new session and process group since the 4.4BSD
439 * setlogin() affects the entire process group.
442 error("setsid failed: %.100s", strerror(errno));
446 * Redirect stdin. We close the parent side of the socket
447 * pair, and make the child side the standard input.
450 if (dup2(pin[0], 0) < 0)
451 perror("dup2 stdin");
454 /* Redirect stdout. */
456 if (dup2(pout[1], 1) < 0)
457 perror("dup2 stdout");
460 /* Redirect stderr. */
462 if (dup2(perr[1], 2) < 0)
463 perror("dup2 stderr");
467 * Redirect stdin, stdout, and stderr. Stdin and stdout will
468 * use the same socket, as some programs (particularly rdist)
469 * seem to depend on it.
473 if (dup2(inout[0], 0) < 0) /* stdin */
474 perror("dup2 stdin");
475 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
476 perror("dup2 stdout");
478 if (dup2(err[0], 2) < 0) /* stderr */
479 perror("dup2 stderr");
483 /* Do processing for the child (exec command etc). */
484 do_child(ssh, s, command);
491 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
495 /* Set interactive/non-interactive mode. */
496 packet_set_interactive(s->display != NULL,
497 options.ip_qos_interactive, options.ip_qos_bulk);
500 * Clear loginmsg, since it's the child's responsibility to display
501 * it to the user, otherwise multiple sessions may accumulate
502 * multiple copies of the login messages.
504 buffer_clear(&loginmsg);
507 /* We are the parent. Close the child sides of the pipes. */
512 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
515 /* We are the parent. Close the child sides of the socket pairs. */
520 * Enter the interactive session. Note: server_loop must be able to
521 * handle the case that fdin and fdout are the same.
523 session_set_fds(s, inout[1], inout[1], err[1],
530 * This is called to fork and execute a command when we have a tty. This
531 * will call do_child from the child, and server_loop from the parent after
532 * setting up file descriptors, controlling tty, updating wtmp, utmp,
533 * lastlog, and other such operations.
536 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
538 int fdout, ptyfd, ttyfd, ptymaster;
542 fatal("do_exec_pty: no session");
547 * Create another descriptor of the pty master side for use as the
548 * standard input. We could use the original descriptor, but this
549 * simplifies code in server_loop. The descriptor is bidirectional.
550 * Do this before forking (and cleanup in the child) so as to
551 * detect and gracefully fail out-of-fd conditions.
553 if ((fdout = dup(ptyfd)) < 0) {
554 error("%s: dup #1: %s", __func__, strerror(errno));
559 /* we keep a reference to the pty master */
560 if ((ptymaster = dup(ptyfd)) < 0) {
561 error("%s: dup #2: %s", __func__, strerror(errno));
568 /* Fork the child. */
569 switch ((pid = fork())) {
571 error("%s: fork: %.100s", __func__, strerror(errno));
583 /* Close the master side of the pseudo tty. */
586 /* Make the pseudo tty our controlling tty. */
587 pty_make_controlling_tty(&ttyfd, s->tty);
589 /* Redirect stdin/stdout/stderr from the pseudo tty. */
590 if (dup2(ttyfd, 0) < 0)
591 error("dup2 stdin: %s", strerror(errno));
592 if (dup2(ttyfd, 1) < 0)
593 error("dup2 stdout: %s", strerror(errno));
594 if (dup2(ttyfd, 2) < 0)
595 error("dup2 stderr: %s", strerror(errno));
597 /* Close the extra descriptor for the pseudo tty. */
600 /* record login, etc. similar to login(1) */
602 do_login(ssh, s, command);
605 * Do common processing for the child, such as execing
608 do_child(ssh, s, command);
615 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
620 /* Parent. Close the slave side of the pseudo tty. */
623 /* Enter interactive session. */
624 s->ptymaster = ptymaster;
625 packet_set_interactive(1,
626 options.ip_qos_interactive, options.ip_qos_bulk);
627 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
631 #ifdef LOGIN_NEEDS_UTMPX
633 do_pre_login(Session *s)
635 struct ssh *ssh = active_state; /* XXX */
637 struct sockaddr_storage from;
638 pid_t pid = getpid();
641 * Get IP address of client. If the connection is not a socket, let
642 * the address be 0.0.0.0.
644 memset(&from, 0, sizeof(from));
645 fromlen = sizeof(from);
646 if (packet_connection_is_on_socket()) {
647 if (getpeername(packet_get_connection_in(),
648 (struct sockaddr *)&from, &fromlen) < 0) {
649 debug("getpeername: %.100s", strerror(errno));
654 record_utmp_only(pid, s->tty, s->pw->pw_name,
655 session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
656 (struct sockaddr *)&from, fromlen);
661 * This is called to fork and execute a command. If another command is
662 * to be forced, execute that instead.
665 do_exec(struct ssh *ssh, Session *s, const char *command)
668 const char *forced = NULL, *tty = NULL;
669 char session_type[1024];
671 if (options.adm_forced_command) {
672 original_command = command;
673 command = options.adm_forced_command;
675 } else if (auth_opts->force_command != NULL) {
676 original_command = command;
677 command = auth_opts->force_command;
678 forced = "(key-option)";
680 if (forced != NULL) {
681 if (IS_INTERNAL_SFTP(command)) {
682 s->is_subsystem = s->is_subsystem ?
683 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
684 } else if (s->is_subsystem)
685 s->is_subsystem = SUBSYSTEM_EXT;
686 snprintf(session_type, sizeof(session_type),
687 "forced-command %s '%.900s'", forced, command);
688 } else if (s->is_subsystem) {
689 snprintf(session_type, sizeof(session_type),
690 "subsystem '%.900s'", s->subsys);
691 } else if (command == NULL) {
692 snprintf(session_type, sizeof(session_type), "shell");
694 /* NB. we don't log unforced commands to preserve privacy */
695 snprintf(session_type, sizeof(session_type), "command");
698 if (s->ttyfd != -1) {
700 if (strncmp(tty, "/dev/", 5) == 0)
704 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
706 tty == NULL ? "" : " on ",
707 tty == NULL ? "" : tty,
709 ssh_remote_ipaddr(ssh),
710 ssh_remote_port(ssh),
713 #ifdef SSH_AUDIT_EVENTS
715 PRIVSEP(audit_run_command(command));
716 else if (s->ttyfd == -1) {
717 char *shell = s->pw->pw_shell;
719 if (shell[0] == '\0') /* empty shell means /bin/sh */
721 PRIVSEP(audit_run_command(shell));
725 ret = do_exec_pty(ssh, s, command);
727 ret = do_exec_no_pty(ssh, s, command);
729 original_command = NULL;
732 * Clear loginmsg: it's the child's responsibility to display
733 * it to the user, otherwise multiple sessions may accumulate
734 * multiple copies of the login messages.
736 buffer_clear(&loginmsg);
741 /* administrative, login(1)-like work */
743 do_login(struct ssh *ssh, Session *s, const char *command)
746 struct sockaddr_storage from;
747 struct passwd * pw = s->pw;
748 pid_t pid = getpid();
751 * Get IP address of client. If the connection is not a socket, let
752 * the address be 0.0.0.0.
754 memset(&from, 0, sizeof(from));
755 fromlen = sizeof(from);
756 if (packet_connection_is_on_socket()) {
757 if (getpeername(packet_get_connection_in(),
758 (struct sockaddr *)&from, &fromlen) < 0) {
759 debug("getpeername: %.100s", strerror(errno));
764 /* Record that there was a login on that tty from the remote host. */
766 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
767 session_get_remote_name_or_ip(ssh, utmp_len,
769 (struct sockaddr *)&from, fromlen);
773 * If password change is needed, do it now.
774 * This needs to occur before the ~/.hushlogin check.
776 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
779 s->authctxt->force_pwchange = 0;
780 /* XXX - signal [net] parent to enable forwardings */
784 if (check_quietlogin(s, command))
793 * Display the message of the day.
801 if (options.print_motd) {
802 #ifdef HAVE_LOGIN_CAP
803 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
806 f = fopen("/etc/motd", "r");
809 while (fgets(buf, sizeof(buf), f))
818 * Check for quiet login, either .hushlogin or command given.
821 check_quietlogin(Session *s, const char *command)
824 struct passwd *pw = s->pw;
827 /* Return 1 if .hushlogin exists or a command given. */
830 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
831 #ifdef HAVE_LOGIN_CAP
832 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
835 if (stat(buf, &st) >= 0)
842 * Reads environment variables from the given file and adds/overrides them
843 * into the environment. If the file does not exist, this does nothing.
844 * Otherwise, it must consist of empty lines, comments (line starts with '#')
845 * and assignments of the form name=value. No other forms are allowed.
848 read_environment_file(char ***env, u_int *envsize,
849 const char *filename)
856 f = fopen(filename, "r");
860 while (fgets(buf, sizeof(buf), f)) {
862 fatal("Too many lines in environment file %s", filename);
863 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
865 if (!*cp || *cp == '#' || *cp == '\n')
868 cp[strcspn(cp, "\n")] = '\0';
870 value = strchr(cp, '=');
872 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
877 * Replace the equals sign by nul, and advance value to
882 child_set_env(env, envsize, cp, value);
887 #ifdef HAVE_ETC_DEFAULT_LOGIN
889 * Return named variable from specified environment, or NULL if not present.
892 child_get_env(char **env, const char *name)
898 for (i=0; env[i] != NULL; i++)
899 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
900 return(env[i] + len + 1);
905 * Read /etc/default/login.
906 * We pick up the PATH (or SUPATH for root) and UMASK.
909 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
911 char **tmpenv = NULL, *var;
912 u_int i, tmpenvsize = 0;
916 * We don't want to copy the whole file to the child's environment,
917 * so we use a temporary environment and copy the variables we're
920 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
926 var = child_get_env(tmpenv, "SUPATH");
928 var = child_get_env(tmpenv, "PATH");
930 child_set_env(env, envsize, "PATH", var);
932 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
933 if (sscanf(var, "%5lo", &mask) == 1)
936 for (i = 0; tmpenv[i] != NULL; i++)
940 #endif /* HAVE_ETC_DEFAULT_LOGIN */
943 copy_environment_blacklist(char **source, char ***env, u_int *envsize,
944 const char *blacklist)
946 char *var_name, *var_val;
952 for(i = 0; source[i] != NULL; i++) {
953 var_name = xstrdup(source[i]);
954 if ((var_val = strstr(var_name, "=")) == NULL) {
960 if (blacklist == NULL ||
961 match_pattern_list(var_name, blacklist, 0) != 1) {
962 debug3("Copy environment: %s=%s", var_name, var_val);
963 child_set_env(env, envsize, var_name, var_val);
971 copy_environment(char **source, char ***env, u_int *envsize)
973 copy_environment_blacklist(source, env, envsize, NULL);
977 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
982 char *ocp, *cp, **env, *laddr;
983 struct passwd *pw = s->pw;
984 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
987 extern char **environ;
988 char **senv, **var, *val;
991 /* Initialize the environment. */
993 env = xcalloc(envsize, sizeof(char *));
998 * The Windows environment contains some setting which are
999 * important for a running system. They must not be dropped.
1004 p = fetch_windows_environment();
1005 copy_environment(p, &env, &envsize);
1006 free_windows_environment(p);
1011 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1014 /* Allow any GSSAPI methods that we've used to alter
1015 * the childs environment as they see fit
1017 ssh_gssapi_do_child(&env, &envsize);
1020 /* Set basic environment. */
1021 for (i = 0; i < s->num_env; i++)
1022 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1024 child_set_env(&env, &envsize, "USER", pw->pw_name);
1025 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1027 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1029 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1030 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1031 child_set_env(&env, &envsize, "MAIL", buf);
1032 #ifdef HAVE_LOGIN_CAP
1033 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1034 child_set_env(&env, &envsize, "TERM", "su");
1036 * Temporarily swap out our real environment with an empty one,
1037 * let setusercontext() apply any environment variables defined
1038 * for the user's login class, copy those variables to the child,
1039 * free the temporary environment, and restore the original.
1042 environ = xmalloc(sizeof(*environ));
1044 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1045 for (var = environ; *var != NULL; ++var) {
1046 if ((val = strchr(*var, '=')) != NULL) {
1048 child_set_env(&env, &envsize, *var, val);
1054 #else /* HAVE_LOGIN_CAP */
1055 # ifndef HAVE_CYGWIN
1057 * There's no standard path on Windows. The path contains
1058 * important components pointing to the system directories,
1059 * needed for loading shared libraries. So the path better
1060 * remains intact here.
1062 # ifdef HAVE_ETC_DEFAULT_LOGIN
1063 read_etc_default_login(&env, &envsize, pw->pw_uid);
1064 path = child_get_env(env, "PATH");
1065 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1066 if (path == NULL || *path == '\0') {
1067 child_set_env(&env, &envsize, "PATH",
1068 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1070 # endif /* HAVE_CYGWIN */
1071 #endif /* HAVE_LOGIN_CAP */
1073 /* Normal systems set SHELL by default. */
1074 child_set_env(&env, &envsize, "SHELL", shell);
1077 /* Set custom environment options from pubkey authentication. */
1078 if (options.permit_user_env) {
1079 for (n = 0 ; n < auth_opts->nenv; n++) {
1080 ocp = xstrdup(auth_opts->env[n]);
1081 cp = strchr(ocp, '=');
1084 child_set_env(&env, &envsize, ocp, cp + 1);
1090 /* SSH_CLIENT deprecated */
1091 snprintf(buf, sizeof buf, "%.50s %d %d",
1092 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1093 ssh_local_port(ssh));
1094 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1096 laddr = get_local_ipaddr(packet_get_connection_in());
1097 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1098 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1099 laddr, ssh_local_port(ssh));
1101 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1103 if (tun_fwd_ifnames != NULL)
1104 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1105 if (auth_info_file != NULL)
1106 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1108 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1110 child_set_env(&env, &envsize, "TERM", s->term);
1112 child_set_env(&env, &envsize, "DISPLAY", s->display);
1113 if (original_command)
1114 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1118 * Since we clear KRB5CCNAME at startup, if it's set now then it
1119 * must have been set by a native authentication method (eg AIX or
1120 * SIA), so copy it to the child.
1125 if ((cp = getenv("KRB5CCNAME")) != NULL)
1126 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1133 if ((cp = getenv("AUTHSTATE")) != NULL)
1134 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1135 read_environment_file(&env, &envsize, "/etc/environment");
1139 if (s->authctxt->krb5_ccname)
1140 child_set_env(&env, &envsize, "KRB5CCNAME",
1141 s->authctxt->krb5_ccname);
1145 * Pull in any environment variables that may have
1148 if (options.use_pam) {
1152 * Don't allow SSH_AUTH_INFO variables posted to PAM to leak
1153 * back into the environment.
1155 p = fetch_pam_child_environment();
1156 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1157 free_pam_environment(p);
1159 p = fetch_pam_environment();
1160 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1161 free_pam_environment(p);
1163 #endif /* USE_PAM */
1165 if (auth_sock_name != NULL)
1166 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1169 /* read $HOME/.ssh/environment. */
1170 if (options.permit_user_env) {
1171 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1172 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1173 read_environment_file(&env, &envsize, buf);
1176 /* dump the environment */
1177 fprintf(stderr, "Environment:\n");
1178 for (i = 0; env[i]; i++)
1179 fprintf(stderr, " %.200s\n", env[i]);
1185 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1186 * first in this order).
1189 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1197 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1199 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1200 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1201 auth_opts->permit_user_rc && options.permit_user_rc &&
1202 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1203 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1204 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1206 fprintf(stderr, "Running %s\n", cmd);
1207 f = popen(cmd, "w");
1210 fprintf(f, "%s %s\n", s->auth_proto,
1214 fprintf(stderr, "Could not run %s\n",
1216 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1218 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1219 _PATH_SSH_SYSTEM_RC);
1220 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1223 fprintf(f, "%s %s\n", s->auth_proto,
1227 fprintf(stderr, "Could not run %s\n",
1228 _PATH_SSH_SYSTEM_RC);
1229 } else if (do_xauth && options.xauth_location != NULL) {
1230 /* Add authority data to .Xauthority if appropriate. */
1233 "Running %.500s remove %.100s\n",
1234 options.xauth_location, s->auth_display);
1236 "%.500s add %.100s %.100s %.100s\n",
1237 options.xauth_location, s->auth_display,
1238 s->auth_proto, s->auth_data);
1240 snprintf(cmd, sizeof cmd, "%s -q -",
1241 options.xauth_location);
1242 f = popen(cmd, "w");
1244 fprintf(f, "remove %s\n",
1246 fprintf(f, "add %s %s %s\n",
1247 s->auth_display, s->auth_proto,
1251 fprintf(stderr, "Could not run %s\n",
1258 do_nologin(struct passwd *pw)
1262 char buf[1024], *def_nl = _PATH_NOLOGIN;
1265 #ifdef HAVE_LOGIN_CAP
1266 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1268 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1270 if (pw->pw_uid == 0)
1274 if (stat(nl, &sb) == -1)
1277 /* /etc/nologin exists. Print its contents if we can and exit. */
1278 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1279 if ((f = fopen(nl, "r")) != NULL) {
1280 while (fgets(buf, sizeof(buf), f))
1288 * Chroot into a directory after checking it for safety: all path components
1289 * must be root-owned directories with strict permissions.
1292 safely_chroot(const char *path, uid_t uid)
1295 char component[PATH_MAX];
1299 fatal("chroot path does not begin at root");
1300 if (strlen(path) >= sizeof(component))
1301 fatal("chroot path too long");
1304 * Descend the path, checking that each component is a
1305 * root-owned directory with strict permissions.
1307 for (cp = path; cp != NULL;) {
1308 if ((cp = strchr(cp, '/')) == NULL)
1309 strlcpy(component, path, sizeof(component));
1312 memcpy(component, path, cp - path);
1313 component[cp - path] = '\0';
1316 debug3("%s: checking '%s'", __func__, component);
1318 if (stat(component, &st) != 0)
1319 fatal("%s: stat(\"%s\"): %s", __func__,
1320 component, strerror(errno));
1321 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1322 fatal("bad ownership or modes for chroot "
1323 "directory %s\"%s\"",
1324 cp == NULL ? "" : "component ", component);
1325 if (!S_ISDIR(st.st_mode))
1326 fatal("chroot path %s\"%s\" is not a directory",
1327 cp == NULL ? "" : "component ", component);
1331 if (chdir(path) == -1)
1332 fatal("Unable to chdir to chroot path \"%s\": "
1333 "%s", path, strerror(errno));
1334 if (chroot(path) == -1)
1335 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1336 if (chdir("/") == -1)
1337 fatal("%s: chdir(/) after chroot: %s",
1338 __func__, strerror(errno));
1339 verbose("Changed root directory to \"%s\"", path);
1342 /* Set login name, uid, gid, and groups. */
1344 do_setusercontext(struct passwd *pw)
1346 char *chroot_path, *tmp;
1348 platform_setusercontext(pw);
1350 if (platform_privileged_uidswap()) {
1351 #ifdef HAVE_LOGIN_CAP
1352 if (setusercontext(lc, pw, pw->pw_uid,
1353 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1354 perror("unable to set user context");
1358 if (setlogin(pw->pw_name) < 0)
1359 error("setlogin failed: %s", strerror(errno));
1360 if (setgid(pw->pw_gid) < 0) {
1364 /* Initialize the group list. */
1365 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1366 perror("initgroups");
1372 platform_setusercontext_post_groups(pw);
1374 if (!in_chroot && options.chroot_directory != NULL &&
1375 strcasecmp(options.chroot_directory, "none") != 0) {
1376 tmp = tilde_expand_filename(options.chroot_directory,
1378 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1379 "u", pw->pw_name, (char *)NULL);
1380 safely_chroot(chroot_path, pw->pw_uid);
1383 /* Make sure we don't attempt to chroot again */
1384 free(options.chroot_directory);
1385 options.chroot_directory = NULL;
1389 #ifdef HAVE_LOGIN_CAP
1390 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1391 perror("unable to set user context (setuser)");
1395 * FreeBSD's setusercontext() will not apply the user's
1396 * own umask setting unless running with the user's UID.
1398 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1402 * In a chroot environment, the set_id() will always fail;
1403 * typically because of the lack of necessary authentication
1404 * services and runtime such as ./usr/lib/libiaf.so,
1405 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1406 * internal sftp chroot case. We'll lose auditing and ACLs but
1407 * permanently_set_uid will take care of the rest.
1409 if (!in_chroot && set_id(pw->pw_name) != 0)
1410 fatal("set_id(%s) Failed", pw->pw_name);
1411 # endif /* USE_LIBIAF */
1412 /* Permanently switch to the desired uid. */
1413 permanently_set_uid(pw);
1415 } else if (options.chroot_directory != NULL &&
1416 strcasecmp(options.chroot_directory, "none") != 0) {
1417 fatal("server lacks privileges to chroot to ChrootDirectory");
1420 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1421 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1425 do_pwchange(Session *s)
1428 fprintf(stderr, "WARNING: Your password has expired.\n");
1429 if (s->ttyfd != -1) {
1431 "You must change your password now and login again!\n");
1435 #ifdef PASSWD_NEEDS_USERNAME
1436 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1439 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1444 "Password change required but no TTY available.\n");
1450 child_close_fds(struct ssh *ssh)
1452 extern int auth_sock;
1454 if (auth_sock != -1) {
1459 if (packet_get_connection_in() == packet_get_connection_out())
1460 close(packet_get_connection_in());
1462 close(packet_get_connection_in());
1463 close(packet_get_connection_out());
1466 * Close all descriptors related to channels. They will still remain
1467 * open in the parent.
1469 /* XXX better use close-on-exec? -markus */
1470 channel_close_all(ssh);
1473 * Close any extra file descriptors. Note that there may still be
1474 * descriptors left by system functions. They will be closed later.
1479 * Close any extra open file descriptors so that we don't have them
1480 * hanging around in clients. Note that we want to do this after
1481 * initgroups, because at least on Solaris 2.3 it leaves file
1484 closefrom(STDERR_FILENO + 1);
1488 * Performs common processing for the child, such as setting up the
1489 * environment, closing extra file descriptors, setting the user and group
1490 * ids, and executing the command or shell.
1494 do_child(struct ssh *ssh, Session *s, const char *command)
1496 extern char **environ;
1498 char *argv[ARGV_MAX];
1499 const char *shell, *shell0;
1500 struct passwd *pw = s->pw;
1503 /* remove hostkey from the child's memory */
1504 destroy_sensitive_data();
1505 packet_clear_keys();
1507 /* Force a password change */
1508 if (s->authctxt->force_pwchange) {
1509 do_setusercontext(pw);
1510 child_close_fds(ssh);
1516 * Login(1) does this as well, and it needs uid 0 for the "-h"
1517 * switch, so we let login(1) to this for us.
1520 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1521 if (!check_quietlogin(s, command))
1523 #else /* HAVE_OSF_SIA */
1524 /* When PAM is enabled we rely on it to do the nologin check */
1525 if (!options.use_pam)
1527 do_setusercontext(pw);
1529 * PAM session modules in do_setusercontext may have
1530 * generated messages, so if this in an interactive
1531 * login then display them too.
1533 if (!check_quietlogin(s, command))
1535 #endif /* HAVE_OSF_SIA */
1538 if (options.use_pam && !is_pam_session_open()) {
1539 debug3("PAM session not opened, exiting");
1546 * Get the shell from the password data. An empty shell field is
1547 * legal, and means /bin/sh.
1549 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1552 * Make sure $SHELL points to the shell from the password file,
1553 * even if shell is overridden from login.conf
1555 env = do_setup_env(ssh, s, shell);
1557 #ifdef HAVE_LOGIN_CAP
1558 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1562 * Close the connection descriptors; note that this is the child, and
1563 * the server will still have the socket open, and it is important
1564 * that we do not shutdown it. Note that the descriptors cannot be
1565 * closed before building the environment, as we call
1566 * ssh_remote_ipaddr there.
1568 child_close_fds(ssh);
1571 * Must take new environment into use so that .ssh/rc,
1572 * /etc/ssh/sshrc and xauth are run in the proper environment.
1576 #if defined(KRB5) && defined(USE_AFS)
1578 * At this point, we check to see if AFS is active and if we have
1579 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1580 * if we can (and need to) extend the ticket into an AFS token. If
1581 * we don't do this, we run into potential problems if the user's
1582 * home directory is in AFS and it's not world-readable.
1585 if (options.kerberos_get_afs_token && k_hasafs() &&
1586 (s->authctxt->krb5_ctx != NULL)) {
1589 debug("Getting AFS token");
1593 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1594 krb5_afslog(s->authctxt->krb5_ctx,
1595 s->authctxt->krb5_fwd_ccache, cell, NULL);
1597 krb5_afslog_home(s->authctxt->krb5_ctx,
1598 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1602 /* Change current directory to the user's home directory. */
1603 if (chdir(pw->pw_dir) < 0) {
1604 /* Suppress missing homedir warning for chroot case */
1605 #ifdef HAVE_LOGIN_CAP
1606 r = login_getcapbool(lc, "requirehome", 0);
1608 if (r || !in_chroot) {
1609 fprintf(stderr, "Could not chdir to home "
1610 "directory %s: %s\n", pw->pw_dir,
1617 closefrom(STDERR_FILENO + 1);
1619 do_rc_files(ssh, s, shell);
1621 /* restore SIGPIPE for child */
1622 signal(SIGPIPE, SIG_DFL);
1624 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1625 printf("This service allows sftp connections only.\n");
1628 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1629 extern int optind, optreset;
1633 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1634 args = xstrdup(command ? command : "sftp-server");
1635 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1636 if (i < ARGV_MAX - 1)
1639 optind = optreset = 1;
1640 __progname = argv[0];
1642 ssh_selinux_change_context("sftpd_t");
1644 exit(sftp_server_main(i, argv, s->pw));
1649 /* Get the last component of the shell name. */
1650 if ((shell0 = strrchr(shell, '/')) != NULL)
1656 * If we have no command, execute the shell. In this case, the shell
1657 * name to be passed in argv[0] is preceded by '-' to indicate that
1658 * this is a login shell.
1663 /* Start the shell. Set initial character to '-'. */
1666 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1667 >= sizeof(argv0) - 1) {
1673 /* Execute the shell. */
1676 execve(shell, argv, env);
1678 /* Executing the shell failed. */
1683 * Execute the command using the user's shell. This uses the -c
1684 * option to execute the command.
1686 argv[0] = (char *) shell0;
1688 argv[2] = (char *) command;
1690 execve(shell, argv, env);
1696 session_unused(int id)
1698 debug3("%s: session id %d unused", __func__, id);
1699 if (id >= options.max_sessions ||
1700 id >= sessions_nalloc) {
1701 fatal("%s: insane session id %d (max %d nalloc %d)",
1702 __func__, id, options.max_sessions, sessions_nalloc);
1704 memset(&sessions[id], 0, sizeof(*sessions));
1705 sessions[id].self = id;
1706 sessions[id].used = 0;
1707 sessions[id].chanid = -1;
1708 sessions[id].ptyfd = -1;
1709 sessions[id].ttyfd = -1;
1710 sessions[id].ptymaster = -1;
1711 sessions[id].x11_chanids = NULL;
1712 sessions[id].next_unused = sessions_first_unused;
1713 sessions_first_unused = id;
1721 if (sessions_first_unused == -1) {
1722 if (sessions_nalloc >= options.max_sessions)
1724 debug2("%s: allocate (allocated %d max %d)",
1725 __func__, sessions_nalloc, options.max_sessions);
1726 tmp = xrecallocarray(sessions, sessions_nalloc,
1727 sessions_nalloc + 1, sizeof(*sessions));
1729 error("%s: cannot allocate %d sessions",
1730 __func__, sessions_nalloc + 1);
1734 session_unused(sessions_nalloc++);
1737 if (sessions_first_unused >= sessions_nalloc ||
1738 sessions_first_unused < 0) {
1739 fatal("%s: insane first_unused %d max %d nalloc %d",
1740 __func__, sessions_first_unused, options.max_sessions,
1744 s = &sessions[sessions_first_unused];
1746 fatal("%s: session %d already used",
1747 __func__, sessions_first_unused);
1749 sessions_first_unused = s->next_unused;
1751 s->next_unused = -1;
1752 debug("session_new: session %d", s->self);
1761 for (i = 0; i < sessions_nalloc; i++) {
1762 Session *s = &sessions[i];
1764 debug("dump: used %d next_unused %d session %d %p "
1765 "channel %d pid %ld",
1776 session_open(Authctxt *authctxt, int chanid)
1778 Session *s = session_new();
1779 debug("session_open: channel %d", chanid);
1781 error("no more sessions");
1784 s->authctxt = authctxt;
1785 s->pw = authctxt->pw;
1786 if (s->pw == NULL || !authctxt->valid)
1787 fatal("no user for session %d", s->self);
1788 debug("session_open: session %d: link with channel %d", s->self, chanid);
1794 session_by_tty(char *tty)
1797 for (i = 0; i < sessions_nalloc; i++) {
1798 Session *s = &sessions[i];
1799 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1800 debug("session_by_tty: session %d tty %s", i, tty);
1804 debug("session_by_tty: unknown tty %.100s", tty);
1810 session_by_channel(int id)
1813 for (i = 0; i < sessions_nalloc; i++) {
1814 Session *s = &sessions[i];
1815 if (s->used && s->chanid == id) {
1816 debug("session_by_channel: session %d channel %d",
1821 debug("session_by_channel: unknown channel %d", id);
1827 session_by_x11_channel(int id)
1831 for (i = 0; i < sessions_nalloc; i++) {
1832 Session *s = &sessions[i];
1834 if (s->x11_chanids == NULL || !s->used)
1836 for (j = 0; s->x11_chanids[j] != -1; j++) {
1837 if (s->x11_chanids[j] == id) {
1838 debug("session_by_x11_channel: session %d "
1839 "channel %d", s->self, id);
1844 debug("session_by_x11_channel: unknown channel %d", id);
1850 session_by_pid(pid_t pid)
1853 debug("session_by_pid: pid %ld", (long)pid);
1854 for (i = 0; i < sessions_nalloc; i++) {
1855 Session *s = &sessions[i];
1856 if (s->used && s->pid == pid)
1859 error("session_by_pid: unknown pid %ld", (long)pid);
1865 session_window_change_req(struct ssh *ssh, Session *s)
1867 s->col = packet_get_int();
1868 s->row = packet_get_int();
1869 s->xpixel = packet_get_int();
1870 s->ypixel = packet_get_int();
1872 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1877 session_pty_req(struct ssh *ssh, Session *s)
1882 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1883 debug("Allocating a pty not permitted for this connection.");
1886 if (s->ttyfd != -1) {
1887 packet_disconnect("Protocol error: you already have a pty.");
1891 s->term = packet_get_string(&len);
1892 s->col = packet_get_int();
1893 s->row = packet_get_int();
1894 s->xpixel = packet_get_int();
1895 s->ypixel = packet_get_int();
1897 if (strcmp(s->term, "") == 0) {
1902 /* Allocate a pty and open it. */
1903 debug("Allocating pty.");
1904 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1910 error("session_pty_req: session %d alloc failed", s->self);
1913 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1915 n_bytes = packet_remaining();
1916 tty_parse_modes(s->ttyfd, &n_bytes);
1919 pty_setowner(s->pw, s->tty);
1921 /* Set window size from the packet. */
1922 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1925 session_proctitle(s);
1930 session_subsystem_req(struct ssh *ssh, Session *s)
1938 s->subsys = packet_get_string(&len);
1940 debug2("subsystem request for %.100s by user %s", s->subsys,
1943 for (i = 0; i < options.num_subsystems; i++) {
1944 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1945 prog = options.subsystem_command[i];
1946 cmd = options.subsystem_args[i];
1947 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1948 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1949 debug("subsystem: %s", prog);
1951 if (stat(prog, &st) < 0)
1952 debug("subsystem: cannot stat %s: %s",
1953 prog, strerror(errno));
1954 s->is_subsystem = SUBSYSTEM_EXT;
1955 debug("subsystem: exec() %s", cmd);
1957 success = do_exec(ssh, s, cmd) == 0;
1963 logit("subsystem request for %.100s by user %s failed, "
1964 "subsystem not found", s->subsys, s->pw->pw_name);
1970 session_x11_req(struct ssh *ssh, Session *s)
1974 if (s->auth_proto != NULL || s->auth_data != NULL) {
1975 error("session_x11_req: session %d: "
1976 "x11 forwarding already active", s->self);
1979 s->single_connection = packet_get_char();
1980 s->auth_proto = packet_get_string(NULL);
1981 s->auth_data = packet_get_string(NULL);
1982 s->screen = packet_get_int();
1985 if (xauth_valid_string(s->auth_proto) &&
1986 xauth_valid_string(s->auth_data))
1987 success = session_setup_x11fwd(ssh, s);
1990 error("Invalid X11 forwarding data");
1993 free(s->auth_proto);
1995 s->auth_proto = NULL;
1996 s->auth_data = NULL;
2002 session_shell_req(struct ssh *ssh, Session *s)
2005 return do_exec(ssh, s, NULL) == 0;
2009 session_exec_req(struct ssh *ssh, Session *s)
2013 char *command = packet_get_string(&len);
2015 success = do_exec(ssh, s, command) == 0;
2021 session_break_req(struct ssh *ssh, Session *s)
2024 packet_get_int(); /* ignored */
2027 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2033 session_env_req(struct ssh *ssh, Session *s)
2036 u_int name_len, val_len, i;
2038 name = packet_get_cstring(&name_len);
2039 val = packet_get_cstring(&val_len);
2042 /* Don't set too many environment variables */
2043 if (s->num_env > 128) {
2044 debug2("Ignoring env request %s: too many env vars", name);
2048 for (i = 0; i < options.num_accept_env; i++) {
2049 if (match_pattern(name, options.accept_env[i])) {
2050 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2051 s->env = xrecallocarray(s->env, s->num_env,
2052 s->num_env + 1, sizeof(*s->env));
2053 s->env[s->num_env].name = name;
2054 s->env[s->num_env].val = val;
2059 debug2("Ignoring env request %s: disallowed name", name);
2068 session_auth_agent_req(struct ssh *ssh, Session *s)
2070 static int called = 0;
2073 if (!auth_opts->permit_agent_forwarding_flag ||
2074 !options.allow_agent_forwarding) {
2075 debug("%s: agent forwarding disabled", __func__);
2082 return auth_input_request_forwarding(ssh, s->pw);
2087 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2092 if ((s = session_by_channel(c->self)) == NULL) {
2093 logit("%s: no session %d req %.100s", __func__, c->self, rtype);
2096 debug("%s: session %d req %s", __func__, s->self, rtype);
2099 * a session is in LARVAL state until a shell, a command
2100 * or a subsystem is executed
2102 if (c->type == SSH_CHANNEL_LARVAL) {
2103 if (strcmp(rtype, "shell") == 0) {
2104 success = session_shell_req(ssh, s);
2105 } else if (strcmp(rtype, "exec") == 0) {
2106 success = session_exec_req(ssh, s);
2107 } else if (strcmp(rtype, "pty-req") == 0) {
2108 success = session_pty_req(ssh, s);
2109 } else if (strcmp(rtype, "x11-req") == 0) {
2110 success = session_x11_req(ssh, s);
2111 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2112 success = session_auth_agent_req(ssh, s);
2113 } else if (strcmp(rtype, "subsystem") == 0) {
2114 success = session_subsystem_req(ssh, s);
2115 } else if (strcmp(rtype, "env") == 0) {
2116 success = session_env_req(ssh, s);
2119 if (strcmp(rtype, "window-change") == 0) {
2120 success = session_window_change_req(ssh, s);
2121 } else if (strcmp(rtype, "break") == 0) {
2122 success = session_break_req(ssh, s);
2129 session_set_fds(struct ssh *ssh, Session *s,
2130 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2133 * now that have a child and a pipe to the child,
2134 * we can activate our channel and register the fd's
2136 if (s->chanid == -1)
2137 fatal("no channel for session %d", s->self);
2138 channel_set_fds(ssh, s->chanid,
2140 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2141 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2145 * Function to perform pty cleanup. Also called if we get aborted abnormally
2146 * (e.g., due to a dropped connection).
2149 session_pty_cleanup2(Session *s)
2152 error("session_pty_cleanup: no session");
2158 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2160 /* Record that the user has logged out. */
2162 record_logout(s->pid, s->tty, s->pw->pw_name);
2164 /* Release the pseudo-tty. */
2166 pty_release(s->tty);
2169 * Close the server side of the socket pairs. We must do this after
2170 * the pty cleanup, so that another process doesn't get this pty
2171 * while we're still cleaning up.
2173 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2174 error("close(s->ptymaster/%d): %s",
2175 s->ptymaster, strerror(errno));
2177 /* unlink pty from session */
2182 session_pty_cleanup(Session *s)
2184 PRIVSEP(session_pty_cleanup2(s));
2190 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2205 return "SIG@openssh.com";
2209 session_close_x11(struct ssh *ssh, int id)
2213 if ((c = channel_by_id(ssh, id)) == NULL) {
2214 debug("%s: x11 channel %d missing", __func__, id);
2216 /* Detach X11 listener */
2217 debug("%s: detach x11 channel %d", __func__, id);
2218 channel_cancel_cleanup(ssh, id);
2219 if (c->ostate != CHAN_OUTPUT_CLOSED)
2220 chan_mark_dead(ssh, c);
2225 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2230 debug3("%s: channel %d", __func__, id);
2231 channel_cancel_cleanup(ssh, id);
2232 if ((s = session_by_x11_channel(id)) == NULL)
2233 fatal("%s: no x11 channel %d", __func__, id);
2234 for (i = 0; s->x11_chanids[i] != -1; i++) {
2235 debug("%s: session %d: closing channel %d",
2236 __func__, s->self, s->x11_chanids[i]);
2238 * The channel "id" is already closing, but make sure we
2239 * close all of its siblings.
2241 if (s->x11_chanids[i] != id)
2242 session_close_x11(ssh, s->x11_chanids[i]);
2244 free(s->x11_chanids);
2245 s->x11_chanids = NULL;
2248 free(s->auth_proto);
2249 s->auth_proto = NULL;
2251 s->auth_data = NULL;
2252 free(s->auth_display);
2253 s->auth_display = NULL;
2257 session_exit_message(struct ssh *ssh, Session *s, int status)
2261 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2262 fatal("%s: session %d: no channel %d",
2263 __func__, s->self, s->chanid);
2264 debug("%s: session %d channel %d pid %ld",
2265 __func__, s->self, s->chanid, (long)s->pid);
2267 if (WIFEXITED(status)) {
2268 channel_request_start(ssh, s->chanid, "exit-status", 0);
2269 packet_put_int(WEXITSTATUS(status));
2271 } else if (WIFSIGNALED(status)) {
2272 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2273 packet_put_cstring(sig2name(WTERMSIG(status)));
2275 packet_put_char(WCOREDUMP(status)? 1 : 0);
2276 #else /* WCOREDUMP */
2278 #endif /* WCOREDUMP */
2279 packet_put_cstring("");
2280 packet_put_cstring("");
2283 /* Some weird exit cause. Just exit. */
2284 packet_disconnect("wait returned status %04x.", status);
2287 /* disconnect channel */
2288 debug("%s: release channel %d", __func__, s->chanid);
2291 * Adjust cleanup callback attachment to send close messages when
2292 * the channel gets EOF. The session will be then be closed
2293 * by session_close_by_channel when the childs close their fds.
2295 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2298 * emulate a write failure with 'chan_write_failed', nobody will be
2299 * interested in data we write.
2300 * Note that we must not call 'chan_read_failed', since there could
2301 * be some more data waiting in the pipe.
2303 if (c->ostate != CHAN_OUTPUT_CLOSED)
2304 chan_write_failed(ssh, c);
2308 session_close(struct ssh *ssh, Session *s)
2312 verbose("Close session: user %s from %.200s port %d id %d",
2314 ssh_remote_ipaddr(ssh),
2315 ssh_remote_port(ssh),
2319 session_pty_cleanup(s);
2322 free(s->x11_chanids);
2323 free(s->auth_display);
2325 free(s->auth_proto);
2327 if (s->env != NULL) {
2328 for (i = 0; i < s->num_env; i++) {
2329 free(s->env[i].name);
2330 free(s->env[i].val);
2334 session_proctitle(s);
2335 session_unused(s->self);
2339 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2341 Session *s = session_by_pid(pid);
2343 debug("%s: no session for pid %ld", __func__, (long)pid);
2346 if (s->chanid != -1)
2347 session_exit_message(ssh, s, status);
2349 session_pty_cleanup(s);
2354 * this is called when a channel dies before
2355 * the session 'child' itself dies
2358 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2360 Session *s = session_by_channel(id);
2364 debug("%s: no session for id %d", __func__, id);
2367 debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
2369 debug("%s: channel %d: has child", __func__, id);
2371 * delay detach of session, but release pty, since
2372 * the fd's to the child are already closed
2375 session_pty_cleanup(s);
2378 /* detach by removing callback */
2379 channel_cancel_cleanup(ssh, s->chanid);
2381 /* Close any X11 listeners associated with this session */
2382 if (s->x11_chanids != NULL) {
2383 for (i = 0; s->x11_chanids[i] != -1; i++) {
2384 session_close_x11(ssh, s->x11_chanids[i]);
2385 s->x11_chanids[i] = -1;
2390 session_close(ssh, s);
2394 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2397 for (i = 0; i < sessions_nalloc; i++) {
2398 Session *s = &sessions[i];
2400 if (closefunc != NULL)
2403 session_close(ssh, s);
2409 session_tty_list(void)
2411 static char buf[1024];
2416 for (i = 0; i < sessions_nalloc; i++) {
2417 Session *s = &sessions[i];
2418 if (s->used && s->ttyfd != -1) {
2420 if (strncmp(s->tty, "/dev/", 5) != 0) {
2421 cp = strrchr(s->tty, '/');
2422 cp = (cp == NULL) ? s->tty : cp + 1;
2427 strlcat(buf, ",", sizeof buf);
2428 strlcat(buf, cp, sizeof buf);
2432 strlcpy(buf, "notty", sizeof buf);
2437 session_proctitle(Session *s)
2440 error("no user for session %d", s->self);
2442 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2446 session_setup_x11fwd(struct ssh *ssh, Session *s)
2449 char display[512], auth_display[512];
2450 char hostname[NI_MAXHOST];
2453 if (!auth_opts->permit_x11_forwarding_flag) {
2454 packet_send_debug("X11 forwarding disabled by key options.");
2457 if (!options.x11_forwarding) {
2458 debug("X11 forwarding disabled in server configuration file.");
2461 if (options.xauth_location == NULL ||
2462 (stat(options.xauth_location, &st) == -1)) {
2463 packet_send_debug("No xauth program; cannot forward X11.");
2466 if (s->display != NULL) {
2467 debug("X11 display already set.");
2470 if (x11_create_display_inet(ssh, options.x11_display_offset,
2471 options.x11_use_localhost, s->single_connection,
2472 &s->display_number, &s->x11_chanids) == -1) {
2473 debug("x11_create_display_inet failed.");
2476 for (i = 0; s->x11_chanids[i] != -1; i++) {
2477 channel_register_cleanup(ssh, s->x11_chanids[i],
2478 session_close_single_x11, 0);
2481 /* Set up a suitable value for the DISPLAY variable. */
2482 if (gethostname(hostname, sizeof(hostname)) < 0)
2483 fatal("gethostname: %.100s", strerror(errno));
2485 * auth_display must be used as the displayname when the
2486 * authorization entry is added with xauth(1). This will be
2487 * different than the DISPLAY string for localhost displays.
2489 if (options.x11_use_localhost) {
2490 snprintf(display, sizeof display, "localhost:%u.%u",
2491 s->display_number, s->screen);
2492 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2493 s->display_number, s->screen);
2494 s->display = xstrdup(display);
2495 s->auth_display = xstrdup(auth_display);
2497 #ifdef IPADDR_IN_DISPLAY
2499 struct in_addr my_addr;
2501 he = gethostbyname(hostname);
2503 error("Can't get IP address for X11 DISPLAY.");
2504 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2507 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2508 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2509 s->display_number, s->screen);
2511 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2512 s->display_number, s->screen);
2514 s->display = xstrdup(display);
2515 s->auth_display = xstrdup(display);
2522 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2524 server_loop2(ssh, authctxt);
2528 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2530 static int called = 0;
2532 debug("do_cleanup");
2534 /* no cleanup if we're in the child for login shell */
2538 /* avoid double cleanup */
2543 if (authctxt == NULL)
2547 if (options.use_pam) {
2549 sshpam_thread_cleanup();
2553 if (!authctxt->authenticated)
2557 if (options.kerberos_ticket_cleanup &&
2559 krb5_cleanup_proc(authctxt);
2563 if (options.gss_cleanup_creds)
2564 ssh_gssapi_cleanup_creds();
2567 /* remove agent socket */
2568 auth_sock_cleanup_proc(authctxt->pw);
2570 /* remove userauth info */
2571 if (auth_info_file != NULL) {
2572 temporarily_use_uid(authctxt->pw);
2573 unlink(auth_info_file);
2575 free(auth_info_file);
2576 auth_info_file = NULL;
2580 * Cleanup ptys/utmp only if privsep is disabled,
2581 * or if running in monitor.
2583 if (!use_privsep || mm_is_monitor())
2584 session_destroy_all(ssh, session_pty_cleanup2);
2587 /* Return a name for the remote host that fits inside utmp_size */
2590 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2592 const char *remote = "";
2595 remote = auth_get_canonical_hostname(ssh, use_dns);
2596 if (utmp_size == 0 || strlen(remote) > utmp_size)
2597 remote = ssh_remote_ipaddr(ssh);