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.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
43 #include <sys/socket.h>
47 #include <arpa/inet.h>
66 #include "openbsd-compat/sys-queue.h"
84 #include "auth-options.h"
86 #include "pathnames.h"
91 #include "serverloop.h"
95 #include "monitor_wrap.h"
99 #if defined(KRB5) && defined(USE_AFS)
104 #include <selinux/selinux.h>
107 #define IS_INTERNAL_SFTP(c) \
108 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
109 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
110 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
111 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
115 Session *session_new(void);
116 void session_set_fds(struct ssh *, Session *, int, int, int, int, int);
117 void session_pty_cleanup(Session *);
118 void session_proctitle(Session *);
119 int session_setup_x11fwd(struct ssh *, Session *);
120 int do_exec_pty(struct ssh *, Session *, const char *);
121 int do_exec_no_pty(struct ssh *, Session *, const char *);
122 int do_exec(struct ssh *, Session *, const char *);
123 void do_login(struct ssh *, Session *, const char *);
124 void do_child(struct ssh *, Session *, const char *);
125 #ifdef LOGIN_NEEDS_UTMPX
126 static void do_pre_login(Session *s);
129 int check_quietlogin(Session *, const char *);
131 static void do_authenticated2(struct ssh *, Authctxt *);
133 static int session_pty_req(struct ssh *, Session *);
136 extern ServerOptions options;
137 extern char *__progname;
138 extern int debug_flag;
139 extern u_int utmp_len;
140 extern int startup_pipe;
141 extern void destroy_sensitive_data(void);
142 extern Buffer loginmsg;
144 /* original command from peer. */
145 const char *original_command = NULL;
148 static int sessions_first_unused = -1;
149 static int sessions_nalloc = 0;
150 static Session *sessions = NULL;
152 #define SUBSYSTEM_NONE 0
153 #define SUBSYSTEM_EXT 1
154 #define SUBSYSTEM_INT_SFTP 2
155 #define SUBSYSTEM_INT_SFTP_ERROR 3
157 #ifdef HAVE_LOGIN_CAP
161 static int is_child = 0;
162 static int in_chroot = 0;
164 /* File containing userauth info, if ExposeAuthInfo set */
165 static char *auth_info_file = NULL;
167 /* Name and directory of socket for authentication agent forwarding. */
168 static char *auth_sock_name = NULL;
169 static char *auth_sock_dir = NULL;
171 /* removes the agent forwarding socket */
174 auth_sock_cleanup_proc(struct passwd *pw)
176 if (auth_sock_name != NULL) {
177 temporarily_use_uid(pw);
178 unlink(auth_sock_name);
179 rmdir(auth_sock_dir);
180 auth_sock_name = NULL;
186 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
191 if (auth_sock_name != NULL) {
192 error("authentication forwarding requested twice.");
196 /* Temporarily drop privileged uid for mkdir/bind. */
197 temporarily_use_uid(pw);
199 /* Allocate a buffer for the socket name, and format the name. */
200 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
202 /* Create private directory for socket */
203 if (mkdtemp(auth_sock_dir) == NULL) {
204 packet_send_debug("Agent forwarding disabled: "
205 "mkdtemp() failed: %.100s", strerror(errno));
208 auth_sock_dir = NULL;
212 xasprintf(&auth_sock_name, "%s/agent.%ld",
213 auth_sock_dir, (long) getpid());
215 /* Start a Unix listener on auth_sock_name. */
216 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
218 /* Restore the privileged uid. */
221 /* Check for socket/bind/listen failure. */
225 /* Allocate a channel for the authentication agent socket. */
226 nc = channel_new(ssh, "auth socket",
227 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
228 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
229 0, "auth socket", 1);
230 nc->path = xstrdup(auth_sock_name);
234 free(auth_sock_name);
235 if (auth_sock_dir != NULL) {
236 rmdir(auth_sock_dir);
241 auth_sock_name = NULL;
242 auth_sock_dir = NULL;
247 display_loginmsg(void)
249 if (buffer_len(&loginmsg) > 0) {
250 buffer_append(&loginmsg, "\0", 1);
251 printf("%s", (char *)buffer_ptr(&loginmsg));
252 buffer_clear(&loginmsg);
257 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
259 int fd = -1, success = 0;
261 if (!options.expose_userauth_info || info == NULL)
264 temporarily_use_uid(pw);
265 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
266 if ((fd = mkstemp(auth_info_file)) == -1) {
267 error("%s: mkstemp: %s", __func__, strerror(errno));
270 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
271 sshbuf_len(info)) != sshbuf_len(info)) {
272 error("%s: write: %s", __func__, strerror(errno));
275 if (close(fd) != 0) {
276 error("%s: close: %s", __func__, strerror(errno));
284 free(auth_info_file);
285 auth_info_file = NULL;
291 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
293 setproctitle("%s", authctxt->pw->pw_name);
295 /* setup the channel layer */
296 /* XXX - streamlocal? */
297 if (no_port_forwarding_flag || options.disable_forwarding ||
298 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
299 channel_disable_adm_local_opens(ssh);
301 channel_permit_all_opens(ssh);
305 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
307 do_authenticated2(ssh, authctxt);
309 do_cleanup(ssh, authctxt);
312 /* Check untrusted xauth strings for metacharacters */
314 xauth_valid_string(const char *s)
318 for (i = 0; s[i] != '\0'; i++) {
319 if (!isalnum((u_char)s[i]) &&
320 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
321 s[i] != '-' && s[i] != '_')
329 * This is called to fork and execute a command when we have no tty. This
330 * will call do_child from the child, and server_loop from the parent after
331 * setting up file descriptors and such.
334 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
339 int pin[2], pout[2], perr[2];
342 fatal("do_exec_no_pty: no session");
344 /* Allocate pipes for communicating with the program. */
346 error("%s: pipe in: %.100s", __func__, strerror(errno));
349 if (pipe(pout) < 0) {
350 error("%s: pipe out: %.100s", __func__, strerror(errno));
355 if (pipe(perr) < 0) {
356 error("%s: pipe err: %.100s", __func__,
365 int inout[2], err[2];
368 fatal("do_exec_no_pty: no session");
370 /* Uses socket pairs to communicate with the program. */
371 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
372 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
375 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
376 error("%s: socketpair #2: %.100s", __func__,
384 session_proctitle(s);
386 /* Fork the child. */
387 switch ((pid = fork())) {
389 error("%s: fork: %.100s", __func__, strerror(errno));
408 * Create a new session and process group since the 4.4BSD
409 * setlogin() affects the entire process group.
412 error("setsid failed: %.100s", strerror(errno));
416 * Redirect stdin. We close the parent side of the socket
417 * pair, and make the child side the standard input.
420 if (dup2(pin[0], 0) < 0)
421 perror("dup2 stdin");
424 /* Redirect stdout. */
426 if (dup2(pout[1], 1) < 0)
427 perror("dup2 stdout");
430 /* Redirect stderr. */
432 if (dup2(perr[1], 2) < 0)
433 perror("dup2 stderr");
437 * Redirect stdin, stdout, and stderr. Stdin and stdout will
438 * use the same socket, as some programs (particularly rdist)
439 * seem to depend on it.
443 if (dup2(inout[0], 0) < 0) /* stdin */
444 perror("dup2 stdin");
445 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
446 perror("dup2 stdout");
448 if (dup2(err[0], 2) < 0) /* stderr */
449 perror("dup2 stderr");
455 cray_init_job(s->pw); /* set up cray jid and tmpdir */
458 /* Do processing for the child (exec command etc). */
459 do_child(ssh, s, command);
466 signal(WJSIGNAL, cray_job_termination_handler);
469 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
473 /* Set interactive/non-interactive mode. */
474 packet_set_interactive(s->display != NULL,
475 options.ip_qos_interactive, options.ip_qos_bulk);
478 * Clear loginmsg, since it's the child's responsibility to display
479 * it to the user, otherwise multiple sessions may accumulate
480 * multiple copies of the login messages.
482 buffer_clear(&loginmsg);
485 /* We are the parent. Close the child sides of the pipes. */
490 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
493 /* We are the parent. Close the child sides of the socket pairs. */
498 * Enter the interactive session. Note: server_loop must be able to
499 * handle the case that fdin and fdout are the same.
501 session_set_fds(s, inout[1], inout[1], err[1],
508 * This is called to fork and execute a command when we have a tty. This
509 * will call do_child from the child, and server_loop from the parent after
510 * setting up file descriptors, controlling tty, updating wtmp, utmp,
511 * lastlog, and other such operations.
514 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
516 int fdout, ptyfd, ttyfd, ptymaster;
520 fatal("do_exec_pty: no session");
525 * Create another descriptor of the pty master side for use as the
526 * standard input. We could use the original descriptor, but this
527 * simplifies code in server_loop. The descriptor is bidirectional.
528 * Do this before forking (and cleanup in the child) so as to
529 * detect and gracefully fail out-of-fd conditions.
531 if ((fdout = dup(ptyfd)) < 0) {
532 error("%s: dup #1: %s", __func__, strerror(errno));
537 /* we keep a reference to the pty master */
538 if ((ptymaster = dup(ptyfd)) < 0) {
539 error("%s: dup #2: %s", __func__, strerror(errno));
546 /* Fork the child. */
547 switch ((pid = fork())) {
549 error("%s: fork: %.100s", __func__, strerror(errno));
561 /* Close the master side of the pseudo tty. */
564 /* Make the pseudo tty our controlling tty. */
565 pty_make_controlling_tty(&ttyfd, s->tty);
567 /* Redirect stdin/stdout/stderr from the pseudo tty. */
568 if (dup2(ttyfd, 0) < 0)
569 error("dup2 stdin: %s", strerror(errno));
570 if (dup2(ttyfd, 1) < 0)
571 error("dup2 stdout: %s", strerror(errno));
572 if (dup2(ttyfd, 2) < 0)
573 error("dup2 stderr: %s", strerror(errno));
575 /* Close the extra descriptor for the pseudo tty. */
578 /* record login, etc. similar to login(1) */
580 cray_init_job(s->pw); /* set up cray jid and tmpdir */
583 do_login(ssh, s, command);
586 * Do common processing for the child, such as execing
589 do_child(ssh, s, command);
596 signal(WJSIGNAL, cray_job_termination_handler);
599 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
604 /* Parent. Close the slave side of the pseudo tty. */
607 /* Enter interactive session. */
608 s->ptymaster = ptymaster;
609 packet_set_interactive(1,
610 options.ip_qos_interactive, options.ip_qos_bulk);
611 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
615 #ifdef LOGIN_NEEDS_UTMPX
617 do_pre_login(Session *s)
619 struct ssh *ssh = active_state; /* XXX */
621 struct sockaddr_storage from;
622 pid_t pid = getpid();
625 * Get IP address of client. If the connection is not a socket, let
626 * the address be 0.0.0.0.
628 memset(&from, 0, sizeof(from));
629 fromlen = sizeof(from);
630 if (packet_connection_is_on_socket()) {
631 if (getpeername(packet_get_connection_in(),
632 (struct sockaddr *)&from, &fromlen) < 0) {
633 debug("getpeername: %.100s", strerror(errno));
638 record_utmp_only(pid, s->tty, s->pw->pw_name,
639 session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
640 (struct sockaddr *)&from, fromlen);
645 * This is called to fork and execute a command. If another command is
646 * to be forced, execute that instead.
649 do_exec(struct ssh *ssh, Session *s, const char *command)
652 const char *forced = NULL, *tty = NULL;
653 char session_type[1024];
655 if (options.adm_forced_command) {
656 original_command = command;
657 command = options.adm_forced_command;
659 } else if (forced_command) {
660 original_command = command;
661 command = forced_command;
662 forced = "(key-option)";
664 if (forced != NULL) {
665 if (IS_INTERNAL_SFTP(command)) {
666 s->is_subsystem = s->is_subsystem ?
667 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
668 } else if (s->is_subsystem)
669 s->is_subsystem = SUBSYSTEM_EXT;
670 snprintf(session_type, sizeof(session_type),
671 "forced-command %s '%.900s'", forced, command);
672 } else if (s->is_subsystem) {
673 snprintf(session_type, sizeof(session_type),
674 "subsystem '%.900s'", s->subsys);
675 } else if (command == NULL) {
676 snprintf(session_type, sizeof(session_type), "shell");
678 /* NB. we don't log unforced commands to preserve privacy */
679 snprintf(session_type, sizeof(session_type), "command");
682 if (s->ttyfd != -1) {
684 if (strncmp(tty, "/dev/", 5) == 0)
688 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
690 tty == NULL ? "" : " on ",
691 tty == NULL ? "" : tty,
693 ssh_remote_ipaddr(ssh),
694 ssh_remote_port(ssh),
697 #ifdef SSH_AUDIT_EVENTS
699 PRIVSEP(audit_run_command(command));
700 else if (s->ttyfd == -1) {
701 char *shell = s->pw->pw_shell;
703 if (shell[0] == '\0') /* empty shell means /bin/sh */
705 PRIVSEP(audit_run_command(shell));
709 ret = do_exec_pty(ssh, s, command);
711 ret = do_exec_no_pty(ssh, s, command);
713 original_command = NULL;
716 * Clear loginmsg: it's the child's responsibility to display
717 * it to the user, otherwise multiple sessions may accumulate
718 * multiple copies of the login messages.
720 buffer_clear(&loginmsg);
725 /* administrative, login(1)-like work */
727 do_login(struct ssh *ssh, Session *s, const char *command)
730 struct sockaddr_storage from;
731 struct passwd * pw = s->pw;
732 pid_t pid = getpid();
735 * Get IP address of client. If the connection is not a socket, let
736 * the address be 0.0.0.0.
738 memset(&from, 0, sizeof(from));
739 fromlen = sizeof(from);
740 if (packet_connection_is_on_socket()) {
741 if (getpeername(packet_get_connection_in(),
742 (struct sockaddr *)&from, &fromlen) < 0) {
743 debug("getpeername: %.100s", strerror(errno));
748 /* Record that there was a login on that tty from the remote host. */
750 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
751 session_get_remote_name_or_ip(ssh, utmp_len,
753 (struct sockaddr *)&from, fromlen);
757 * If password change is needed, do it now.
758 * This needs to occur before the ~/.hushlogin check.
760 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
763 s->authctxt->force_pwchange = 0;
764 /* XXX - signal [net] parent to enable forwardings */
768 if (check_quietlogin(s, command))
777 * Display the message of the day.
785 if (options.print_motd) {
786 #ifdef HAVE_LOGIN_CAP
787 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
790 f = fopen("/etc/motd", "r");
793 while (fgets(buf, sizeof(buf), f))
802 * Check for quiet login, either .hushlogin or command given.
805 check_quietlogin(Session *s, const char *command)
808 struct passwd *pw = s->pw;
811 /* Return 1 if .hushlogin exists or a command given. */
814 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
815 #ifdef HAVE_LOGIN_CAP
816 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
819 if (stat(buf, &st) >= 0)
826 * Reads environment variables from the given file and adds/overrides them
827 * into the environment. If the file does not exist, this does nothing.
828 * Otherwise, it must consist of empty lines, comments (line starts with '#')
829 * and assignments of the form name=value. No other forms are allowed.
832 read_environment_file(char ***env, u_int *envsize,
833 const char *filename)
840 f = fopen(filename, "r");
844 while (fgets(buf, sizeof(buf), f)) {
846 fatal("Too many lines in environment file %s", filename);
847 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
849 if (!*cp || *cp == '#' || *cp == '\n')
852 cp[strcspn(cp, "\n")] = '\0';
854 value = strchr(cp, '=');
856 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
861 * Replace the equals sign by nul, and advance value to
866 child_set_env(env, envsize, cp, value);
871 #ifdef HAVE_ETC_DEFAULT_LOGIN
873 * Return named variable from specified environment, or NULL if not present.
876 child_get_env(char **env, const char *name)
882 for (i=0; env[i] != NULL; i++)
883 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
884 return(env[i] + len + 1);
889 * Read /etc/default/login.
890 * We pick up the PATH (or SUPATH for root) and UMASK.
893 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
895 char **tmpenv = NULL, *var;
896 u_int i, tmpenvsize = 0;
900 * We don't want to copy the whole file to the child's environment,
901 * so we use a temporary environment and copy the variables we're
904 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
910 var = child_get_env(tmpenv, "SUPATH");
912 var = child_get_env(tmpenv, "PATH");
914 child_set_env(env, envsize, "PATH", var);
916 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
917 if (sscanf(var, "%5lo", &mask) == 1)
920 for (i = 0; tmpenv[i] != NULL; i++)
924 #endif /* HAVE_ETC_DEFAULT_LOGIN */
927 copy_environment_blacklist(char **source, char ***env, u_int *envsize,
928 const char *blacklist)
930 char *var_name, *var_val;
936 for(i = 0; source[i] != NULL; i++) {
937 var_name = xstrdup(source[i]);
938 if ((var_val = strstr(var_name, "=")) == NULL) {
944 if (blacklist == NULL ||
945 match_pattern_list(var_name, blacklist, 0) != 1) {
946 debug3("Copy environment: %s=%s", var_name, var_val);
947 child_set_env(env, envsize, var_name, var_val);
955 copy_environment(char **source, char ***env, u_int *envsize)
957 copy_environment_blacklist(source, env, envsize, NULL);
961 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
966 struct passwd *pw = s->pw;
967 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
971 /* Initialize the environment. */
973 env = xcalloc(envsize, sizeof(char *));
978 * The Windows environment contains some setting which are
979 * important for a running system. They must not be dropped.
984 p = fetch_windows_environment();
985 copy_environment(p, &env, &envsize);
986 free_windows_environment(p);
991 /* Allow any GSSAPI methods that we've used to alter
992 * the childs environment as they see fit
994 ssh_gssapi_do_child(&env, &envsize);
997 /* Set basic environment. */
998 for (i = 0; i < s->num_env; i++)
999 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1001 child_set_env(&env, &envsize, "USER", pw->pw_name);
1002 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1004 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1006 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1007 #ifdef HAVE_LOGIN_CAP
1008 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1009 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1011 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1012 #else /* HAVE_LOGIN_CAP */
1013 # ifndef HAVE_CYGWIN
1015 * There's no standard path on Windows. The path contains
1016 * important components pointing to the system directories,
1017 * needed for loading shared libraries. So the path better
1018 * remains intact here.
1020 # ifdef HAVE_ETC_DEFAULT_LOGIN
1021 read_etc_default_login(&env, &envsize, pw->pw_uid);
1022 path = child_get_env(env, "PATH");
1023 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1024 if (path == NULL || *path == '\0') {
1025 child_set_env(&env, &envsize, "PATH",
1026 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1028 # endif /* HAVE_CYGWIN */
1029 #endif /* HAVE_LOGIN_CAP */
1031 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1032 child_set_env(&env, &envsize, "MAIL", buf);
1034 /* Normal systems set SHELL by default. */
1035 child_set_env(&env, &envsize, "SHELL", shell);
1038 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1040 /* Set custom environment options from RSA authentication. */
1041 while (custom_environment) {
1042 struct envstring *ce = custom_environment;
1045 for (i = 0; str[i] != '=' && str[i]; i++)
1047 if (str[i] == '=') {
1049 child_set_env(&env, &envsize, str, str + i + 1);
1051 custom_environment = ce->next;
1056 /* SSH_CLIENT deprecated */
1057 snprintf(buf, sizeof buf, "%.50s %d %d",
1058 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1059 ssh_local_port(ssh));
1060 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1062 laddr = get_local_ipaddr(packet_get_connection_in());
1063 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1064 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1065 laddr, ssh_local_port(ssh));
1067 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1069 if (auth_info_file != NULL)
1070 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1072 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1074 child_set_env(&env, &envsize, "TERM", s->term);
1076 child_set_env(&env, &envsize, "DISPLAY", s->display);
1077 if (original_command)
1078 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1082 if (cray_tmpdir[0] != '\0')
1083 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1084 #endif /* _UNICOS */
1087 * Since we clear KRB5CCNAME at startup, if it's set now then it
1088 * must have been set by a native authentication method (eg AIX or
1089 * SIA), so copy it to the child.
1094 if ((cp = getenv("KRB5CCNAME")) != NULL)
1095 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1102 if ((cp = getenv("AUTHSTATE")) != NULL)
1103 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1104 read_environment_file(&env, &envsize, "/etc/environment");
1108 if (s->authctxt->krb5_ccname)
1109 child_set_env(&env, &envsize, "KRB5CCNAME",
1110 s->authctxt->krb5_ccname);
1114 * Pull in any environment variables that may have
1117 if (options.use_pam) {
1121 * Don't allow SSH_AUTH_INFO variables posted to PAM to leak
1122 * back into the environment.
1124 p = fetch_pam_child_environment();
1125 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1126 free_pam_environment(p);
1128 p = fetch_pam_environment();
1129 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1130 free_pam_environment(p);
1132 #endif /* USE_PAM */
1134 if (auth_sock_name != NULL)
1135 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1138 /* read $HOME/.ssh/environment. */
1139 if (options.permit_user_env) {
1140 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1141 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1142 read_environment_file(&env, &envsize, buf);
1145 /* dump the environment */
1146 fprintf(stderr, "Environment:\n");
1147 for (i = 0; env[i]; i++)
1148 fprintf(stderr, " %.200s\n", env[i]);
1154 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1155 * first in this order).
1158 do_rc_files(Session *s, const char *shell)
1166 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1168 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1169 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1170 !no_user_rc && options.permit_user_rc &&
1171 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1172 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1173 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1175 fprintf(stderr, "Running %s\n", cmd);
1176 f = popen(cmd, "w");
1179 fprintf(f, "%s %s\n", s->auth_proto,
1183 fprintf(stderr, "Could not run %s\n",
1185 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1187 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1188 _PATH_SSH_SYSTEM_RC);
1189 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1192 fprintf(f, "%s %s\n", s->auth_proto,
1196 fprintf(stderr, "Could not run %s\n",
1197 _PATH_SSH_SYSTEM_RC);
1198 } else if (do_xauth && options.xauth_location != NULL) {
1199 /* Add authority data to .Xauthority if appropriate. */
1202 "Running %.500s remove %.100s\n",
1203 options.xauth_location, s->auth_display);
1205 "%.500s add %.100s %.100s %.100s\n",
1206 options.xauth_location, s->auth_display,
1207 s->auth_proto, s->auth_data);
1209 snprintf(cmd, sizeof cmd, "%s -q -",
1210 options.xauth_location);
1211 f = popen(cmd, "w");
1213 fprintf(f, "remove %s\n",
1215 fprintf(f, "add %s %s %s\n",
1216 s->auth_display, s->auth_proto,
1220 fprintf(stderr, "Could not run %s\n",
1227 do_nologin(struct passwd *pw)
1230 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1233 #ifdef HAVE_LOGIN_CAP
1234 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1236 nl = strdup(login_getcapstr(lc, "nologin", def_nl, def_nl));
1238 if (pw->pw_uid == 0)
1242 if (stat(nl, &sb) == -1) {
1248 /* /etc/nologin exists. Print its contents if we can and exit. */
1249 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1250 if ((f = fopen(nl, "r")) != NULL) {
1251 while (fgets(buf, sizeof(buf), f))
1259 * Chroot into a directory after checking it for safety: all path components
1260 * must be root-owned directories with strict permissions.
1263 safely_chroot(const char *path, uid_t uid)
1266 char component[PATH_MAX];
1270 fatal("chroot path does not begin at root");
1271 if (strlen(path) >= sizeof(component))
1272 fatal("chroot path too long");
1275 * Descend the path, checking that each component is a
1276 * root-owned directory with strict permissions.
1278 for (cp = path; cp != NULL;) {
1279 if ((cp = strchr(cp, '/')) == NULL)
1280 strlcpy(component, path, sizeof(component));
1283 memcpy(component, path, cp - path);
1284 component[cp - path] = '\0';
1287 debug3("%s: checking '%s'", __func__, component);
1289 if (stat(component, &st) != 0)
1290 fatal("%s: stat(\"%s\"): %s", __func__,
1291 component, strerror(errno));
1292 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1293 fatal("bad ownership or modes for chroot "
1294 "directory %s\"%s\"",
1295 cp == NULL ? "" : "component ", component);
1296 if (!S_ISDIR(st.st_mode))
1297 fatal("chroot path %s\"%s\" is not a directory",
1298 cp == NULL ? "" : "component ", component);
1302 if (chdir(path) == -1)
1303 fatal("Unable to chdir to chroot path \"%s\": "
1304 "%s", path, strerror(errno));
1305 if (chroot(path) == -1)
1306 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1307 if (chdir("/") == -1)
1308 fatal("%s: chdir(/) after chroot: %s",
1309 __func__, strerror(errno));
1310 verbose("Changed root directory to \"%s\"", path);
1313 /* Set login name, uid, gid, and groups. */
1315 do_setusercontext(struct passwd *pw)
1317 char *chroot_path, *tmp;
1319 platform_setusercontext(pw);
1321 if (platform_privileged_uidswap()) {
1322 #ifdef HAVE_LOGIN_CAP
1323 if (setusercontext(lc, pw, pw->pw_uid,
1324 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1325 perror("unable to set user context");
1329 if (setlogin(pw->pw_name) < 0)
1330 error("setlogin failed: %s", strerror(errno));
1331 if (setgid(pw->pw_gid) < 0) {
1335 /* Initialize the group list. */
1336 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1337 perror("initgroups");
1343 platform_setusercontext_post_groups(pw);
1345 if (!in_chroot && options.chroot_directory != NULL &&
1346 strcasecmp(options.chroot_directory, "none") != 0) {
1347 tmp = tilde_expand_filename(options.chroot_directory,
1349 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1350 "u", pw->pw_name, (char *)NULL);
1351 safely_chroot(chroot_path, pw->pw_uid);
1354 /* Make sure we don't attempt to chroot again */
1355 free(options.chroot_directory);
1356 options.chroot_directory = NULL;
1360 #ifdef HAVE_LOGIN_CAP
1361 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1362 perror("unable to set user context (setuser)");
1366 * FreeBSD's setusercontext() will not apply the user's
1367 * own umask setting unless running with the user's UID.
1369 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1373 * In a chroot environment, the set_id() will always fail;
1374 * typically because of the lack of necessary authentication
1375 * services and runtime such as ./usr/lib/libiaf.so,
1376 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1377 * internal sftp chroot case. We'll lose auditing and ACLs but
1378 * permanently_set_uid will take care of the rest.
1380 if (!in_chroot && set_id(pw->pw_name) != 0)
1381 fatal("set_id(%s) Failed", pw->pw_name);
1382 # endif /* USE_LIBIAF */
1383 /* Permanently switch to the desired uid. */
1384 permanently_set_uid(pw);
1386 } else if (options.chroot_directory != NULL &&
1387 strcasecmp(options.chroot_directory, "none") != 0) {
1388 fatal("server lacks privileges to chroot to ChrootDirectory");
1391 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1392 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1396 do_pwchange(Session *s)
1399 fprintf(stderr, "WARNING: Your password has expired.\n");
1400 if (s->ttyfd != -1) {
1402 "You must change your password now and login again!\n");
1406 #ifdef PASSWD_NEEDS_USERNAME
1407 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1410 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1415 "Password change required but no TTY available.\n");
1421 child_close_fds(struct ssh *ssh)
1423 extern int auth_sock;
1425 if (auth_sock != -1) {
1430 if (packet_get_connection_in() == packet_get_connection_out())
1431 close(packet_get_connection_in());
1433 close(packet_get_connection_in());
1434 close(packet_get_connection_out());
1437 * Close all descriptors related to channels. They will still remain
1438 * open in the parent.
1440 /* XXX better use close-on-exec? -markus */
1441 channel_close_all(ssh);
1444 * Close any extra file descriptors. Note that there may still be
1445 * descriptors left by system functions. They will be closed later.
1450 * Close any extra open file descriptors so that we don't have them
1451 * hanging around in clients. Note that we want to do this after
1452 * initgroups, because at least on Solaris 2.3 it leaves file
1455 closefrom(STDERR_FILENO + 1);
1459 * Performs common processing for the child, such as setting up the
1460 * environment, closing extra file descriptors, setting the user and group
1461 * ids, and executing the command or shell.
1465 do_child(struct ssh *ssh, Session *s, const char *command)
1467 extern char **environ;
1469 char *argv[ARGV_MAX];
1470 const char *shell, *shell0;
1471 struct passwd *pw = s->pw;
1474 /* remove hostkey from the child's memory */
1475 destroy_sensitive_data();
1476 packet_clear_keys();
1478 /* Force a password change */
1479 if (s->authctxt->force_pwchange) {
1480 do_setusercontext(pw);
1481 child_close_fds(ssh);
1487 cray_setup(pw->pw_uid, pw->pw_name, command);
1488 #endif /* _UNICOS */
1491 * Login(1) does this as well, and it needs uid 0 for the "-h"
1492 * switch, so we let login(1) to this for us.
1495 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1496 if (!check_quietlogin(s, command))
1498 #else /* HAVE_OSF_SIA */
1499 /* When PAM is enabled we rely on it to do the nologin check */
1500 if (!options.use_pam)
1502 do_setusercontext(pw);
1504 * PAM session modules in do_setusercontext may have
1505 * generated messages, so if this in an interactive
1506 * login then display them too.
1508 if (!check_quietlogin(s, command))
1510 #endif /* HAVE_OSF_SIA */
1513 if (options.use_pam && !is_pam_session_open()) {
1514 debug3("PAM session not opened, exiting");
1521 * Get the shell from the password data. An empty shell field is
1522 * legal, and means /bin/sh.
1524 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1527 * Make sure $SHELL points to the shell from the password file,
1528 * even if shell is overridden from login.conf
1530 env = do_setup_env(ssh, s, shell);
1532 #ifdef HAVE_LOGIN_CAP
1533 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1537 * Close the connection descriptors; note that this is the child, and
1538 * the server will still have the socket open, and it is important
1539 * that we do not shutdown it. Note that the descriptors cannot be
1540 * closed before building the environment, as we call
1541 * ssh_remote_ipaddr there.
1543 child_close_fds(ssh);
1546 * Must take new environment into use so that .ssh/rc,
1547 * /etc/ssh/sshrc and xauth are run in the proper environment.
1551 #if defined(KRB5) && defined(USE_AFS)
1553 * At this point, we check to see if AFS is active and if we have
1554 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1555 * if we can (and need to) extend the ticket into an AFS token. If
1556 * we don't do this, we run into potential problems if the user's
1557 * home directory is in AFS and it's not world-readable.
1560 if (options.kerberos_get_afs_token && k_hasafs() &&
1561 (s->authctxt->krb5_ctx != NULL)) {
1564 debug("Getting AFS token");
1568 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1569 krb5_afslog(s->authctxt->krb5_ctx,
1570 s->authctxt->krb5_fwd_ccache, cell, NULL);
1572 krb5_afslog_home(s->authctxt->krb5_ctx,
1573 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1577 /* Change current directory to the user's home directory. */
1578 if (chdir(pw->pw_dir) < 0) {
1579 /* Suppress missing homedir warning for chroot case */
1580 #ifdef HAVE_LOGIN_CAP
1581 r = login_getcapbool(lc, "requirehome", 0);
1583 if (r || !in_chroot) {
1584 fprintf(stderr, "Could not chdir to home "
1585 "directory %s: %s\n", pw->pw_dir,
1592 closefrom(STDERR_FILENO + 1);
1594 do_rc_files(s, shell);
1596 /* restore SIGPIPE for child */
1597 signal(SIGPIPE, SIG_DFL);
1599 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1600 printf("This service allows sftp connections only.\n");
1603 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1604 extern int optind, optreset;
1608 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1609 args = xstrdup(command ? command : "sftp-server");
1610 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1611 if (i < ARGV_MAX - 1)
1614 optind = optreset = 1;
1615 __progname = argv[0];
1617 ssh_selinux_change_context("sftpd_t");
1619 exit(sftp_server_main(i, argv, s->pw));
1624 /* Get the last component of the shell name. */
1625 if ((shell0 = strrchr(shell, '/')) != NULL)
1631 * If we have no command, execute the shell. In this case, the shell
1632 * name to be passed in argv[0] is preceded by '-' to indicate that
1633 * this is a login shell.
1638 /* Start the shell. Set initial character to '-'. */
1641 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1642 >= sizeof(argv0) - 1) {
1648 /* Execute the shell. */
1651 execve(shell, argv, env);
1653 /* Executing the shell failed. */
1658 * Execute the command using the user's shell. This uses the -c
1659 * option to execute the command.
1661 argv[0] = (char *) shell0;
1663 argv[2] = (char *) command;
1665 execve(shell, argv, env);
1671 session_unused(int id)
1673 debug3("%s: session id %d unused", __func__, id);
1674 if (id >= options.max_sessions ||
1675 id >= sessions_nalloc) {
1676 fatal("%s: insane session id %d (max %d nalloc %d)",
1677 __func__, id, options.max_sessions, sessions_nalloc);
1679 memset(&sessions[id], 0, sizeof(*sessions));
1680 sessions[id].self = id;
1681 sessions[id].used = 0;
1682 sessions[id].chanid = -1;
1683 sessions[id].ptyfd = -1;
1684 sessions[id].ttyfd = -1;
1685 sessions[id].ptymaster = -1;
1686 sessions[id].x11_chanids = NULL;
1687 sessions[id].next_unused = sessions_first_unused;
1688 sessions_first_unused = id;
1696 if (sessions_first_unused == -1) {
1697 if (sessions_nalloc >= options.max_sessions)
1699 debug2("%s: allocate (allocated %d max %d)",
1700 __func__, sessions_nalloc, options.max_sessions);
1701 tmp = xrecallocarray(sessions, sessions_nalloc,
1702 sessions_nalloc + 1, sizeof(*sessions));
1704 error("%s: cannot allocate %d sessions",
1705 __func__, sessions_nalloc + 1);
1709 session_unused(sessions_nalloc++);
1712 if (sessions_first_unused >= sessions_nalloc ||
1713 sessions_first_unused < 0) {
1714 fatal("%s: insane first_unused %d max %d nalloc %d",
1715 __func__, sessions_first_unused, options.max_sessions,
1719 s = &sessions[sessions_first_unused];
1721 fatal("%s: session %d already used",
1722 __func__, sessions_first_unused);
1724 sessions_first_unused = s->next_unused;
1726 s->next_unused = -1;
1727 debug("session_new: session %d", s->self);
1736 for (i = 0; i < sessions_nalloc; i++) {
1737 Session *s = &sessions[i];
1739 debug("dump: used %d next_unused %d session %d %p "
1740 "channel %d pid %ld",
1751 session_open(Authctxt *authctxt, int chanid)
1753 Session *s = session_new();
1754 debug("session_open: channel %d", chanid);
1756 error("no more sessions");
1759 s->authctxt = authctxt;
1760 s->pw = authctxt->pw;
1761 if (s->pw == NULL || !authctxt->valid)
1762 fatal("no user for session %d", s->self);
1763 debug("session_open: session %d: link with channel %d", s->self, chanid);
1769 session_by_tty(char *tty)
1772 for (i = 0; i < sessions_nalloc; i++) {
1773 Session *s = &sessions[i];
1774 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1775 debug("session_by_tty: session %d tty %s", i, tty);
1779 debug("session_by_tty: unknown tty %.100s", tty);
1785 session_by_channel(int id)
1788 for (i = 0; i < sessions_nalloc; i++) {
1789 Session *s = &sessions[i];
1790 if (s->used && s->chanid == id) {
1791 debug("session_by_channel: session %d channel %d",
1796 debug("session_by_channel: unknown channel %d", id);
1802 session_by_x11_channel(int id)
1806 for (i = 0; i < sessions_nalloc; i++) {
1807 Session *s = &sessions[i];
1809 if (s->x11_chanids == NULL || !s->used)
1811 for (j = 0; s->x11_chanids[j] != -1; j++) {
1812 if (s->x11_chanids[j] == id) {
1813 debug("session_by_x11_channel: session %d "
1814 "channel %d", s->self, id);
1819 debug("session_by_x11_channel: unknown channel %d", id);
1825 session_by_pid(pid_t pid)
1828 debug("session_by_pid: pid %ld", (long)pid);
1829 for (i = 0; i < sessions_nalloc; i++) {
1830 Session *s = &sessions[i];
1831 if (s->used && s->pid == pid)
1834 error("session_by_pid: unknown pid %ld", (long)pid);
1840 session_window_change_req(struct ssh *ssh, Session *s)
1842 s->col = packet_get_int();
1843 s->row = packet_get_int();
1844 s->xpixel = packet_get_int();
1845 s->ypixel = packet_get_int();
1847 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1852 session_pty_req(struct ssh *ssh, Session *s)
1857 if (no_pty_flag || !options.permit_tty) {
1858 debug("Allocating a pty not permitted for this authentication.");
1861 if (s->ttyfd != -1) {
1862 packet_disconnect("Protocol error: you already have a pty.");
1866 s->term = packet_get_string(&len);
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 if (strcmp(s->term, "") == 0) {
1877 /* Allocate a pty and open it. */
1878 debug("Allocating pty.");
1879 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1885 error("session_pty_req: session %d alloc failed", s->self);
1888 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1890 n_bytes = packet_remaining();
1891 tty_parse_modes(s->ttyfd, &n_bytes);
1894 pty_setowner(s->pw, s->tty);
1896 /* Set window size from the packet. */
1897 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1900 session_proctitle(s);
1905 session_subsystem_req(struct ssh *ssh, Session *s)
1913 s->subsys = packet_get_string(&len);
1915 debug2("subsystem request for %.100s by user %s", s->subsys,
1918 for (i = 0; i < options.num_subsystems; i++) {
1919 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1920 prog = options.subsystem_command[i];
1921 cmd = options.subsystem_args[i];
1922 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1923 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1924 debug("subsystem: %s", prog);
1926 if (stat(prog, &st) < 0)
1927 debug("subsystem: cannot stat %s: %s",
1928 prog, strerror(errno));
1929 s->is_subsystem = SUBSYSTEM_EXT;
1930 debug("subsystem: exec() %s", cmd);
1932 success = do_exec(ssh, s, cmd) == 0;
1938 logit("subsystem request for %.100s by user %s failed, "
1939 "subsystem not found", s->subsys, s->pw->pw_name);
1945 session_x11_req(struct ssh *ssh, Session *s)
1949 if (s->auth_proto != NULL || s->auth_data != NULL) {
1950 error("session_x11_req: session %d: "
1951 "x11 forwarding already active", s->self);
1954 s->single_connection = packet_get_char();
1955 s->auth_proto = packet_get_string(NULL);
1956 s->auth_data = packet_get_string(NULL);
1957 s->screen = packet_get_int();
1960 if (xauth_valid_string(s->auth_proto) &&
1961 xauth_valid_string(s->auth_data))
1962 success = session_setup_x11fwd(ssh, s);
1965 error("Invalid X11 forwarding data");
1968 free(s->auth_proto);
1970 s->auth_proto = NULL;
1971 s->auth_data = NULL;
1977 session_shell_req(struct ssh *ssh, Session *s)
1980 return do_exec(ssh, s, NULL) == 0;
1984 session_exec_req(struct ssh *ssh, Session *s)
1988 char *command = packet_get_string(&len);
1990 success = do_exec(ssh, s, command) == 0;
1996 session_break_req(struct ssh *ssh, Session *s)
1999 packet_get_int(); /* ignored */
2002 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2008 session_env_req(struct ssh *ssh, Session *s)
2011 u_int name_len, val_len, i;
2013 name = packet_get_cstring(&name_len);
2014 val = packet_get_cstring(&val_len);
2017 /* Don't set too many environment variables */
2018 if (s->num_env > 128) {
2019 debug2("Ignoring env request %s: too many env vars", name);
2023 for (i = 0; i < options.num_accept_env; i++) {
2024 if (match_pattern(name, options.accept_env[i])) {
2025 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2026 s->env = xrecallocarray(s->env, s->num_env,
2027 s->num_env + 1, sizeof(*s->env));
2028 s->env[s->num_env].name = name;
2029 s->env[s->num_env].val = val;
2034 debug2("Ignoring env request %s: disallowed name", name);
2043 session_auth_agent_req(struct ssh *ssh, Session *s)
2045 static int called = 0;
2047 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2048 debug("session_auth_agent_req: no_agent_forwarding_flag");
2055 return auth_input_request_forwarding(ssh, s->pw);
2060 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2065 if ((s = session_by_channel(c->self)) == NULL) {
2066 logit("%s: no session %d req %.100s", __func__, c->self, rtype);
2069 debug("%s: session %d req %s", __func__, s->self, rtype);
2072 * a session is in LARVAL state until a shell, a command
2073 * or a subsystem is executed
2075 if (c->type == SSH_CHANNEL_LARVAL) {
2076 if (strcmp(rtype, "shell") == 0) {
2077 success = session_shell_req(ssh, s);
2078 } else if (strcmp(rtype, "exec") == 0) {
2079 success = session_exec_req(ssh, s);
2080 } else if (strcmp(rtype, "pty-req") == 0) {
2081 success = session_pty_req(ssh, s);
2082 } else if (strcmp(rtype, "x11-req") == 0) {
2083 success = session_x11_req(ssh, s);
2084 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2085 success = session_auth_agent_req(ssh, s);
2086 } else if (strcmp(rtype, "subsystem") == 0) {
2087 success = session_subsystem_req(ssh, s);
2088 } else if (strcmp(rtype, "env") == 0) {
2089 success = session_env_req(ssh, s);
2092 if (strcmp(rtype, "window-change") == 0) {
2093 success = session_window_change_req(ssh, s);
2094 } else if (strcmp(rtype, "break") == 0) {
2095 success = session_break_req(ssh, s);
2102 session_set_fds(struct ssh *ssh, Session *s,
2103 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2106 * now that have a child and a pipe to the child,
2107 * we can activate our channel and register the fd's
2109 if (s->chanid == -1)
2110 fatal("no channel for session %d", s->self);
2111 channel_set_fds(ssh, s->chanid,
2113 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2114 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2118 * Function to perform pty cleanup. Also called if we get aborted abnormally
2119 * (e.g., due to a dropped connection).
2122 session_pty_cleanup2(Session *s)
2125 error("session_pty_cleanup: no session");
2131 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2133 /* Record that the user has logged out. */
2135 record_logout(s->pid, s->tty, s->pw->pw_name);
2137 /* Release the pseudo-tty. */
2139 pty_release(s->tty);
2142 * Close the server side of the socket pairs. We must do this after
2143 * the pty cleanup, so that another process doesn't get this pty
2144 * while we're still cleaning up.
2146 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2147 error("close(s->ptymaster/%d): %s",
2148 s->ptymaster, strerror(errno));
2150 /* unlink pty from session */
2155 session_pty_cleanup(Session *s)
2157 PRIVSEP(session_pty_cleanup2(s));
2163 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2178 return "SIG@openssh.com";
2182 session_close_x11(struct ssh *ssh, int id)
2186 if ((c = channel_by_id(ssh, id)) == NULL) {
2187 debug("%s: x11 channel %d missing", __func__, id);
2189 /* Detach X11 listener */
2190 debug("%s: detach x11 channel %d", __func__, id);
2191 channel_cancel_cleanup(ssh, id);
2192 if (c->ostate != CHAN_OUTPUT_CLOSED)
2193 chan_mark_dead(ssh, c);
2198 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2203 debug3("%s: channel %d", __func__, id);
2204 channel_cancel_cleanup(ssh, id);
2205 if ((s = session_by_x11_channel(id)) == NULL)
2206 fatal("%s: no x11 channel %d", __func__, id);
2207 for (i = 0; s->x11_chanids[i] != -1; i++) {
2208 debug("%s: session %d: closing channel %d",
2209 __func__, s->self, s->x11_chanids[i]);
2211 * The channel "id" is already closing, but make sure we
2212 * close all of its siblings.
2214 if (s->x11_chanids[i] != id)
2215 session_close_x11(ssh, s->x11_chanids[i]);
2217 free(s->x11_chanids);
2218 s->x11_chanids = NULL;
2221 free(s->auth_proto);
2222 s->auth_proto = NULL;
2224 s->auth_data = NULL;
2225 free(s->auth_display);
2226 s->auth_display = NULL;
2230 session_exit_message(struct ssh *ssh, Session *s, int status)
2234 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2235 fatal("%s: session %d: no channel %d",
2236 __func__, s->self, s->chanid);
2237 debug("%s: session %d channel %d pid %ld",
2238 __func__, s->self, s->chanid, (long)s->pid);
2240 if (WIFEXITED(status)) {
2241 channel_request_start(ssh, s->chanid, "exit-status", 0);
2242 packet_put_int(WEXITSTATUS(status));
2244 } else if (WIFSIGNALED(status)) {
2245 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2246 packet_put_cstring(sig2name(WTERMSIG(status)));
2248 packet_put_char(WCOREDUMP(status)? 1 : 0);
2249 #else /* WCOREDUMP */
2251 #endif /* WCOREDUMP */
2252 packet_put_cstring("");
2253 packet_put_cstring("");
2256 /* Some weird exit cause. Just exit. */
2257 packet_disconnect("wait returned status %04x.", status);
2260 /* disconnect channel */
2261 debug("%s: release channel %d", __func__, s->chanid);
2264 * Adjust cleanup callback attachment to send close messages when
2265 * the channel gets EOF. The session will be then be closed
2266 * by session_close_by_channel when the childs close their fds.
2268 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2271 * emulate a write failure with 'chan_write_failed', nobody will be
2272 * interested in data we write.
2273 * Note that we must not call 'chan_read_failed', since there could
2274 * be some more data waiting in the pipe.
2276 if (c->ostate != CHAN_OUTPUT_CLOSED)
2277 chan_write_failed(ssh, c);
2281 session_close(struct ssh *ssh, Session *s)
2285 verbose("Close session: user %s from %.200s port %d id %d",
2287 ssh_remote_ipaddr(ssh),
2288 ssh_remote_port(ssh),
2292 session_pty_cleanup(s);
2295 free(s->x11_chanids);
2296 free(s->auth_display);
2298 free(s->auth_proto);
2300 if (s->env != NULL) {
2301 for (i = 0; i < s->num_env; i++) {
2302 free(s->env[i].name);
2303 free(s->env[i].val);
2307 session_proctitle(s);
2308 session_unused(s->self);
2312 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2314 Session *s = session_by_pid(pid);
2316 debug("%s: no session for pid %ld", __func__, (long)pid);
2319 if (s->chanid != -1)
2320 session_exit_message(ssh, s, status);
2322 session_pty_cleanup(s);
2327 * this is called when a channel dies before
2328 * the session 'child' itself dies
2331 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2333 Session *s = session_by_channel(id);
2337 debug("%s: no session for id %d", __func__, id);
2340 debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
2342 debug("%s: channel %d: has child", __func__, id);
2344 * delay detach of session, but release pty, since
2345 * the fd's to the child are already closed
2348 session_pty_cleanup(s);
2351 /* detach by removing callback */
2352 channel_cancel_cleanup(ssh, s->chanid);
2354 /* Close any X11 listeners associated with this session */
2355 if (s->x11_chanids != NULL) {
2356 for (i = 0; s->x11_chanids[i] != -1; i++) {
2357 session_close_x11(ssh, s->x11_chanids[i]);
2358 s->x11_chanids[i] = -1;
2363 session_close(ssh, s);
2367 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2370 for (i = 0; i < sessions_nalloc; i++) {
2371 Session *s = &sessions[i];
2373 if (closefunc != NULL)
2376 session_close(ssh, s);
2382 session_tty_list(void)
2384 static char buf[1024];
2389 for (i = 0; i < sessions_nalloc; i++) {
2390 Session *s = &sessions[i];
2391 if (s->used && s->ttyfd != -1) {
2393 if (strncmp(s->tty, "/dev/", 5) != 0) {
2394 cp = strrchr(s->tty, '/');
2395 cp = (cp == NULL) ? s->tty : cp + 1;
2400 strlcat(buf, ",", sizeof buf);
2401 strlcat(buf, cp, sizeof buf);
2405 strlcpy(buf, "notty", sizeof buf);
2410 session_proctitle(Session *s)
2413 error("no user for session %d", s->self);
2415 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2419 session_setup_x11fwd(struct ssh *ssh, Session *s)
2422 char display[512], auth_display[512];
2423 char hostname[NI_MAXHOST];
2426 if (no_x11_forwarding_flag) {
2427 packet_send_debug("X11 forwarding disabled in user configuration file.");
2430 if (!options.x11_forwarding) {
2431 debug("X11 forwarding disabled in server configuration file.");
2434 if (options.xauth_location == NULL ||
2435 (stat(options.xauth_location, &st) == -1)) {
2436 packet_send_debug("No xauth program; cannot forward with spoofing.");
2439 if (s->display != NULL) {
2440 debug("X11 display already set.");
2443 if (x11_create_display_inet(ssh, options.x11_display_offset,
2444 options.x11_use_localhost, s->single_connection,
2445 &s->display_number, &s->x11_chanids) == -1) {
2446 debug("x11_create_display_inet failed.");
2449 for (i = 0; s->x11_chanids[i] != -1; i++) {
2450 channel_register_cleanup(ssh, s->x11_chanids[i],
2451 session_close_single_x11, 0);
2454 /* Set up a suitable value for the DISPLAY variable. */
2455 if (gethostname(hostname, sizeof(hostname)) < 0)
2456 fatal("gethostname: %.100s", strerror(errno));
2458 * auth_display must be used as the displayname when the
2459 * authorization entry is added with xauth(1). This will be
2460 * different than the DISPLAY string for localhost displays.
2462 if (options.x11_use_localhost) {
2463 snprintf(display, sizeof display, "localhost:%u.%u",
2464 s->display_number, s->screen);
2465 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2466 s->display_number, s->screen);
2467 s->display = xstrdup(display);
2468 s->auth_display = xstrdup(auth_display);
2470 #ifdef IPADDR_IN_DISPLAY
2472 struct in_addr my_addr;
2474 he = gethostbyname(hostname);
2476 error("Can't get IP address for X11 DISPLAY.");
2477 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2480 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2481 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2482 s->display_number, s->screen);
2484 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2485 s->display_number, s->screen);
2487 s->display = xstrdup(display);
2488 s->auth_display = xstrdup(display);
2495 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2497 server_loop2(ssh, authctxt);
2501 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2503 static int called = 0;
2505 debug("do_cleanup");
2507 /* no cleanup if we're in the child for login shell */
2511 /* avoid double cleanup */
2516 if (authctxt == NULL)
2520 if (options.use_pam) {
2522 sshpam_thread_cleanup();
2526 if (!authctxt->authenticated)
2530 if (options.kerberos_ticket_cleanup &&
2532 krb5_cleanup_proc(authctxt);
2536 if (options.gss_cleanup_creds)
2537 ssh_gssapi_cleanup_creds();
2540 /* remove agent socket */
2541 auth_sock_cleanup_proc(authctxt->pw);
2543 /* remove userauth info */
2544 if (auth_info_file != NULL) {
2545 temporarily_use_uid(authctxt->pw);
2546 unlink(auth_info_file);
2548 free(auth_info_file);
2549 auth_info_file = NULL;
2553 * Cleanup ptys/utmp only if privsep is disabled,
2554 * or if running in monitor.
2556 if (!use_privsep || mm_is_monitor())
2557 session_destroy_all(ssh, session_pty_cleanup2);
2560 /* Return a name for the remote host that fits inside utmp_size */
2563 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2565 const char *remote = "";
2568 remote = auth_get_canonical_hostname(ssh, use_dns);
2569 if (utmp_size == 0 || strlen(remote) > utmp_size)
2570 remote = ssh_remote_ipaddr(ssh);