1 /* $OpenBSD: session.c,v 1.329 2021/08/11 05:20:17 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"
86 #include "auth-options.h"
88 #include "pathnames.h"
93 #include "serverloop.h"
97 #include "monitor_wrap.h"
101 #if defined(KRB5) && defined(USE_AFS)
106 #include <selinux/selinux.h>
109 #define IS_INTERNAL_SFTP(c) \
110 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
111 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
112 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
113 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
117 Session *session_new(void);
118 void session_set_fds(struct ssh *, Session *, int, int, int, int, int);
119 void session_pty_cleanup(Session *);
120 void session_proctitle(Session *);
121 int session_setup_x11fwd(struct ssh *, Session *);
122 int do_exec_pty(struct ssh *, Session *, const char *);
123 int do_exec_no_pty(struct ssh *, Session *, const char *);
124 int do_exec(struct ssh *, Session *, const char *);
125 void do_login(struct ssh *, Session *, const char *);
126 void do_child(struct ssh *, Session *, const char *);
128 int check_quietlogin(Session *, const char *);
130 static void do_authenticated2(struct ssh *, Authctxt *);
132 static int session_pty_req(struct ssh *, Session *);
135 extern ServerOptions options;
136 extern char *__progname;
137 extern int debug_flag;
138 extern u_int utmp_len;
139 extern int startup_pipe;
140 extern void destroy_sensitive_data(void);
141 extern struct sshbuf *loginmsg;
142 extern struct sshauthopt *auth_opts;
143 extern char *tun_fwd_ifnames; /* serverloop.c */
145 /* original command from peer. */
146 const char *original_command = NULL;
149 static int sessions_first_unused = -1;
150 static int sessions_nalloc = 0;
151 static Session *sessions = NULL;
153 #define SUBSYSTEM_NONE 0
154 #define SUBSYSTEM_EXT 1
155 #define SUBSYSTEM_INT_SFTP 2
156 #define SUBSYSTEM_INT_SFTP_ERROR 3
158 #ifdef HAVE_LOGIN_CAP
162 static int is_child = 0;
163 static int in_chroot = 0;
165 /* File containing userauth info, if ExposeAuthInfo set */
166 static char *auth_info_file = NULL;
168 /* Name and directory of socket for authentication agent forwarding. */
169 static char *auth_sock_name = NULL;
170 static char *auth_sock_dir = NULL;
172 /* removes the agent forwarding socket */
175 auth_sock_cleanup_proc(struct passwd *pw)
177 if (auth_sock_name != NULL) {
178 temporarily_use_uid(pw);
179 unlink(auth_sock_name);
180 rmdir(auth_sock_dir);
181 auth_sock_name = NULL;
187 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
192 if (auth_sock_name != NULL) {
193 error("authentication forwarding requested twice.");
197 /* Temporarily drop privileged uid for mkdir/bind. */
198 temporarily_use_uid(pw);
200 /* Allocate a buffer for the socket name, and format the name. */
201 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
203 /* Create private directory for socket */
204 if (mkdtemp(auth_sock_dir) == NULL) {
205 ssh_packet_send_debug(ssh, "Agent forwarding disabled: "
206 "mkdtemp() failed: %.100s", strerror(errno));
209 auth_sock_dir = NULL;
213 xasprintf(&auth_sock_name, "%s/agent.%ld",
214 auth_sock_dir, (long) getpid());
216 /* Start a Unix listener on auth_sock_name. */
217 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
219 /* Restore the privileged uid. */
222 /* Check for socket/bind/listen failure. */
226 /* Allocate a channel for the authentication agent socket. */
227 nc = channel_new(ssh, "auth socket",
228 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
229 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
230 0, "auth socket", 1);
231 nc->path = xstrdup(auth_sock_name);
235 free(auth_sock_name);
236 if (auth_sock_dir != NULL) {
237 temporarily_use_uid(pw);
238 rmdir(auth_sock_dir);
244 auth_sock_name = NULL;
245 auth_sock_dir = NULL;
250 display_loginmsg(void)
254 if (sshbuf_len(loginmsg) == 0)
256 if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
257 fatal_fr(r, "sshbuf_put_u8");
258 printf("%s", (char *)sshbuf_ptr(loginmsg));
259 sshbuf_reset(loginmsg);
263 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
265 int fd = -1, success = 0;
267 if (!options.expose_userauth_info || info == NULL)
270 temporarily_use_uid(pw);
271 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
272 if ((fd = mkstemp(auth_info_file)) == -1) {
273 error_f("mkstemp: %s", strerror(errno));
276 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
277 sshbuf_len(info)) != sshbuf_len(info)) {
278 error_f("write: %s", strerror(errno));
281 if (close(fd) != 0) {
282 error_f("close: %s", strerror(errno));
290 free(auth_info_file);
291 auth_info_file = NULL;
297 set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
299 char *tmp, *cp, *host;
303 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
304 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
305 for (i = 0; i < auth_opts->npermitopen; i++) {
306 tmp = cp = xstrdup(auth_opts->permitopen[i]);
307 /* This shouldn't fail as it has already been checked */
308 if ((host = hpdelim(&cp)) == NULL)
309 fatal_f("internal error: hpdelim");
310 host = cleanhostname(host);
311 if (cp == NULL || (port = permitopen_port(cp)) < 0)
312 fatal_f("internal error: permitopen port");
313 channel_add_permission(ssh,
314 FORWARD_USER, FORWARD_LOCAL, host, port);
318 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
319 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
320 for (i = 0; i < auth_opts->npermitlisten; i++) {
321 tmp = cp = xstrdup(auth_opts->permitlisten[i]);
322 /* This shouldn't fail as it has already been checked */
323 if ((host = hpdelim(&cp)) == NULL)
324 fatal_f("internal error: hpdelim");
325 host = cleanhostname(host);
326 if (cp == NULL || (port = permitopen_port(cp)) < 0)
327 fatal_f("internal error: permitlisten port");
328 channel_add_permission(ssh,
329 FORWARD_USER, FORWARD_REMOTE, host, port);
336 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
338 setproctitle("%s", authctxt->pw->pw_name);
340 auth_log_authopts("active", auth_opts, 0);
342 /* setup the channel layer */
343 /* XXX - streamlocal? */
344 set_fwdpermit_from_authopts(ssh, auth_opts);
346 if (!auth_opts->permit_port_forwarding_flag ||
347 options.disable_forwarding) {
348 channel_disable_admin(ssh, FORWARD_LOCAL);
349 channel_disable_admin(ssh, FORWARD_REMOTE);
351 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
352 channel_disable_admin(ssh, FORWARD_LOCAL);
354 channel_permit_all(ssh, FORWARD_LOCAL);
355 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
356 channel_disable_admin(ssh, FORWARD_REMOTE);
358 channel_permit_all(ssh, FORWARD_REMOTE);
360 auth_debug_send(ssh);
362 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
364 do_authenticated2(ssh, authctxt);
366 do_cleanup(ssh, authctxt);
369 /* Check untrusted xauth strings for metacharacters */
371 xauth_valid_string(const char *s)
375 for (i = 0; s[i] != '\0'; i++) {
376 if (!isalnum((u_char)s[i]) &&
377 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
378 s[i] != '-' && s[i] != '_')
386 * This is called to fork and execute a command when we have no tty. This
387 * will call do_child from the child, and server_loop from the parent after
388 * setting up file descriptors and such.
391 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
395 int pin[2], pout[2], perr[2];
398 fatal("do_exec_no_pty: no session");
400 /* Allocate pipes for communicating with the program. */
401 if (pipe(pin) == -1) {
402 error_f("pipe in: %.100s", strerror(errno));
405 if (pipe(pout) == -1) {
406 error_f("pipe out: %.100s", strerror(errno));
411 if (pipe(perr) == -1) {
412 error_f("pipe err: %.100s", strerror(errno));
420 int inout[2], err[2];
423 fatal("do_exec_no_pty: no session");
425 /* Uses socket pairs to communicate with the program. */
426 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) {
427 error_f("socketpair #1: %.100s", strerror(errno));
430 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) == -1) {
431 error_f("socketpair #2: %.100s", strerror(errno));
438 session_proctitle(s);
440 /* Fork the child. */
441 switch ((pid = fork())) {
443 error_f("fork: %.100s", strerror(errno));
462 * Create a new session and process group since the 4.4BSD
463 * setlogin() affects the entire process group.
466 error("setsid failed: %.100s", strerror(errno));
470 * Redirect stdin. We close the parent side of the socket
471 * pair, and make the child side the standard input.
474 if (dup2(pin[0], 0) == -1)
475 perror("dup2 stdin");
478 /* Redirect stdout. */
480 if (dup2(pout[1], 1) == -1)
481 perror("dup2 stdout");
484 /* Redirect stderr. */
486 if (dup2(perr[1], 2) == -1)
487 perror("dup2 stderr");
491 * Redirect stdin, stdout, and stderr. Stdin and stdout will
492 * use the same socket, as some programs (particularly rdist)
493 * seem to depend on it.
497 if (dup2(inout[0], 0) == -1) /* stdin */
498 perror("dup2 stdin");
499 if (dup2(inout[0], 1) == -1) /* stdout (same as stdin) */
500 perror("dup2 stdout");
502 if (dup2(err[0], 2) == -1) /* stderr */
503 perror("dup2 stderr");
507 /* Do processing for the child (exec command etc). */
508 do_child(ssh, s, command);
515 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
519 /* Set interactive/non-interactive mode. */
520 ssh_packet_set_interactive(ssh, s->display != NULL,
521 options.ip_qos_interactive, options.ip_qos_bulk);
524 * Clear loginmsg, since it's the child's responsibility to display
525 * it to the user, otherwise multiple sessions may accumulate
526 * multiple copies of the login messages.
528 sshbuf_reset(loginmsg);
531 /* We are the parent. Close the child sides of the pipes. */
536 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
539 /* We are the parent. Close the child sides of the socket pairs. */
544 * Enter the interactive session. Note: server_loop must be able to
545 * handle the case that fdin and fdout are the same.
547 session_set_fds(ssh, s, inout[1], inout[1], err[1],
554 * This is called to fork and execute a command when we have a tty. This
555 * will call do_child from the child, and server_loop from the parent after
556 * setting up file descriptors, controlling tty, updating wtmp, utmp,
557 * lastlog, and other such operations.
560 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
562 int fdout, ptyfd, ttyfd, ptymaster;
566 fatal("do_exec_pty: no session");
571 * Create another descriptor of the pty master side for use as the
572 * standard input. We could use the original descriptor, but this
573 * simplifies code in server_loop. The descriptor is bidirectional.
574 * Do this before forking (and cleanup in the child) so as to
575 * detect and gracefully fail out-of-fd conditions.
577 if ((fdout = dup(ptyfd)) == -1) {
578 error_f("dup #1: %s", strerror(errno));
583 /* we keep a reference to the pty master */
584 if ((ptymaster = dup(ptyfd)) == -1) {
585 error_f("dup #2: %s", strerror(errno));
592 /* Fork the child. */
593 switch ((pid = fork())) {
595 error_f("fork: %.100s", strerror(errno));
607 /* Close the master side of the pseudo tty. */
610 /* Make the pseudo tty our controlling tty. */
611 pty_make_controlling_tty(&ttyfd, s->tty);
613 /* Redirect stdin/stdout/stderr from the pseudo tty. */
614 if (dup2(ttyfd, 0) == -1)
615 error("dup2 stdin: %s", strerror(errno));
616 if (dup2(ttyfd, 1) == -1)
617 error("dup2 stdout: %s", strerror(errno));
618 if (dup2(ttyfd, 2) == -1)
619 error("dup2 stderr: %s", strerror(errno));
621 /* Close the extra descriptor for the pseudo tty. */
624 /* record login, etc. similar to login(1) */
626 do_login(ssh, s, command);
629 * Do common processing for the child, such as execing
632 do_child(ssh, s, command);
639 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
644 /* Parent. Close the slave side of the pseudo tty. */
647 /* Enter interactive session. */
648 s->ptymaster = ptymaster;
649 ssh_packet_set_interactive(ssh, 1,
650 options.ip_qos_interactive, options.ip_qos_bulk);
651 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
656 * This is called to fork and execute a command. If another command is
657 * to be forced, execute that instead.
660 do_exec(struct ssh *ssh, Session *s, const char *command)
663 const char *forced = NULL, *tty = NULL;
664 char session_type[1024];
666 if (options.adm_forced_command) {
667 original_command = command;
668 command = options.adm_forced_command;
670 } else if (auth_opts->force_command != NULL) {
671 original_command = command;
672 command = auth_opts->force_command;
673 forced = "(key-option)";
676 if (forced != NULL) {
678 if (IS_INTERNAL_SFTP(command)) {
679 s->is_subsystem = s->is_subsystem ?
680 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
681 } else if (s->is_subsystem)
682 s->is_subsystem = SUBSYSTEM_EXT;
683 snprintf(session_type, sizeof(session_type),
684 "forced-command %s '%.900s'", forced, command);
685 } else if (s->is_subsystem) {
686 snprintf(session_type, sizeof(session_type),
687 "subsystem '%.900s'", s->subsys);
688 } else if (command == NULL) {
689 snprintf(session_type, sizeof(session_type), "shell");
691 /* NB. we don't log unforced commands to preserve privacy */
692 snprintf(session_type, sizeof(session_type), "command");
695 if (s->ttyfd != -1) {
697 if (strncmp(tty, "/dev/", 5) == 0)
701 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
703 tty == NULL ? "" : " on ",
704 tty == NULL ? "" : tty,
706 ssh_remote_ipaddr(ssh),
707 ssh_remote_port(ssh),
710 #ifdef SSH_AUDIT_EVENTS
712 PRIVSEP(audit_run_command(command));
713 else if (s->ttyfd == -1) {
714 char *shell = s->pw->pw_shell;
716 if (shell[0] == '\0') /* empty shell means /bin/sh */
718 PRIVSEP(audit_run_command(shell));
722 ret = do_exec_pty(ssh, s, command);
724 ret = do_exec_no_pty(ssh, s, command);
726 original_command = NULL;
729 * Clear loginmsg: it's the child's responsibility to display
730 * it to the user, otherwise multiple sessions may accumulate
731 * multiple copies of the login messages.
733 sshbuf_reset(loginmsg);
738 /* administrative, login(1)-like work */
740 do_login(struct ssh *ssh, Session *s, const char *command)
743 struct sockaddr_storage from;
744 struct passwd * pw = s->pw;
745 pid_t pid = getpid();
748 * Get IP address of client. If the connection is not a socket, let
749 * the address be 0.0.0.0.
751 memset(&from, 0, sizeof(from));
752 fromlen = sizeof(from);
753 if (ssh_packet_connection_is_on_socket(ssh)) {
754 if (getpeername(ssh_packet_get_connection_in(ssh),
755 (struct sockaddr *)&from, &fromlen) == -1) {
756 debug("getpeername: %.100s", strerror(errno));
761 /* Record that there was a login on that tty from the remote host. */
763 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
764 session_get_remote_name_or_ip(ssh, utmp_len,
766 (struct sockaddr *)&from, fromlen);
770 * If password change is needed, do it now.
771 * This needs to occur before the ~/.hushlogin check.
773 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
776 s->authctxt->force_pwchange = 0;
777 /* XXX - signal [net] parent to enable forwardings */
781 if (check_quietlogin(s, command))
790 * Display the message of the day.
798 if (options.print_motd) {
799 #ifdef HAVE_LOGIN_CAP
800 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
803 f = fopen("/etc/motd", "r");
806 while (fgets(buf, sizeof(buf), f))
815 * Check for quiet login, either .hushlogin or command given.
818 check_quietlogin(Session *s, const char *command)
821 struct passwd *pw = s->pw;
824 /* Return 1 if .hushlogin exists or a command given. */
827 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
828 #ifdef HAVE_LOGIN_CAP
829 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
832 if (stat(buf, &st) >= 0)
839 * Reads environment variables from the given file and adds/overrides them
840 * into the environment. If the file does not exist, this does nothing.
841 * Otherwise, it must consist of empty lines, comments (line starts with '#')
842 * and assignments of the form name=value. No other forms are allowed.
843 * If allowlist is not NULL, then it is interpreted as a pattern list and
844 * only variable names that match it will be accepted.
847 read_environment_file(char ***env, u_int *envsize,
848 const char *filename, const char *allowlist)
851 char *line = NULL, *cp, *value;
855 f = fopen(filename, "r");
859 while (getline(&line, &linesize, f) != -1) {
861 fatal("Too many lines in environment file %s", filename);
862 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
864 if (!*cp || *cp == '#' || *cp == '\n')
867 cp[strcspn(cp, "\n")] = '\0';
869 value = strchr(cp, '=');
871 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
876 * Replace the equals sign by nul, and advance value to
881 if (allowlist != NULL &&
882 match_pattern_list(cp, allowlist, 0) != 1)
884 child_set_env(env, envsize, cp, value);
890 #ifdef HAVE_ETC_DEFAULT_LOGIN
892 * Return named variable from specified environment, or NULL if not present.
895 child_get_env(char **env, const char *name)
901 for (i=0; env[i] != NULL; i++)
902 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
903 return(env[i] + len + 1);
908 * Read /etc/default/login.
909 * We pick up the PATH (or SUPATH for root) and UMASK.
912 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
914 char **tmpenv = NULL, *var;
915 u_int i, tmpenvsize = 0;
919 * We don't want to copy the whole file to the child's environment,
920 * so we use a temporary environment and copy the variables we're
923 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
924 options.permit_user_env_allowlist);
930 var = child_get_env(tmpenv, "SUPATH");
932 var = child_get_env(tmpenv, "PATH");
934 child_set_env(env, envsize, "PATH", var);
936 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
937 if (sscanf(var, "%5lo", &mask) == 1)
940 for (i = 0; tmpenv[i] != NULL; i++)
944 #endif /* HAVE_ETC_DEFAULT_LOGIN */
946 #if defined(USE_PAM) || defined(HAVE_CYGWIN)
948 copy_environment_denylist(char **source, char ***env, u_int *envsize,
949 const char *denylist)
951 char *var_name, *var_val;
957 for(i = 0; source[i] != NULL; i++) {
958 var_name = xstrdup(source[i]);
959 if ((var_val = strstr(var_name, "=")) == NULL) {
965 if (denylist == NULL ||
966 match_pattern_list(var_name, denylist, 0) != 1) {
967 debug3("Copy environment: %s=%s", var_name, var_val);
968 child_set_env(env, envsize, var_name, var_val);
974 #endif /* defined(USE_PAM) || defined(HAVE_CYGWIN) */
978 copy_environment(char **source, char ***env, u_int *envsize)
980 copy_environment_denylist(source, env, envsize, NULL);
985 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
990 char *ocp, *cp, *value, **env, *laddr;
991 struct passwd *pw = s->pw;
992 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
995 extern char **environ;
996 char **senv, **var, *val;
999 /* Initialize the environment. */
1001 env = xcalloc(envsize, sizeof(char *));
1006 * The Windows environment contains some setting which are
1007 * important for a running system. They must not be dropped.
1012 p = fetch_windows_environment();
1013 copy_environment(p, &env, &envsize);
1014 free_windows_environment(p);
1019 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1022 /* Allow any GSSAPI methods that we've used to alter
1023 * the child's environment as they see fit
1025 ssh_gssapi_do_child(&env, &envsize);
1028 /* Set basic environment. */
1029 for (i = 0; i < s->num_env; i++)
1030 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1032 child_set_env(&env, &envsize, "USER", pw->pw_name);
1033 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1035 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1037 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1038 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1039 child_set_env(&env, &envsize, "MAIL", buf);
1040 #ifdef HAVE_LOGIN_CAP
1041 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1042 child_set_env(&env, &envsize, "TERM", "su");
1044 * Temporarily swap out our real environment with an empty one,
1045 * let setusercontext() apply any environment variables defined
1046 * for the user's login class, copy those variables to the child,
1047 * free the temporary environment, and restore the original.
1050 environ = xmalloc(sizeof(*environ));
1052 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1053 for (var = environ; *var != NULL; ++var) {
1054 if ((val = strchr(*var, '=')) != NULL) {
1056 child_set_env(&env, &envsize, *var, val);
1062 #else /* HAVE_LOGIN_CAP */
1063 # ifndef HAVE_CYGWIN
1065 * There's no standard path on Windows. The path contains
1066 * important components pointing to the system directories,
1067 * needed for loading shared libraries. So the path better
1068 * remains intact here.
1070 # ifdef HAVE_ETC_DEFAULT_LOGIN
1071 read_etc_default_login(&env, &envsize, pw->pw_uid);
1072 path = child_get_env(env, "PATH");
1073 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1074 if (path == NULL || *path == '\0') {
1075 child_set_env(&env, &envsize, "PATH",
1076 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1078 # endif /* HAVE_CYGWIN */
1079 #endif /* HAVE_LOGIN_CAP */
1081 if (!options.use_pam) {
1082 snprintf(buf, sizeof buf, "%.200s/%.50s",
1083 _PATH_MAILDIR, pw->pw_name);
1084 child_set_env(&env, &envsize, "MAIL", buf);
1087 /* Normal systems set SHELL by default. */
1088 child_set_env(&env, &envsize, "SHELL", shell);
1091 child_set_env(&env, &envsize, "TERM", s->term);
1093 child_set_env(&env, &envsize, "DISPLAY", s->display);
1096 * Since we clear KRB5CCNAME at startup, if it's set now then it
1097 * must have been set by a native authentication method (eg AIX or
1098 * SIA), so copy it to the child.
1103 if ((cp = getenv("KRB5CCNAME")) != NULL)
1104 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1111 if ((cp = getenv("AUTHSTATE")) != NULL)
1112 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1113 read_environment_file(&env, &envsize, "/etc/environment",
1114 options.permit_user_env_allowlist);
1118 if (s->authctxt->krb5_ccname)
1119 child_set_env(&env, &envsize, "KRB5CCNAME",
1120 s->authctxt->krb5_ccname);
1122 if (auth_sock_name != NULL)
1123 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1127 /* Set custom environment options from pubkey authentication. */
1128 if (options.permit_user_env) {
1129 for (n = 0 ; n < auth_opts->nenv; n++) {
1130 ocp = xstrdup(auth_opts->env[n]);
1131 cp = strchr(ocp, '=');
1134 /* Apply PermitUserEnvironment allowlist */
1135 if (options.permit_user_env_allowlist == NULL ||
1136 match_pattern_list(ocp,
1137 options.permit_user_env_allowlist, 0) == 1)
1138 child_set_env(&env, &envsize,
1145 /* read $HOME/.ssh/environment. */
1146 if (options.permit_user_env) {
1147 snprintf(buf, sizeof buf, "%.200s/%s/environment",
1148 pw->pw_dir, _PATH_SSH_USER_DIR);
1149 read_environment_file(&env, &envsize, buf,
1150 options.permit_user_env_allowlist);
1155 * Pull in any environment variables that may have
1158 if (options.use_pam) {
1162 * Don't allow PAM-internal env vars to leak
1163 * back into the session environment.
1165 #define PAM_ENV_DENYLIST "SSH_AUTH_INFO*,SSH_CONNECTION*"
1166 p = fetch_pam_child_environment();
1167 copy_environment_denylist(p, &env, &envsize,
1169 free_pam_environment(p);
1171 p = fetch_pam_environment();
1172 copy_environment_denylist(p, &env, &envsize,
1174 free_pam_environment(p);
1176 #endif /* USE_PAM */
1178 /* Environment specified by admin */
1179 for (i = 0; i < options.num_setenv; i++) {
1180 cp = xstrdup(options.setenv[i]);
1181 if ((value = strchr(cp, '=')) == NULL) {
1182 /* shouldn't happen; vars are checked in servconf.c */
1183 fatal("Invalid config SetEnv: %s", options.setenv[i]);
1186 child_set_env(&env, &envsize, cp, value);
1189 /* SSH_CLIENT deprecated */
1190 snprintf(buf, sizeof buf, "%.50s %d %d",
1191 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1192 ssh_local_port(ssh));
1193 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1195 laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh));
1196 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1197 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1198 laddr, ssh_local_port(ssh));
1200 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1202 if (tun_fwd_ifnames != NULL)
1203 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1204 if (auth_info_file != NULL)
1205 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1207 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1208 if (original_command)
1209 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1213 /* dump the environment */
1214 fprintf(stderr, "Environment:\n");
1215 for (i = 0; env[i]; i++)
1216 fprintf(stderr, " %.200s\n", env[i]);
1222 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1223 * first in this order).
1226 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1229 char *cmd = NULL, *user_rc = NULL;
1234 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1235 xasprintf(&user_rc, "%s/%s", s->pw->pw_dir, _PATH_SSH_USER_RC);
1237 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1238 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1239 auth_opts->permit_user_rc && options.permit_user_rc &&
1240 stat(user_rc, &st) >= 0) {
1241 if (xasprintf(&cmd, "%s -c '%s %s'", shell, _PATH_BSHELL,
1243 fatal_f("xasprintf: %s", strerror(errno));
1245 fprintf(stderr, "Running %s\n", cmd);
1246 f = popen(cmd, "w");
1249 fprintf(f, "%s %s\n", s->auth_proto,
1253 fprintf(stderr, "Could not run %s\n",
1255 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1257 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1258 _PATH_SSH_SYSTEM_RC);
1259 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1262 fprintf(f, "%s %s\n", s->auth_proto,
1266 fprintf(stderr, "Could not run %s\n",
1267 _PATH_SSH_SYSTEM_RC);
1268 } else if (do_xauth && options.xauth_location != NULL) {
1269 /* Add authority data to .Xauthority if appropriate. */
1272 "Running %.500s remove %.100s\n",
1273 options.xauth_location, s->auth_display);
1275 "%.500s add %.100s %.100s %.100s\n",
1276 options.xauth_location, s->auth_display,
1277 s->auth_proto, s->auth_data);
1279 if (xasprintf(&cmd, "%s -q -", options.xauth_location) == -1)
1280 fatal_f("xasprintf: %s", strerror(errno));
1281 f = popen(cmd, "w");
1283 fprintf(f, "remove %s\n",
1285 fprintf(f, "add %s %s %s\n",
1286 s->auth_display, s->auth_proto,
1290 fprintf(stderr, "Could not run %s\n",
1299 do_nologin(struct passwd *pw)
1303 char buf[1024], *def_nl = _PATH_NOLOGIN;
1306 #ifdef HAVE_LOGIN_CAP
1307 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1309 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1311 if (pw->pw_uid == 0)
1315 if (stat(nl, &sb) == -1)
1318 /* /etc/nologin exists. Print its contents if we can and exit. */
1319 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1320 if ((f = fopen(nl, "r")) != NULL) {
1321 while (fgets(buf, sizeof(buf), f))
1329 * Chroot into a directory after checking it for safety: all path components
1330 * must be root-owned directories with strict permissions.
1333 safely_chroot(const char *path, uid_t uid)
1336 char component[PATH_MAX];
1339 if (!path_absolute(path))
1340 fatal("chroot path does not begin at root");
1341 if (strlen(path) >= sizeof(component))
1342 fatal("chroot path too long");
1345 * Descend the path, checking that each component is a
1346 * root-owned directory with strict permissions.
1348 for (cp = path; cp != NULL;) {
1349 if ((cp = strchr(cp, '/')) == NULL)
1350 strlcpy(component, path, sizeof(component));
1353 memcpy(component, path, cp - path);
1354 component[cp - path] = '\0';
1357 debug3_f("checking '%s'", component);
1359 if (stat(component, &st) != 0)
1360 fatal_f("stat(\"%s\"): %s",
1361 component, strerror(errno));
1362 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1363 fatal("bad ownership or modes for chroot "
1364 "directory %s\"%s\"",
1365 cp == NULL ? "" : "component ", component);
1366 if (!S_ISDIR(st.st_mode))
1367 fatal("chroot path %s\"%s\" is not a directory",
1368 cp == NULL ? "" : "component ", component);
1372 if (chdir(path) == -1)
1373 fatal("Unable to chdir to chroot path \"%s\": "
1374 "%s", path, strerror(errno));
1375 if (chroot(path) == -1)
1376 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1377 if (chdir("/") == -1)
1378 fatal_f("chdir(/) after chroot: %s", strerror(errno));
1379 verbose("Changed root directory to \"%s\"", path);
1382 /* Set login name, uid, gid, and groups. */
1384 do_setusercontext(struct passwd *pw)
1386 char uidstr[32], *chroot_path, *tmp;
1388 platform_setusercontext(pw);
1390 if (platform_privileged_uidswap()) {
1391 #ifdef HAVE_LOGIN_CAP
1392 if (setusercontext(lc, pw, pw->pw_uid,
1393 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1394 perror("unable to set user context");
1398 if (setlogin(pw->pw_name) < 0)
1399 error("setlogin failed: %s", strerror(errno));
1400 if (setgid(pw->pw_gid) < 0) {
1404 /* Initialize the group list. */
1405 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1406 perror("initgroups");
1412 platform_setusercontext_post_groups(pw);
1414 if (!in_chroot && options.chroot_directory != NULL &&
1415 strcasecmp(options.chroot_directory, "none") != 0) {
1416 tmp = tilde_expand_filename(options.chroot_directory,
1418 snprintf(uidstr, sizeof(uidstr), "%llu",
1419 (unsigned long long)pw->pw_uid);
1420 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1421 "u", pw->pw_name, "U", uidstr, (char *)NULL);
1422 safely_chroot(chroot_path, pw->pw_uid);
1425 /* Make sure we don't attempt to chroot again */
1426 free(options.chroot_directory);
1427 options.chroot_directory = NULL;
1431 #ifdef HAVE_LOGIN_CAP
1432 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1433 perror("unable to set user context (setuser)");
1437 * FreeBSD's setusercontext() will not apply the user's
1438 * own umask setting unless running with the user's UID.
1440 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1444 * In a chroot environment, the set_id() will always fail;
1445 * typically because of the lack of necessary authentication
1446 * services and runtime such as ./usr/lib/libiaf.so,
1447 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1448 * internal sftp chroot case. We'll lose auditing and ACLs but
1449 * permanently_set_uid will take care of the rest.
1451 if (!in_chroot && set_id(pw->pw_name) != 0)
1452 fatal("set_id(%s) Failed", pw->pw_name);
1453 # endif /* USE_LIBIAF */
1454 /* Permanently switch to the desired uid. */
1455 permanently_set_uid(pw);
1457 } else if (options.chroot_directory != NULL &&
1458 strcasecmp(options.chroot_directory, "none") != 0) {
1459 fatal("server lacks privileges to chroot to ChrootDirectory");
1462 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1463 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1467 do_pwchange(Session *s)
1470 fprintf(stderr, "WARNING: Your password has expired.\n");
1471 if (s->ttyfd != -1) {
1473 "You must change your password now and login again!\n");
1477 #ifdef PASSWD_NEEDS_USERNAME
1478 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1481 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1486 "Password change required but no TTY available.\n");
1492 child_close_fds(struct ssh *ssh)
1494 extern int auth_sock;
1496 if (auth_sock != -1) {
1501 if (ssh_packet_get_connection_in(ssh) ==
1502 ssh_packet_get_connection_out(ssh))
1503 close(ssh_packet_get_connection_in(ssh));
1505 close(ssh_packet_get_connection_in(ssh));
1506 close(ssh_packet_get_connection_out(ssh));
1509 * Close all descriptors related to channels. They will still remain
1510 * open in the parent.
1512 /* XXX better use close-on-exec? -markus */
1513 channel_close_all(ssh);
1516 * Close any extra file descriptors. Note that there may still be
1517 * descriptors left by system functions. They will be closed later.
1521 /* Stop directing logs to a high-numbered fd before we close it */
1522 log_redirect_stderr_to(NULL);
1525 * Close any extra open file descriptors so that we don't have them
1526 * hanging around in clients. Note that we want to do this after
1527 * initgroups, because at least on Solaris 2.3 it leaves file
1530 closefrom(STDERR_FILENO + 1);
1534 * Performs common processing for the child, such as setting up the
1535 * environment, closing extra file descriptors, setting the user and group
1536 * ids, and executing the command or shell.
1540 do_child(struct ssh *ssh, Session *s, const char *command)
1542 extern char **environ;
1543 char **env, *argv[ARGV_MAX], remote_id[512];
1544 const char *shell, *shell0;
1545 struct passwd *pw = s->pw;
1548 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1550 /* remove hostkey from the child's memory */
1551 destroy_sensitive_data();
1552 ssh_packet_clear_keys(ssh);
1554 /* Force a password change */
1555 if (s->authctxt->force_pwchange) {
1556 do_setusercontext(pw);
1557 child_close_fds(ssh);
1563 * Login(1) does this as well, and it needs uid 0 for the "-h"
1564 * switch, so we let login(1) to this for us.
1567 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1568 if (!check_quietlogin(s, command))
1570 #else /* HAVE_OSF_SIA */
1571 /* When PAM is enabled we rely on it to do the nologin check */
1572 if (!options.use_pam)
1574 do_setusercontext(pw);
1576 * PAM session modules in do_setusercontext may have
1577 * generated messages, so if this in an interactive
1578 * login then display them too.
1580 if (!check_quietlogin(s, command))
1582 #endif /* HAVE_OSF_SIA */
1585 if (options.use_pam && !is_pam_session_open()) {
1586 debug3("PAM session not opened, exiting");
1593 * Get the shell from the password data. An empty shell field is
1594 * legal, and means /bin/sh.
1596 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1599 * Make sure $SHELL points to the shell from the password file,
1600 * even if shell is overridden from login.conf
1602 env = do_setup_env(ssh, s, shell);
1604 #ifdef HAVE_LOGIN_CAP
1605 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1609 * Close the connection descriptors; note that this is the child, and
1610 * the server will still have the socket open, and it is important
1611 * that we do not shutdown it. Note that the descriptors cannot be
1612 * closed before building the environment, as we call
1613 * ssh_remote_ipaddr there.
1615 child_close_fds(ssh);
1618 * Must take new environment into use so that .ssh/rc,
1619 * /etc/ssh/sshrc and xauth are run in the proper environment.
1623 #if defined(KRB5) && defined(USE_AFS)
1625 * At this point, we check to see if AFS is active and if we have
1626 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1627 * if we can (and need to) extend the ticket into an AFS token. If
1628 * we don't do this, we run into potential problems if the user's
1629 * home directory is in AFS and it's not world-readable.
1632 if (options.kerberos_get_afs_token && k_hasafs() &&
1633 (s->authctxt->krb5_ctx != NULL)) {
1636 debug("Getting AFS token");
1640 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1641 krb5_afslog(s->authctxt->krb5_ctx,
1642 s->authctxt->krb5_fwd_ccache, cell, NULL);
1644 krb5_afslog_home(s->authctxt->krb5_ctx,
1645 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1649 /* Change current directory to the user's home directory. */
1650 if (chdir(pw->pw_dir) == -1) {
1651 /* Suppress missing homedir warning for chroot case */
1652 #ifdef HAVE_LOGIN_CAP
1653 r = login_getcapbool(lc, "requirehome", 0);
1655 if (r || !in_chroot) {
1656 fprintf(stderr, "Could not chdir to home "
1657 "directory %s: %s\n", pw->pw_dir,
1664 closefrom(STDERR_FILENO + 1);
1666 do_rc_files(ssh, s, shell);
1668 /* restore SIGPIPE for child */
1669 ssh_signal(SIGPIPE, SIG_DFL);
1671 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1672 error("Connection from %s: refusing non-sftp session",
1674 printf("This service allows sftp connections only.\n");
1677 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1678 extern int optind, optreset;
1682 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1683 args = xstrdup(command ? command : "sftp-server");
1684 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1685 if (i < ARGV_MAX - 1)
1688 optind = optreset = 1;
1689 __progname = argv[0];
1691 ssh_selinux_change_context("sftpd_t");
1693 exit(sftp_server_main(i, argv, s->pw));
1698 /* Get the last component of the shell name. */
1699 if ((shell0 = strrchr(shell, '/')) != NULL)
1705 * If we have no command, execute the shell. In this case, the shell
1706 * name to be passed in argv[0] is preceded by '-' to indicate that
1707 * this is a login shell.
1712 /* Start the shell. Set initial character to '-'. */
1715 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1716 >= sizeof(argv0) - 1) {
1722 /* Execute the shell. */
1725 execve(shell, argv, env);
1727 /* Executing the shell failed. */
1732 * Execute the command using the user's shell. This uses the -c
1733 * option to execute the command.
1735 argv[0] = (char *) shell0;
1737 argv[2] = (char *) command;
1739 execve(shell, argv, env);
1745 session_unused(int id)
1747 debug3_f("session id %d unused", id);
1748 if (id >= options.max_sessions ||
1749 id >= sessions_nalloc) {
1750 fatal_f("insane session id %d (max %d nalloc %d)",
1751 id, options.max_sessions, sessions_nalloc);
1753 memset(&sessions[id], 0, sizeof(*sessions));
1754 sessions[id].self = id;
1755 sessions[id].used = 0;
1756 sessions[id].chanid = -1;
1757 sessions[id].ptyfd = -1;
1758 sessions[id].ttyfd = -1;
1759 sessions[id].ptymaster = -1;
1760 sessions[id].x11_chanids = NULL;
1761 sessions[id].next_unused = sessions_first_unused;
1762 sessions_first_unused = id;
1770 if (sessions_first_unused == -1) {
1771 if (sessions_nalloc >= options.max_sessions)
1773 debug2_f("allocate (allocated %d max %d)",
1774 sessions_nalloc, options.max_sessions);
1775 tmp = xrecallocarray(sessions, sessions_nalloc,
1776 sessions_nalloc + 1, sizeof(*sessions));
1778 error_f("cannot allocate %d sessions",
1779 sessions_nalloc + 1);
1783 session_unused(sessions_nalloc++);
1786 if (sessions_first_unused >= sessions_nalloc ||
1787 sessions_first_unused < 0) {
1788 fatal_f("insane first_unused %d max %d nalloc %d",
1789 sessions_first_unused, options.max_sessions,
1793 s = &sessions[sessions_first_unused];
1795 fatal_f("session %d already used", sessions_first_unused);
1796 sessions_first_unused = s->next_unused;
1798 s->next_unused = -1;
1799 debug("session_new: session %d", s->self);
1808 for (i = 0; i < sessions_nalloc; i++) {
1809 Session *s = &sessions[i];
1811 debug("dump: used %d next_unused %d session %d "
1812 "channel %d pid %ld",
1822 session_open(Authctxt *authctxt, int chanid)
1824 Session *s = session_new();
1825 debug("session_open: channel %d", chanid);
1827 error("no more sessions");
1830 s->authctxt = authctxt;
1831 s->pw = authctxt->pw;
1832 if (s->pw == NULL || !authctxt->valid)
1833 fatal("no user for session %d", s->self);
1834 debug("session_open: session %d: link with channel %d", s->self, chanid);
1840 session_by_tty(char *tty)
1843 for (i = 0; i < sessions_nalloc; i++) {
1844 Session *s = &sessions[i];
1845 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1846 debug("session_by_tty: session %d tty %s", i, tty);
1850 debug("session_by_tty: unknown tty %.100s", tty);
1856 session_by_channel(int id)
1859 for (i = 0; i < sessions_nalloc; i++) {
1860 Session *s = &sessions[i];
1861 if (s->used && s->chanid == id) {
1862 debug("session_by_channel: session %d channel %d",
1867 debug("session_by_channel: unknown channel %d", id);
1873 session_by_x11_channel(int id)
1877 for (i = 0; i < sessions_nalloc; i++) {
1878 Session *s = &sessions[i];
1880 if (s->x11_chanids == NULL || !s->used)
1882 for (j = 0; s->x11_chanids[j] != -1; j++) {
1883 if (s->x11_chanids[j] == id) {
1884 debug("session_by_x11_channel: session %d "
1885 "channel %d", s->self, id);
1890 debug("session_by_x11_channel: unknown channel %d", id);
1896 session_by_pid(pid_t pid)
1899 debug("session_by_pid: pid %ld", (long)pid);
1900 for (i = 0; i < sessions_nalloc; i++) {
1901 Session *s = &sessions[i];
1902 if (s->used && s->pid == pid)
1905 error("session_by_pid: unknown pid %ld", (long)pid);
1911 session_window_change_req(struct ssh *ssh, Session *s)
1915 if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1916 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1917 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1918 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 ||
1919 (r = sshpkt_get_end(ssh)) != 0)
1920 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1921 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1926 session_pty_req(struct ssh *ssh, Session *s)
1930 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1931 debug("Allocating a pty not permitted for this connection.");
1934 if (s->ttyfd != -1) {
1935 ssh_packet_disconnect(ssh, "Protocol error: you already have a pty.");
1939 if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 ||
1940 (r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1941 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1942 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1943 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0)
1944 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1946 if (strcmp(s->term, "") == 0) {
1951 /* Allocate a pty and open it. */
1952 debug("Allocating pty.");
1953 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1959 error("session_pty_req: session %d alloc failed", s->self);
1962 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1964 ssh_tty_parse_modes(ssh, s->ttyfd);
1966 if ((r = sshpkt_get_end(ssh)) != 0)
1967 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1970 pty_setowner(s->pw, s->tty);
1972 /* Set window size from the packet. */
1973 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1975 session_proctitle(s);
1980 session_subsystem_req(struct ssh *ssh, Session *s)
1987 if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 ||
1988 (r = sshpkt_get_end(ssh)) != 0)
1989 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1990 debug2("subsystem request for %.100s by user %s", s->subsys,
1993 for (i = 0; i < options.num_subsystems; i++) {
1994 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1995 prog = options.subsystem_command[i];
1996 cmd = options.subsystem_args[i];
1997 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1998 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1999 debug("subsystem: %s", prog);
2001 if (stat(prog, &st) == -1)
2002 debug("subsystem: cannot stat %s: %s",
2003 prog, strerror(errno));
2004 s->is_subsystem = SUBSYSTEM_EXT;
2005 debug("subsystem: exec() %s", cmd);
2007 success = do_exec(ssh, s, cmd) == 0;
2013 logit("subsystem request for %.100s by user %s failed, "
2014 "subsystem not found", s->subsys, s->pw->pw_name);
2020 session_x11_req(struct ssh *ssh, Session *s)
2023 u_char single_connection = 0;
2025 if (s->auth_proto != NULL || s->auth_data != NULL) {
2026 error("session_x11_req: session %d: "
2027 "x11 forwarding already active", s->self);
2030 if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 ||
2031 (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 ||
2032 (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 ||
2033 (r = sshpkt_get_u32(ssh, &s->screen)) != 0 ||
2034 (r = sshpkt_get_end(ssh)) != 0)
2035 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2037 s->single_connection = single_connection;
2039 if (xauth_valid_string(s->auth_proto) &&
2040 xauth_valid_string(s->auth_data))
2041 success = session_setup_x11fwd(ssh, s);
2044 error("Invalid X11 forwarding data");
2047 free(s->auth_proto);
2049 s->auth_proto = NULL;
2050 s->auth_data = NULL;
2056 session_shell_req(struct ssh *ssh, Session *s)
2060 if ((r = sshpkt_get_end(ssh)) != 0)
2061 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2062 return do_exec(ssh, s, NULL) == 0;
2066 session_exec_req(struct ssh *ssh, Session *s)
2070 char *command = NULL;
2072 if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 ||
2073 (r = sshpkt_get_end(ssh)) != 0)
2074 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2076 success = do_exec(ssh, s, command) == 0;
2082 session_break_req(struct ssh *ssh, Session *s)
2086 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */
2087 (r = sshpkt_get_end(ssh)) != 0)
2088 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2090 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) == -1)
2096 session_env_req(struct ssh *ssh, Session *s)
2102 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
2103 (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 ||
2104 (r = sshpkt_get_end(ssh)) != 0)
2105 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2107 /* Don't set too many environment variables */
2108 if (s->num_env > 128) {
2109 debug2("Ignoring env request %s: too many env vars", name);
2113 for (i = 0; i < options.num_accept_env; i++) {
2114 if (match_pattern(name, options.accept_env[i])) {
2115 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2116 s->env = xrecallocarray(s->env, s->num_env,
2117 s->num_env + 1, sizeof(*s->env));
2118 s->env[s->num_env].name = name;
2119 s->env[s->num_env].val = val;
2124 debug2("Ignoring env request %s: disallowed name", name);
2133 * Conversion of signals from ssh channel request names.
2134 * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
2138 name2sig(char *name)
2140 #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
2150 if (strcmp(name, "INFO@openssh.com") == 0)
2157 session_signal_req(struct ssh *ssh, Session *s)
2159 char *signame = NULL;
2160 int r, sig, success = 0;
2162 if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
2163 (r = sshpkt_get_end(ssh)) != 0) {
2164 error_fr(r, "parse");
2167 if ((sig = name2sig(signame)) == -1) {
2168 error_f("unsupported signal \"%s\"", signame);
2172 error_f("no pid for session %d", s->self);
2175 if (s->forced || s->is_subsystem) {
2176 error_f("refusing to send signal %s to %s session",
2177 signame, s->forced ? "forced-command" : "subsystem");
2180 if (!use_privsep || mm_is_monitor()) {
2181 error_f("session signalling requires privilege separation");
2185 debug_f("signal %s, killpg(%ld, %d)", signame, (long)s->pid, sig);
2186 temporarily_use_uid(s->pw);
2187 r = killpg(s->pid, sig);
2190 error_f("killpg(%ld, %d): %s", (long)s->pid,
2191 sig, strerror(errno));
2203 session_auth_agent_req(struct ssh *ssh, Session *s)
2205 static int called = 0;
2208 if ((r = sshpkt_get_end(ssh)) != 0)
2209 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2210 if (!auth_opts->permit_agent_forwarding_flag ||
2211 !options.allow_agent_forwarding) {
2212 debug_f("agent forwarding disabled");
2219 return auth_input_request_forwarding(ssh, s->pw);
2224 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2229 if ((s = session_by_channel(c->self)) == NULL) {
2230 logit_f("no session %d req %.100s", c->self, rtype);
2233 debug_f("session %d req %s", s->self, rtype);
2236 * a session is in LARVAL state until a shell, a command
2237 * or a subsystem is executed
2239 if (c->type == SSH_CHANNEL_LARVAL) {
2240 if (strcmp(rtype, "shell") == 0) {
2241 success = session_shell_req(ssh, s);
2242 } else if (strcmp(rtype, "exec") == 0) {
2243 success = session_exec_req(ssh, s);
2244 } else if (strcmp(rtype, "pty-req") == 0) {
2245 success = session_pty_req(ssh, s);
2246 } else if (strcmp(rtype, "x11-req") == 0) {
2247 success = session_x11_req(ssh, s);
2248 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2249 success = session_auth_agent_req(ssh, s);
2250 } else if (strcmp(rtype, "subsystem") == 0) {
2251 success = session_subsystem_req(ssh, s);
2252 } else if (strcmp(rtype, "env") == 0) {
2253 success = session_env_req(ssh, s);
2256 if (strcmp(rtype, "window-change") == 0) {
2257 success = session_window_change_req(ssh, s);
2258 } else if (strcmp(rtype, "break") == 0) {
2259 success = session_break_req(ssh, s);
2260 } else if (strcmp(rtype, "signal") == 0) {
2261 success = session_signal_req(ssh, s);
2268 session_set_fds(struct ssh *ssh, Session *s,
2269 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2272 * now that have a child and a pipe to the child,
2273 * we can activate our channel and register the fd's
2275 if (s->chanid == -1)
2276 fatal("no channel for session %d", s->self);
2277 channel_set_fds(ssh, s->chanid,
2279 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2280 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2284 * Function to perform pty cleanup. Also called if we get aborted abnormally
2285 * (e.g., due to a dropped connection).
2288 session_pty_cleanup2(Session *s)
2291 error_f("no session");
2297 debug_f("session %d release %s", s->self, s->tty);
2299 /* Record that the user has logged out. */
2301 record_logout(s->pid, s->tty, s->pw->pw_name);
2303 /* Release the pseudo-tty. */
2305 pty_release(s->tty);
2308 * Close the server side of the socket pairs. We must do this after
2309 * the pty cleanup, so that another process doesn't get this pty
2310 * while we're still cleaning up.
2312 if (s->ptymaster != -1 && close(s->ptymaster) == -1)
2313 error("close(s->ptymaster/%d): %s",
2314 s->ptymaster, strerror(errno));
2316 /* unlink pty from session */
2321 session_pty_cleanup(Session *s)
2323 PRIVSEP(session_pty_cleanup2(s));
2329 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2344 return "SIG@openssh.com";
2348 session_close_x11(struct ssh *ssh, int id)
2352 if ((c = channel_by_id(ssh, id)) == NULL) {
2353 debug_f("x11 channel %d missing", id);
2355 /* Detach X11 listener */
2356 debug_f("detach x11 channel %d", id);
2357 channel_cancel_cleanup(ssh, id);
2358 if (c->ostate != CHAN_OUTPUT_CLOSED)
2359 chan_mark_dead(ssh, c);
2364 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2369 debug3_f("channel %d", id);
2370 channel_cancel_cleanup(ssh, id);
2371 if ((s = session_by_x11_channel(id)) == NULL)
2372 fatal_f("no x11 channel %d", id);
2373 for (i = 0; s->x11_chanids[i] != -1; i++) {
2374 debug_f("session %d: closing channel %d",
2375 s->self, s->x11_chanids[i]);
2377 * The channel "id" is already closing, but make sure we
2378 * close all of its siblings.
2380 if (s->x11_chanids[i] != id)
2381 session_close_x11(ssh, s->x11_chanids[i]);
2383 free(s->x11_chanids);
2384 s->x11_chanids = NULL;
2387 free(s->auth_proto);
2388 s->auth_proto = NULL;
2390 s->auth_data = NULL;
2391 free(s->auth_display);
2392 s->auth_display = NULL;
2396 session_exit_message(struct ssh *ssh, Session *s, int status)
2401 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2402 fatal_f("session %d: no channel %d", s->self, s->chanid);
2403 debug_f("session %d channel %d pid %ld",
2404 s->self, s->chanid, (long)s->pid);
2406 if (WIFEXITED(status)) {
2407 channel_request_start(ssh, s->chanid, "exit-status", 0);
2408 if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 ||
2409 (r = sshpkt_send(ssh)) != 0)
2410 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2411 } else if (WIFSIGNALED(status)) {
2412 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2414 # define WCOREDUMP(x) (0)
2416 if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 ||
2417 (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 ||
2418 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2419 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2420 (r = sshpkt_send(ssh)) != 0)
2421 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2423 /* Some weird exit cause. Just exit. */
2424 ssh_packet_disconnect(ssh, "wait returned status %04x.", status);
2427 /* disconnect channel */
2428 debug_f("release channel %d", s->chanid);
2431 * Adjust cleanup callback attachment to send close messages when
2432 * the channel gets EOF. The session will be then be closed
2433 * by session_close_by_channel when the child sessions close their fds.
2435 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2438 * emulate a write failure with 'chan_write_failed', nobody will be
2439 * interested in data we write.
2440 * Note that we must not call 'chan_read_failed', since there could
2441 * be some more data waiting in the pipe.
2443 if (c->ostate != CHAN_OUTPUT_CLOSED)
2444 chan_write_failed(ssh, c);
2448 session_close(struct ssh *ssh, Session *s)
2452 verbose("Close session: user %s from %.200s port %d id %d",
2454 ssh_remote_ipaddr(ssh),
2455 ssh_remote_port(ssh),
2459 session_pty_cleanup(s);
2462 free(s->x11_chanids);
2463 free(s->auth_display);
2465 free(s->auth_proto);
2467 if (s->env != NULL) {
2468 for (i = 0; i < s->num_env; i++) {
2469 free(s->env[i].name);
2470 free(s->env[i].val);
2474 session_proctitle(s);
2475 session_unused(s->self);
2479 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2481 Session *s = session_by_pid(pid);
2483 debug_f("no session for pid %ld", (long)pid);
2486 if (s->chanid != -1)
2487 session_exit_message(ssh, s, status);
2489 session_pty_cleanup(s);
2494 * this is called when a channel dies before
2495 * the session 'child' itself dies
2498 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2500 Session *s = session_by_channel(id);
2504 debug_f("no session for id %d", id);
2507 debug_f("channel %d child %ld", id, (long)s->pid);
2509 debug_f("channel %d: has child, ttyfd %d", id, s->ttyfd);
2511 * delay detach of session, but release pty, since
2512 * the fd's to the child are already closed
2515 session_pty_cleanup(s);
2518 /* detach by removing callback */
2519 channel_cancel_cleanup(ssh, s->chanid);
2521 /* Close any X11 listeners associated with this session */
2522 if (s->x11_chanids != NULL) {
2523 for (i = 0; s->x11_chanids[i] != -1; i++) {
2524 session_close_x11(ssh, s->x11_chanids[i]);
2525 s->x11_chanids[i] = -1;
2530 session_close(ssh, s);
2534 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2537 for (i = 0; i < sessions_nalloc; i++) {
2538 Session *s = &sessions[i];
2540 if (closefunc != NULL)
2543 session_close(ssh, s);
2549 session_tty_list(void)
2551 static char buf[1024];
2556 for (i = 0; i < sessions_nalloc; i++) {
2557 Session *s = &sessions[i];
2558 if (s->used && s->ttyfd != -1) {
2560 if (strncmp(s->tty, "/dev/", 5) != 0) {
2561 cp = strrchr(s->tty, '/');
2562 cp = (cp == NULL) ? s->tty : cp + 1;
2567 strlcat(buf, ",", sizeof buf);
2568 strlcat(buf, cp, sizeof buf);
2572 strlcpy(buf, "notty", sizeof buf);
2577 session_proctitle(Session *s)
2580 error("no user for session %d", s->self);
2582 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2586 session_setup_x11fwd(struct ssh *ssh, Session *s)
2589 char display[512], auth_display[512];
2590 char hostname[NI_MAXHOST];
2593 if (!auth_opts->permit_x11_forwarding_flag) {
2594 ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options.");
2597 if (!options.x11_forwarding) {
2598 debug("X11 forwarding disabled in server configuration file.");
2601 if (options.xauth_location == NULL ||
2602 (stat(options.xauth_location, &st) == -1)) {
2603 ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11.");
2606 if (s->display != NULL) {
2607 debug("X11 display already set.");
2610 if (x11_create_display_inet(ssh, options.x11_display_offset,
2611 options.x11_use_localhost, s->single_connection,
2612 &s->display_number, &s->x11_chanids) == -1) {
2613 debug("x11_create_display_inet failed.");
2616 for (i = 0; s->x11_chanids[i] != -1; i++) {
2617 channel_register_cleanup(ssh, s->x11_chanids[i],
2618 session_close_single_x11, 0);
2621 /* Set up a suitable value for the DISPLAY variable. */
2622 if (gethostname(hostname, sizeof(hostname)) == -1)
2623 fatal("gethostname: %.100s", strerror(errno));
2625 * auth_display must be used as the displayname when the
2626 * authorization entry is added with xauth(1). This will be
2627 * different than the DISPLAY string for localhost displays.
2629 if (options.x11_use_localhost) {
2630 snprintf(display, sizeof display, "localhost:%u.%u",
2631 s->display_number, s->screen);
2632 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2633 s->display_number, s->screen);
2634 s->display = xstrdup(display);
2635 s->auth_display = xstrdup(auth_display);
2637 #ifdef IPADDR_IN_DISPLAY
2639 struct in_addr my_addr;
2641 he = gethostbyname(hostname);
2643 error("Can't get IP address for X11 DISPLAY.");
2644 ssh_packet_send_debug(ssh, "Can't get IP address for X11 DISPLAY.");
2647 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2648 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2649 s->display_number, s->screen);
2651 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2652 s->display_number, s->screen);
2654 s->display = xstrdup(display);
2655 s->auth_display = xstrdup(display);
2662 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2664 server_loop2(ssh, authctxt);
2668 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2670 static int called = 0;
2672 debug("do_cleanup");
2674 /* no cleanup if we're in the child for login shell */
2678 /* avoid double cleanup */
2683 if (authctxt == NULL)
2687 if (options.use_pam) {
2689 sshpam_thread_cleanup();
2693 if (!authctxt->authenticated)
2697 if (options.kerberos_ticket_cleanup &&
2699 krb5_cleanup_proc(authctxt);
2703 if (options.gss_cleanup_creds)
2704 ssh_gssapi_cleanup_creds();
2707 /* remove agent socket */
2708 auth_sock_cleanup_proc(authctxt->pw);
2710 /* remove userauth info */
2711 if (auth_info_file != NULL) {
2712 temporarily_use_uid(authctxt->pw);
2713 unlink(auth_info_file);
2715 free(auth_info_file);
2716 auth_info_file = NULL;
2720 * Cleanup ptys/utmp only if privsep is disabled,
2721 * or if running in monitor.
2723 if (!use_privsep || mm_is_monitor())
2724 session_destroy_all(ssh, session_pty_cleanup2);
2727 /* Return a name for the remote host that fits inside utmp_size */
2730 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2732 const char *remote = "";
2735 remote = auth_get_canonical_hostname(ssh, use_dns);
2736 if (utmp_size == 0 || strlen(remote) > utmp_size)
2737 remote = ssh_remote_ipaddr(ssh);