1 /* $OpenBSD: session.c,v 1.330 2022/02/08 08:59:12 dtucker 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 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
42 #include <sys/socket.h>
46 #include <arpa/inet.h>
65 #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 *);
126 int check_quietlogin(Session *, const char *);
128 static void do_authenticated2(struct ssh *, Authctxt *);
130 static int session_pty_req(struct ssh *, Session *);
133 extern ServerOptions options;
134 extern char *__progname;
135 extern int debug_flag;
136 extern u_int utmp_len;
137 extern int startup_pipe;
138 extern void destroy_sensitive_data(void);
139 extern struct sshbuf *loginmsg;
140 extern struct sshauthopt *auth_opts;
141 extern char *tun_fwd_ifnames; /* serverloop.c */
143 /* original command from peer. */
144 const char *original_command = NULL;
147 static int sessions_first_unused = -1;
148 static int sessions_nalloc = 0;
149 static Session *sessions = NULL;
151 #define SUBSYSTEM_NONE 0
152 #define SUBSYSTEM_EXT 1
153 #define SUBSYSTEM_INT_SFTP 2
154 #define SUBSYSTEM_INT_SFTP_ERROR 3
156 #ifdef HAVE_LOGIN_CAP
160 static int is_child = 0;
161 static int in_chroot = 0;
163 /* File containing userauth info, if ExposeAuthInfo set */
164 static char *auth_info_file = NULL;
166 /* Name and directory of socket for authentication agent forwarding. */
167 static char *auth_sock_name = NULL;
168 static char *auth_sock_dir = NULL;
170 /* removes the agent forwarding socket */
173 auth_sock_cleanup_proc(struct passwd *pw)
175 if (auth_sock_name != NULL) {
176 temporarily_use_uid(pw);
177 unlink(auth_sock_name);
178 rmdir(auth_sock_dir);
179 auth_sock_name = NULL;
185 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
190 if (auth_sock_name != NULL) {
191 error("authentication forwarding requested twice.");
195 /* Temporarily drop privileged uid for mkdir/bind. */
196 temporarily_use_uid(pw);
198 /* Allocate a buffer for the socket name, and format the name. */
199 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
201 /* Create private directory for socket */
202 if (mkdtemp(auth_sock_dir) == NULL) {
203 ssh_packet_send_debug(ssh, "Agent forwarding disabled: "
204 "mkdtemp() failed: %.100s", strerror(errno));
207 auth_sock_dir = NULL;
211 xasprintf(&auth_sock_name, "%s/agent.%ld",
212 auth_sock_dir, (long) getpid());
214 /* Start a Unix listener on auth_sock_name. */
215 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
217 /* Restore the privileged uid. */
220 /* Check for socket/bind/listen failure. */
224 /* Allocate a channel for the authentication agent socket. */
225 nc = channel_new(ssh, "auth socket",
226 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
227 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
228 0, "auth socket", 1);
229 nc->path = xstrdup(auth_sock_name);
233 free(auth_sock_name);
234 if (auth_sock_dir != NULL) {
235 temporarily_use_uid(pw);
236 rmdir(auth_sock_dir);
242 auth_sock_name = NULL;
243 auth_sock_dir = NULL;
248 display_loginmsg(void)
252 if (sshbuf_len(loginmsg) == 0)
254 if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
255 fatal_fr(r, "sshbuf_put_u8");
256 printf("%s", (char *)sshbuf_ptr(loginmsg));
257 sshbuf_reset(loginmsg);
261 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
263 int fd = -1, success = 0;
265 if (!options.expose_userauth_info || info == NULL)
268 temporarily_use_uid(pw);
269 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
270 if ((fd = mkstemp(auth_info_file)) == -1) {
271 error_f("mkstemp: %s", strerror(errno));
274 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
275 sshbuf_len(info)) != sshbuf_len(info)) {
276 error_f("write: %s", strerror(errno));
279 if (close(fd) != 0) {
280 error_f("close: %s", strerror(errno));
288 free(auth_info_file);
289 auth_info_file = NULL;
295 set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
297 char *tmp, *cp, *host;
301 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
302 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
303 for (i = 0; i < auth_opts->npermitopen; i++) {
304 tmp = cp = xstrdup(auth_opts->permitopen[i]);
305 /* This shouldn't fail as it has already been checked */
306 if ((host = hpdelim2(&cp, NULL)) == NULL)
307 fatal_f("internal error: hpdelim");
308 host = cleanhostname(host);
309 if (cp == NULL || (port = permitopen_port(cp)) < 0)
310 fatal_f("internal error: permitopen port");
311 channel_add_permission(ssh,
312 FORWARD_USER, FORWARD_LOCAL, host, port);
316 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
317 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
318 for (i = 0; i < auth_opts->npermitlisten; i++) {
319 tmp = cp = xstrdup(auth_opts->permitlisten[i]);
320 /* This shouldn't fail as it has already been checked */
321 if ((host = hpdelim(&cp)) == NULL)
322 fatal_f("internal error: hpdelim");
323 host = cleanhostname(host);
324 if (cp == NULL || (port = permitopen_port(cp)) < 0)
325 fatal_f("internal error: permitlisten port");
326 channel_add_permission(ssh,
327 FORWARD_USER, FORWARD_REMOTE, host, port);
334 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
336 setproctitle("%s", authctxt->pw->pw_name);
338 auth_log_authopts("active", auth_opts, 0);
340 /* setup the channel layer */
341 /* XXX - streamlocal? */
342 set_fwdpermit_from_authopts(ssh, auth_opts);
344 if (!auth_opts->permit_port_forwarding_flag ||
345 options.disable_forwarding) {
346 channel_disable_admin(ssh, FORWARD_LOCAL);
347 channel_disable_admin(ssh, FORWARD_REMOTE);
349 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
350 channel_disable_admin(ssh, FORWARD_LOCAL);
352 channel_permit_all(ssh, FORWARD_LOCAL);
353 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
354 channel_disable_admin(ssh, FORWARD_REMOTE);
356 channel_permit_all(ssh, FORWARD_REMOTE);
358 auth_debug_send(ssh);
360 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
362 do_authenticated2(ssh, authctxt);
364 do_cleanup(ssh, authctxt);
367 /* Check untrusted xauth strings for metacharacters */
369 xauth_valid_string(const char *s)
373 for (i = 0; s[i] != '\0'; i++) {
374 if (!isalnum((u_char)s[i]) &&
375 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
376 s[i] != '-' && s[i] != '_')
384 * This is called to fork and execute a command when we have no tty. This
385 * will call do_child from the child, and server_loop from the parent after
386 * setting up file descriptors and such.
389 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
393 int pin[2], pout[2], perr[2];
396 fatal("do_exec_no_pty: no session");
398 /* Allocate pipes for communicating with the program. */
399 if (pipe(pin) == -1) {
400 error_f("pipe in: %.100s", strerror(errno));
403 if (pipe(pout) == -1) {
404 error_f("pipe out: %.100s", strerror(errno));
409 if (pipe(perr) == -1) {
410 error_f("pipe err: %.100s", strerror(errno));
418 int inout[2], err[2];
421 fatal("do_exec_no_pty: no session");
423 /* Uses socket pairs to communicate with the program. */
424 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) {
425 error_f("socketpair #1: %.100s", strerror(errno));
428 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) == -1) {
429 error_f("socketpair #2: %.100s", strerror(errno));
436 session_proctitle(s);
438 /* Fork the child. */
439 switch ((pid = fork())) {
441 error_f("fork: %.100s", strerror(errno));
460 * Create a new session and process group since the 4.4BSD
461 * setlogin() affects the entire process group.
464 error("setsid failed: %.100s", strerror(errno));
468 * Redirect stdin. We close the parent side of the socket
469 * pair, and make the child side the standard input.
472 if (dup2(pin[0], 0) == -1)
473 perror("dup2 stdin");
476 /* Redirect stdout. */
478 if (dup2(pout[1], 1) == -1)
479 perror("dup2 stdout");
482 /* Redirect stderr. */
484 if (dup2(perr[1], 2) == -1)
485 perror("dup2 stderr");
489 * Redirect stdin, stdout, and stderr. Stdin and stdout will
490 * use the same socket, as some programs (particularly rdist)
491 * seem to depend on it.
495 if (dup2(inout[0], 0) == -1) /* stdin */
496 perror("dup2 stdin");
497 if (dup2(inout[0], 1) == -1) /* stdout (same as stdin) */
498 perror("dup2 stdout");
500 if (dup2(err[0], 2) == -1) /* stderr */
501 perror("dup2 stderr");
505 /* Do processing for the child (exec command etc). */
506 do_child(ssh, s, command);
513 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
517 /* Set interactive/non-interactive mode. */
518 ssh_packet_set_interactive(ssh, s->display != NULL,
519 options.ip_qos_interactive, options.ip_qos_bulk);
522 * Clear loginmsg, since it's the child's responsibility to display
523 * it to the user, otherwise multiple sessions may accumulate
524 * multiple copies of the login messages.
526 sshbuf_reset(loginmsg);
529 /* We are the parent. Close the child sides of the pipes. */
534 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
537 /* We are the parent. Close the child sides of the socket pairs. */
542 * Enter the interactive session. Note: server_loop must be able to
543 * handle the case that fdin and fdout are the same.
545 session_set_fds(ssh, s, inout[1], inout[1], err[1],
552 * This is called to fork and execute a command when we have a tty. This
553 * will call do_child from the child, and server_loop from the parent after
554 * setting up file descriptors, controlling tty, updating wtmp, utmp,
555 * lastlog, and other such operations.
558 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
560 int fdout, ptyfd, ttyfd, ptymaster;
564 fatal("do_exec_pty: no session");
569 * Create another descriptor of the pty master side for use as the
570 * standard input. We could use the original descriptor, but this
571 * simplifies code in server_loop. The descriptor is bidirectional.
572 * Do this before forking (and cleanup in the child) so as to
573 * detect and gracefully fail out-of-fd conditions.
575 if ((fdout = dup(ptyfd)) == -1) {
576 error_f("dup #1: %s", strerror(errno));
581 /* we keep a reference to the pty master */
582 if ((ptymaster = dup(ptyfd)) == -1) {
583 error_f("dup #2: %s", strerror(errno));
590 /* Fork the child. */
591 switch ((pid = fork())) {
593 error_f("fork: %.100s", strerror(errno));
605 /* Close the master side of the pseudo tty. */
608 /* Make the pseudo tty our controlling tty. */
609 pty_make_controlling_tty(&ttyfd, s->tty);
611 /* Redirect stdin/stdout/stderr from the pseudo tty. */
612 if (dup2(ttyfd, 0) == -1)
613 error("dup2 stdin: %s", strerror(errno));
614 if (dup2(ttyfd, 1) == -1)
615 error("dup2 stdout: %s", strerror(errno));
616 if (dup2(ttyfd, 2) == -1)
617 error("dup2 stderr: %s", strerror(errno));
619 /* Close the extra descriptor for the pseudo tty. */
622 /* record login, etc. similar to login(1) */
624 do_login(ssh, s, command);
627 * Do common processing for the child, such as execing
630 do_child(ssh, s, command);
637 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
642 /* Parent. Close the slave side of the pseudo tty. */
645 /* Enter interactive session. */
646 s->ptymaster = ptymaster;
647 ssh_packet_set_interactive(ssh, 1,
648 options.ip_qos_interactive, options.ip_qos_bulk);
649 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
654 * This is called to fork and execute a command. If another command is
655 * to be forced, execute that instead.
658 do_exec(struct ssh *ssh, Session *s, const char *command)
661 const char *forced = NULL, *tty = NULL;
662 char session_type[1024];
664 if (options.adm_forced_command) {
665 original_command = command;
666 command = options.adm_forced_command;
668 } else if (auth_opts->force_command != NULL) {
669 original_command = command;
670 command = auth_opts->force_command;
671 forced = "(key-option)";
674 if (forced != NULL) {
676 if (IS_INTERNAL_SFTP(command)) {
677 s->is_subsystem = s->is_subsystem ?
678 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
679 } else if (s->is_subsystem)
680 s->is_subsystem = SUBSYSTEM_EXT;
681 snprintf(session_type, sizeof(session_type),
682 "forced-command %s '%.900s'", forced, command);
683 } else if (s->is_subsystem) {
684 snprintf(session_type, sizeof(session_type),
685 "subsystem '%.900s'", s->subsys);
686 } else if (command == NULL) {
687 snprintf(session_type, sizeof(session_type), "shell");
689 /* NB. we don't log unforced commands to preserve privacy */
690 snprintf(session_type, sizeof(session_type), "command");
693 if (s->ttyfd != -1) {
695 if (strncmp(tty, "/dev/", 5) == 0)
699 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
701 tty == NULL ? "" : " on ",
702 tty == NULL ? "" : tty,
704 ssh_remote_ipaddr(ssh),
705 ssh_remote_port(ssh),
708 #ifdef SSH_AUDIT_EVENTS
710 PRIVSEP(audit_run_command(command));
711 else if (s->ttyfd == -1) {
712 char *shell = s->pw->pw_shell;
714 if (shell[0] == '\0') /* empty shell means /bin/sh */
716 PRIVSEP(audit_run_command(shell));
720 ret = do_exec_pty(ssh, s, command);
722 ret = do_exec_no_pty(ssh, s, command);
724 original_command = NULL;
727 * Clear loginmsg: it's the child's responsibility to display
728 * it to the user, otherwise multiple sessions may accumulate
729 * multiple copies of the login messages.
731 sshbuf_reset(loginmsg);
736 /* administrative, login(1)-like work */
738 do_login(struct ssh *ssh, Session *s, const char *command)
741 struct sockaddr_storage from;
742 struct passwd * pw = s->pw;
743 pid_t pid = getpid();
746 * Get IP address of client. If the connection is not a socket, let
747 * the address be 0.0.0.0.
749 memset(&from, 0, sizeof(from));
750 fromlen = sizeof(from);
751 if (ssh_packet_connection_is_on_socket(ssh)) {
752 if (getpeername(ssh_packet_get_connection_in(ssh),
753 (struct sockaddr *)&from, &fromlen) == -1) {
754 debug("getpeername: %.100s", strerror(errno));
759 /* Record that there was a login on that tty from the remote host. */
761 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
762 session_get_remote_name_or_ip(ssh, utmp_len,
764 (struct sockaddr *)&from, fromlen);
768 * If password change is needed, do it now.
769 * This needs to occur before the ~/.hushlogin check.
771 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
774 s->authctxt->force_pwchange = 0;
775 /* XXX - signal [net] parent to enable forwardings */
779 if (check_quietlogin(s, command))
788 * Display the message of the day.
796 if (options.print_motd) {
797 #ifdef HAVE_LOGIN_CAP
798 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
801 f = fopen("/etc/motd", "r");
804 while (fgets(buf, sizeof(buf), f))
813 * Check for quiet login, either .hushlogin or command given.
816 check_quietlogin(Session *s, const char *command)
819 struct passwd *pw = s->pw;
822 /* Return 1 if .hushlogin exists or a command given. */
825 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
826 #ifdef HAVE_LOGIN_CAP
827 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
830 if (stat(buf, &st) >= 0)
837 * Reads environment variables from the given file and adds/overrides them
838 * into the environment. If the file does not exist, this does nothing.
839 * Otherwise, it must consist of empty lines, comments (line starts with '#')
840 * and assignments of the form name=value. No other forms are allowed.
841 * If allowlist is not NULL, then it is interpreted as a pattern list and
842 * only variable names that match it will be accepted.
845 read_environment_file(char ***env, u_int *envsize,
846 const char *filename, const char *allowlist)
849 char *line = NULL, *cp, *value;
853 f = fopen(filename, "r");
857 while (getline(&line, &linesize, f) != -1) {
859 fatal("Too many lines in environment file %s", filename);
860 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
862 if (!*cp || *cp == '#' || *cp == '\n')
865 cp[strcspn(cp, "\n")] = '\0';
867 value = strchr(cp, '=');
869 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
874 * Replace the equals sign by nul, and advance value to
879 if (allowlist != NULL &&
880 match_pattern_list(cp, allowlist, 0) != 1)
882 child_set_env(env, envsize, cp, value);
888 #ifdef HAVE_ETC_DEFAULT_LOGIN
890 * Return named variable from specified environment, or NULL if not present.
893 child_get_env(char **env, const char *name)
899 for (i=0; env[i] != NULL; i++)
900 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
901 return(env[i] + len + 1);
906 * Read /etc/default/login.
907 * We pick up the PATH (or SUPATH for root) and UMASK.
910 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
912 char **tmpenv = NULL, *var;
913 u_int i, tmpenvsize = 0;
917 * We don't want to copy the whole file to the child's environment,
918 * so we use a temporary environment and copy the variables we're
921 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
922 options.permit_user_env_allowlist);
928 var = child_get_env(tmpenv, "SUPATH");
930 var = child_get_env(tmpenv, "PATH");
932 child_set_env(env, envsize, "PATH", var);
934 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
935 if (sscanf(var, "%5lo", &mask) == 1)
938 for (i = 0; tmpenv[i] != NULL; i++)
942 #endif /* HAVE_ETC_DEFAULT_LOGIN */
944 #if defined(USE_PAM) || defined(HAVE_CYGWIN)
946 copy_environment_denylist(char **source, char ***env, u_int *envsize,
947 const char *denylist)
949 char *var_name, *var_val;
955 for(i = 0; source[i] != NULL; i++) {
956 var_name = xstrdup(source[i]);
957 if ((var_val = strstr(var_name, "=")) == NULL) {
963 if (denylist == NULL ||
964 match_pattern_list(var_name, denylist, 0) != 1) {
965 debug3("Copy environment: %s=%s", var_name, var_val);
966 child_set_env(env, envsize, var_name, var_val);
972 #endif /* defined(USE_PAM) || defined(HAVE_CYGWIN) */
976 copy_environment(char **source, char ***env, u_int *envsize)
978 copy_environment_denylist(source, env, envsize, NULL);
983 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
988 char *ocp, *cp, *value, **env, *laddr;
989 struct passwd *pw = s->pw;
990 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
993 extern char **environ;
994 char **senv, **var, *val;
997 /* Initialize the environment. */
999 env = xcalloc(envsize, sizeof(char *));
1004 * The Windows environment contains some setting which are
1005 * important for a running system. They must not be dropped.
1010 p = fetch_windows_environment();
1011 copy_environment(p, &env, &envsize);
1012 free_windows_environment(p);
1017 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1020 /* Allow any GSSAPI methods that we've used to alter
1021 * the child's environment as they see fit
1023 ssh_gssapi_do_child(&env, &envsize);
1026 /* Set basic environment. */
1027 for (i = 0; i < s->num_env; i++)
1028 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1030 child_set_env(&env, &envsize, "USER", pw->pw_name);
1031 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1033 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1035 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1036 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1037 child_set_env(&env, &envsize, "MAIL", buf);
1038 #ifdef HAVE_LOGIN_CAP
1039 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1040 child_set_env(&env, &envsize, "TERM", "su");
1042 * Temporarily swap out our real environment with an empty one,
1043 * let setusercontext() apply any environment variables defined
1044 * for the user's login class, copy those variables to the child,
1045 * free the temporary environment, and restore the original.
1048 environ = xmalloc(sizeof(*environ));
1050 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1051 for (var = environ; *var != NULL; ++var) {
1052 if ((val = strchr(*var, '=')) != NULL) {
1054 child_set_env(&env, &envsize, *var, val);
1060 #else /* HAVE_LOGIN_CAP */
1061 # ifndef HAVE_CYGWIN
1063 * There's no standard path on Windows. The path contains
1064 * important components pointing to the system directories,
1065 * needed for loading shared libraries. So the path better
1066 * remains intact here.
1068 # ifdef HAVE_ETC_DEFAULT_LOGIN
1069 read_etc_default_login(&env, &envsize, pw->pw_uid);
1070 path = child_get_env(env, "PATH");
1071 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1072 if (path == NULL || *path == '\0') {
1073 child_set_env(&env, &envsize, "PATH",
1074 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1076 # endif /* HAVE_CYGWIN */
1077 #endif /* HAVE_LOGIN_CAP */
1079 /* Normal systems set SHELL by default. */
1080 child_set_env(&env, &envsize, "SHELL", shell);
1083 child_set_env(&env, &envsize, "TERM", s->term);
1085 child_set_env(&env, &envsize, "DISPLAY", s->display);
1088 * Since we clear KRB5CCNAME at startup, if it's set now then it
1089 * must have been set by a native authentication method (eg AIX or
1090 * SIA), so copy it to the child.
1095 if ((cp = getenv("KRB5CCNAME")) != NULL)
1096 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1103 if ((cp = getenv("AUTHSTATE")) != NULL)
1104 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1105 read_environment_file(&env, &envsize, "/etc/environment",
1106 options.permit_user_env_allowlist);
1110 if (s->authctxt->krb5_ccname)
1111 child_set_env(&env, &envsize, "KRB5CCNAME",
1112 s->authctxt->krb5_ccname);
1114 if (auth_sock_name != NULL)
1115 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1119 /* Set custom environment options from pubkey authentication. */
1120 if (options.permit_user_env) {
1121 for (n = 0 ; n < auth_opts->nenv; n++) {
1122 ocp = xstrdup(auth_opts->env[n]);
1123 cp = strchr(ocp, '=');
1126 /* Apply PermitUserEnvironment allowlist */
1127 if (options.permit_user_env_allowlist == NULL ||
1128 match_pattern_list(ocp,
1129 options.permit_user_env_allowlist, 0) == 1)
1130 child_set_env(&env, &envsize,
1137 /* read $HOME/.ssh/environment. */
1138 if (options.permit_user_env) {
1139 snprintf(buf, sizeof buf, "%.200s/%s/environment",
1140 pw->pw_dir, _PATH_SSH_USER_DIR);
1141 read_environment_file(&env, &envsize, buf,
1142 options.permit_user_env_allowlist);
1147 * Pull in any environment variables that may have
1150 if (options.use_pam) {
1154 * Don't allow PAM-internal env vars to leak
1155 * back into the session environment.
1157 #define PAM_ENV_DENYLIST "SSH_AUTH_INFO*,SSH_CONNECTION*"
1158 p = fetch_pam_child_environment();
1159 copy_environment_denylist(p, &env, &envsize,
1161 free_pam_environment(p);
1163 p = fetch_pam_environment();
1164 copy_environment_denylist(p, &env, &envsize,
1166 free_pam_environment(p);
1168 #endif /* USE_PAM */
1170 /* Environment specified by admin */
1171 for (i = 0; i < options.num_setenv; i++) {
1172 cp = xstrdup(options.setenv[i]);
1173 if ((value = strchr(cp, '=')) == NULL) {
1174 /* shouldn't happen; vars are checked in servconf.c */
1175 fatal("Invalid config SetEnv: %s", options.setenv[i]);
1178 child_set_env(&env, &envsize, cp, value);
1181 /* SSH_CLIENT deprecated */
1182 snprintf(buf, sizeof buf, "%.50s %d %d",
1183 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1184 ssh_local_port(ssh));
1185 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1187 laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh));
1188 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1189 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1190 laddr, ssh_local_port(ssh));
1192 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1194 if (tun_fwd_ifnames != NULL)
1195 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1196 if (auth_info_file != NULL)
1197 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1199 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1200 if (original_command)
1201 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1205 /* dump the environment */
1206 fprintf(stderr, "Environment:\n");
1207 for (i = 0; env[i]; i++)
1208 fprintf(stderr, " %.200s\n", env[i]);
1214 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1215 * first in this order).
1218 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1221 char *cmd = NULL, *user_rc = NULL;
1226 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1227 xasprintf(&user_rc, "%s/%s", s->pw->pw_dir, _PATH_SSH_USER_RC);
1229 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1230 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1231 auth_opts->permit_user_rc && options.permit_user_rc &&
1232 stat(user_rc, &st) >= 0) {
1233 if (xasprintf(&cmd, "%s -c '%s %s'", shell, _PATH_BSHELL,
1235 fatal_f("xasprintf: %s", strerror(errno));
1237 fprintf(stderr, "Running %s\n", cmd);
1238 f = popen(cmd, "w");
1241 fprintf(f, "%s %s\n", s->auth_proto,
1245 fprintf(stderr, "Could not run %s\n",
1247 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1249 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1250 _PATH_SSH_SYSTEM_RC);
1251 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1254 fprintf(f, "%s %s\n", s->auth_proto,
1258 fprintf(stderr, "Could not run %s\n",
1259 _PATH_SSH_SYSTEM_RC);
1260 } else if (do_xauth && options.xauth_location != NULL) {
1261 /* Add authority data to .Xauthority if appropriate. */
1264 "Running %.500s remove %.100s\n",
1265 options.xauth_location, s->auth_display);
1267 "%.500s add %.100s %.100s %.100s\n",
1268 options.xauth_location, s->auth_display,
1269 s->auth_proto, s->auth_data);
1271 if (xasprintf(&cmd, "%s -q -", options.xauth_location) == -1)
1272 fatal_f("xasprintf: %s", strerror(errno));
1273 f = popen(cmd, "w");
1275 fprintf(f, "remove %s\n",
1277 fprintf(f, "add %s %s %s\n",
1278 s->auth_display, s->auth_proto,
1282 fprintf(stderr, "Could not run %s\n",
1291 do_nologin(struct passwd *pw)
1295 char buf[1024], *def_nl = _PATH_NOLOGIN;
1298 #ifdef HAVE_LOGIN_CAP
1299 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1301 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1303 if (pw->pw_uid == 0)
1307 if (stat(nl, &sb) == -1)
1310 /* /etc/nologin exists. Print its contents if we can and exit. */
1311 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1312 if ((f = fopen(nl, "r")) != NULL) {
1313 while (fgets(buf, sizeof(buf), f))
1321 * Chroot into a directory after checking it for safety: all path components
1322 * must be root-owned directories with strict permissions.
1325 safely_chroot(const char *path, uid_t uid)
1328 char component[PATH_MAX];
1331 if (!path_absolute(path))
1332 fatal("chroot path does not begin at root");
1333 if (strlen(path) >= sizeof(component))
1334 fatal("chroot path too long");
1337 * Descend the path, checking that each component is a
1338 * root-owned directory with strict permissions.
1340 for (cp = path; cp != NULL;) {
1341 if ((cp = strchr(cp, '/')) == NULL)
1342 strlcpy(component, path, sizeof(component));
1345 memcpy(component, path, cp - path);
1346 component[cp - path] = '\0';
1349 debug3_f("checking '%s'", component);
1351 if (stat(component, &st) != 0)
1352 fatal_f("stat(\"%s\"): %s",
1353 component, strerror(errno));
1354 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1355 fatal("bad ownership or modes for chroot "
1356 "directory %s\"%s\"",
1357 cp == NULL ? "" : "component ", component);
1358 if (!S_ISDIR(st.st_mode))
1359 fatal("chroot path %s\"%s\" is not a directory",
1360 cp == NULL ? "" : "component ", component);
1364 if (chdir(path) == -1)
1365 fatal("Unable to chdir to chroot path \"%s\": "
1366 "%s", path, strerror(errno));
1367 if (chroot(path) == -1)
1368 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1369 if (chdir("/") == -1)
1370 fatal_f("chdir(/) after chroot: %s", strerror(errno));
1371 verbose("Changed root directory to \"%s\"", path);
1374 /* Set login name, uid, gid, and groups. */
1376 do_setusercontext(struct passwd *pw)
1378 char uidstr[32], *chroot_path, *tmp;
1380 platform_setusercontext(pw);
1382 if (platform_privileged_uidswap()) {
1383 #ifdef HAVE_LOGIN_CAP
1384 if (setusercontext(lc, pw, pw->pw_uid,
1385 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1386 perror("unable to set user context");
1390 if (setlogin(pw->pw_name) < 0)
1391 error("setlogin failed: %s", strerror(errno));
1392 if (setgid(pw->pw_gid) < 0) {
1396 /* Initialize the group list. */
1397 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1398 perror("initgroups");
1404 platform_setusercontext_post_groups(pw);
1406 if (!in_chroot && options.chroot_directory != NULL &&
1407 strcasecmp(options.chroot_directory, "none") != 0) {
1408 tmp = tilde_expand_filename(options.chroot_directory,
1410 snprintf(uidstr, sizeof(uidstr), "%llu",
1411 (unsigned long long)pw->pw_uid);
1412 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1413 "u", pw->pw_name, "U", uidstr, (char *)NULL);
1414 safely_chroot(chroot_path, pw->pw_uid);
1417 /* Make sure we don't attempt to chroot again */
1418 free(options.chroot_directory);
1419 options.chroot_directory = NULL;
1423 #ifdef HAVE_LOGIN_CAP
1424 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1425 perror("unable to set user context (setuser)");
1429 * FreeBSD's setusercontext() will not apply the user's
1430 * own umask setting unless running with the user's UID.
1432 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1436 * In a chroot environment, the set_id() will always fail;
1437 * typically because of the lack of necessary authentication
1438 * services and runtime such as ./usr/lib/libiaf.so,
1439 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1440 * internal sftp chroot case. We'll lose auditing and ACLs but
1441 * permanently_set_uid will take care of the rest.
1443 if (!in_chroot && set_id(pw->pw_name) != 0)
1444 fatal("set_id(%s) Failed", pw->pw_name);
1445 # endif /* USE_LIBIAF */
1446 /* Permanently switch to the desired uid. */
1447 permanently_set_uid(pw);
1449 } else if (options.chroot_directory != NULL &&
1450 strcasecmp(options.chroot_directory, "none") != 0) {
1451 fatal("server lacks privileges to chroot to ChrootDirectory");
1454 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1455 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1459 do_pwchange(Session *s)
1462 fprintf(stderr, "WARNING: Your password has expired.\n");
1463 if (s->ttyfd != -1) {
1465 "You must change your password now and login again!\n");
1469 #ifdef PASSWD_NEEDS_USERNAME
1470 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1473 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1478 "Password change required but no TTY available.\n");
1484 child_close_fds(struct ssh *ssh)
1486 extern int auth_sock;
1488 if (auth_sock != -1) {
1493 if (ssh_packet_get_connection_in(ssh) ==
1494 ssh_packet_get_connection_out(ssh))
1495 close(ssh_packet_get_connection_in(ssh));
1497 close(ssh_packet_get_connection_in(ssh));
1498 close(ssh_packet_get_connection_out(ssh));
1501 * Close all descriptors related to channels. They will still remain
1502 * open in the parent.
1504 /* XXX better use close-on-exec? -markus */
1505 channel_close_all(ssh);
1508 * Close any extra file descriptors. Note that there may still be
1509 * descriptors left by system functions. They will be closed later.
1513 /* Stop directing logs to a high-numbered fd before we close it */
1514 log_redirect_stderr_to(NULL);
1517 * Close any extra open file descriptors so that we don't have them
1518 * hanging around in clients. Note that we want to do this after
1519 * initgroups, because at least on Solaris 2.3 it leaves file
1522 closefrom(STDERR_FILENO + 1);
1526 * Performs common processing for the child, such as setting up the
1527 * environment, closing extra file descriptors, setting the user and group
1528 * ids, and executing the command or shell.
1532 do_child(struct ssh *ssh, Session *s, const char *command)
1534 extern char **environ;
1535 char **env, *argv[ARGV_MAX], remote_id[512];
1536 const char *shell, *shell0;
1537 struct passwd *pw = s->pw;
1540 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1542 /* remove hostkey from the child's memory */
1543 destroy_sensitive_data();
1544 ssh_packet_clear_keys(ssh);
1546 /* Force a password change */
1547 if (s->authctxt->force_pwchange) {
1548 do_setusercontext(pw);
1549 child_close_fds(ssh);
1555 * Login(1) does this as well, and it needs uid 0 for the "-h"
1556 * switch, so we let login(1) to this for us.
1559 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1560 if (!check_quietlogin(s, command))
1562 #else /* HAVE_OSF_SIA */
1563 /* When PAM is enabled we rely on it to do the nologin check */
1564 if (!options.use_pam)
1566 do_setusercontext(pw);
1568 * PAM session modules in do_setusercontext may have
1569 * generated messages, so if this in an interactive
1570 * login then display them too.
1572 if (!check_quietlogin(s, command))
1574 #endif /* HAVE_OSF_SIA */
1577 if (options.use_pam && !is_pam_session_open()) {
1578 debug3("PAM session not opened, exiting");
1585 * Get the shell from the password data. An empty shell field is
1586 * legal, and means /bin/sh.
1588 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1591 * Make sure $SHELL points to the shell from the password file,
1592 * even if shell is overridden from login.conf
1594 env = do_setup_env(ssh, s, shell);
1596 #ifdef HAVE_LOGIN_CAP
1597 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1601 * Close the connection descriptors; note that this is the child, and
1602 * the server will still have the socket open, and it is important
1603 * that we do not shutdown it. Note that the descriptors cannot be
1604 * closed before building the environment, as we call
1605 * ssh_remote_ipaddr there.
1607 child_close_fds(ssh);
1610 * Must take new environment into use so that .ssh/rc,
1611 * /etc/ssh/sshrc and xauth are run in the proper environment.
1615 #if defined(KRB5) && defined(USE_AFS)
1617 * At this point, we check to see if AFS is active and if we have
1618 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1619 * if we can (and need to) extend the ticket into an AFS token. If
1620 * we don't do this, we run into potential problems if the user's
1621 * home directory is in AFS and it's not world-readable.
1624 if (options.kerberos_get_afs_token && k_hasafs() &&
1625 (s->authctxt->krb5_ctx != NULL)) {
1628 debug("Getting AFS token");
1632 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1633 krb5_afslog(s->authctxt->krb5_ctx,
1634 s->authctxt->krb5_fwd_ccache, cell, NULL);
1636 krb5_afslog_home(s->authctxt->krb5_ctx,
1637 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1641 /* Change current directory to the user's home directory. */
1642 if (chdir(pw->pw_dir) == -1) {
1643 /* Suppress missing homedir warning for chroot case */
1644 #ifdef HAVE_LOGIN_CAP
1645 r = login_getcapbool(lc, "requirehome", 0);
1647 if (r || !in_chroot) {
1648 fprintf(stderr, "Could not chdir to home "
1649 "directory %s: %s\n", pw->pw_dir,
1656 closefrom(STDERR_FILENO + 1);
1658 do_rc_files(ssh, s, shell);
1660 /* restore SIGPIPE for child */
1661 ssh_signal(SIGPIPE, SIG_DFL);
1663 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1664 error("Connection from %s: refusing non-sftp session",
1666 printf("This service allows sftp connections only.\n");
1669 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1670 extern int optind, optreset;
1674 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1675 args = xstrdup(command ? command : "sftp-server");
1676 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1677 if (i < ARGV_MAX - 1)
1680 optind = optreset = 1;
1681 __progname = argv[0];
1683 ssh_selinux_change_context("sftpd_t");
1685 exit(sftp_server_main(i, argv, s->pw));
1690 /* Get the last component of the shell name. */
1691 if ((shell0 = strrchr(shell, '/')) != NULL)
1697 * If we have no command, execute the shell. In this case, the shell
1698 * name to be passed in argv[0] is preceded by '-' to indicate that
1699 * this is a login shell.
1704 /* Start the shell. Set initial character to '-'. */
1707 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1708 >= sizeof(argv0) - 1) {
1714 /* Execute the shell. */
1717 execve(shell, argv, env);
1719 /* Executing the shell failed. */
1724 * Execute the command using the user's shell. This uses the -c
1725 * option to execute the command.
1727 argv[0] = (char *) shell0;
1729 argv[2] = (char *) command;
1731 execve(shell, argv, env);
1737 session_unused(int id)
1739 debug3_f("session id %d unused", id);
1740 if (id >= options.max_sessions ||
1741 id >= sessions_nalloc) {
1742 fatal_f("insane session id %d (max %d nalloc %d)",
1743 id, options.max_sessions, sessions_nalloc);
1745 memset(&sessions[id], 0, sizeof(*sessions));
1746 sessions[id].self = id;
1747 sessions[id].used = 0;
1748 sessions[id].chanid = -1;
1749 sessions[id].ptyfd = -1;
1750 sessions[id].ttyfd = -1;
1751 sessions[id].ptymaster = -1;
1752 sessions[id].x11_chanids = NULL;
1753 sessions[id].next_unused = sessions_first_unused;
1754 sessions_first_unused = id;
1762 if (sessions_first_unused == -1) {
1763 if (sessions_nalloc >= options.max_sessions)
1765 debug2_f("allocate (allocated %d max %d)",
1766 sessions_nalloc, options.max_sessions);
1767 tmp = xrecallocarray(sessions, sessions_nalloc,
1768 sessions_nalloc + 1, sizeof(*sessions));
1770 error_f("cannot allocate %d sessions",
1771 sessions_nalloc + 1);
1775 session_unused(sessions_nalloc++);
1778 if (sessions_first_unused >= sessions_nalloc ||
1779 sessions_first_unused < 0) {
1780 fatal_f("insane first_unused %d max %d nalloc %d",
1781 sessions_first_unused, options.max_sessions,
1785 s = &sessions[sessions_first_unused];
1787 fatal_f("session %d already used", sessions_first_unused);
1788 sessions_first_unused = s->next_unused;
1790 s->next_unused = -1;
1791 debug("session_new: session %d", s->self);
1800 for (i = 0; i < sessions_nalloc; i++) {
1801 Session *s = &sessions[i];
1803 debug("dump: used %d next_unused %d session %d "
1804 "channel %d pid %ld",
1814 session_open(Authctxt *authctxt, int chanid)
1816 Session *s = session_new();
1817 debug("session_open: channel %d", chanid);
1819 error("no more sessions");
1822 s->authctxt = authctxt;
1823 s->pw = authctxt->pw;
1824 if (s->pw == NULL || !authctxt->valid)
1825 fatal("no user for session %d", s->self);
1826 debug("session_open: session %d: link with channel %d", s->self, chanid);
1832 session_by_tty(char *tty)
1835 for (i = 0; i < sessions_nalloc; i++) {
1836 Session *s = &sessions[i];
1837 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1838 debug("session_by_tty: session %d tty %s", i, tty);
1842 debug("session_by_tty: unknown tty %.100s", tty);
1848 session_by_channel(int id)
1851 for (i = 0; i < sessions_nalloc; i++) {
1852 Session *s = &sessions[i];
1853 if (s->used && s->chanid == id) {
1854 debug("session_by_channel: session %d channel %d",
1859 debug("session_by_channel: unknown channel %d", id);
1865 session_by_x11_channel(int id)
1869 for (i = 0; i < sessions_nalloc; i++) {
1870 Session *s = &sessions[i];
1872 if (s->x11_chanids == NULL || !s->used)
1874 for (j = 0; s->x11_chanids[j] != -1; j++) {
1875 if (s->x11_chanids[j] == id) {
1876 debug("session_by_x11_channel: session %d "
1877 "channel %d", s->self, id);
1882 debug("session_by_x11_channel: unknown channel %d", id);
1888 session_by_pid(pid_t pid)
1891 debug("session_by_pid: pid %ld", (long)pid);
1892 for (i = 0; i < sessions_nalloc; i++) {
1893 Session *s = &sessions[i];
1894 if (s->used && s->pid == pid)
1897 error("session_by_pid: unknown pid %ld", (long)pid);
1903 session_window_change_req(struct ssh *ssh, Session *s)
1907 if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1908 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1909 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1910 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 ||
1911 (r = sshpkt_get_end(ssh)) != 0)
1912 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1913 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1918 session_pty_req(struct ssh *ssh, Session *s)
1922 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1923 debug("Allocating a pty not permitted for this connection.");
1926 if (s->ttyfd != -1) {
1927 ssh_packet_disconnect(ssh, "Protocol error: you already have a pty.");
1931 if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 ||
1932 (r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1933 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1934 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1935 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0)
1936 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1938 if (strcmp(s->term, "") == 0) {
1943 /* Allocate a pty and open it. */
1944 debug("Allocating pty.");
1945 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1951 error("session_pty_req: session %d alloc failed", s->self);
1954 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1956 ssh_tty_parse_modes(ssh, s->ttyfd);
1958 if ((r = sshpkt_get_end(ssh)) != 0)
1959 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1962 pty_setowner(s->pw, s->tty);
1964 /* Set window size from the packet. */
1965 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1967 session_proctitle(s);
1972 session_subsystem_req(struct ssh *ssh, Session *s)
1979 if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 ||
1980 (r = sshpkt_get_end(ssh)) != 0)
1981 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1982 debug2("subsystem request for %.100s by user %s", s->subsys,
1985 for (i = 0; i < options.num_subsystems; i++) {
1986 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1987 prog = options.subsystem_command[i];
1988 cmd = options.subsystem_args[i];
1989 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1990 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1991 debug("subsystem: %s", prog);
1993 if (stat(prog, &st) == -1)
1994 debug("subsystem: cannot stat %s: %s",
1995 prog, strerror(errno));
1996 s->is_subsystem = SUBSYSTEM_EXT;
1997 debug("subsystem: exec() %s", cmd);
1999 success = do_exec(ssh, s, cmd) == 0;
2005 logit("subsystem request for %.100s by user %s failed, "
2006 "subsystem not found", s->subsys, s->pw->pw_name);
2012 session_x11_req(struct ssh *ssh, Session *s)
2015 u_char single_connection = 0;
2017 if (s->auth_proto != NULL || s->auth_data != NULL) {
2018 error("session_x11_req: session %d: "
2019 "x11 forwarding already active", s->self);
2022 if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 ||
2023 (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 ||
2024 (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 ||
2025 (r = sshpkt_get_u32(ssh, &s->screen)) != 0 ||
2026 (r = sshpkt_get_end(ssh)) != 0)
2027 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2029 s->single_connection = single_connection;
2031 if (xauth_valid_string(s->auth_proto) &&
2032 xauth_valid_string(s->auth_data))
2033 success = session_setup_x11fwd(ssh, s);
2036 error("Invalid X11 forwarding data");
2039 free(s->auth_proto);
2041 s->auth_proto = NULL;
2042 s->auth_data = NULL;
2048 session_shell_req(struct ssh *ssh, Session *s)
2052 if ((r = sshpkt_get_end(ssh)) != 0)
2053 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2054 return do_exec(ssh, s, NULL) == 0;
2058 session_exec_req(struct ssh *ssh, Session *s)
2062 char *command = NULL;
2064 if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 ||
2065 (r = sshpkt_get_end(ssh)) != 0)
2066 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2068 success = do_exec(ssh, s, command) == 0;
2074 session_break_req(struct ssh *ssh, Session *s)
2078 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */
2079 (r = sshpkt_get_end(ssh)) != 0)
2080 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2082 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) == -1)
2088 session_env_req(struct ssh *ssh, Session *s)
2094 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
2095 (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 ||
2096 (r = sshpkt_get_end(ssh)) != 0)
2097 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2099 /* Don't set too many environment variables */
2100 if (s->num_env > 128) {
2101 debug2("Ignoring env request %s: too many env vars", name);
2105 for (i = 0; i < options.num_accept_env; i++) {
2106 if (match_pattern(name, options.accept_env[i])) {
2107 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2108 s->env = xrecallocarray(s->env, s->num_env,
2109 s->num_env + 1, sizeof(*s->env));
2110 s->env[s->num_env].name = name;
2111 s->env[s->num_env].val = val;
2116 debug2("Ignoring env request %s: disallowed name", name);
2125 * Conversion of signals from ssh channel request names.
2126 * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
2130 name2sig(char *name)
2132 #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
2142 if (strcmp(name, "INFO@openssh.com") == 0)
2149 session_signal_req(struct ssh *ssh, Session *s)
2151 char *signame = NULL;
2152 int r, sig, success = 0;
2154 if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
2155 (r = sshpkt_get_end(ssh)) != 0) {
2156 error_fr(r, "parse");
2159 if ((sig = name2sig(signame)) == -1) {
2160 error_f("unsupported signal \"%s\"", signame);
2164 error_f("no pid for session %d", s->self);
2167 if (s->forced || s->is_subsystem) {
2168 error_f("refusing to send signal %s to %s session",
2169 signame, s->forced ? "forced-command" : "subsystem");
2172 if (!use_privsep || mm_is_monitor()) {
2173 error_f("session signalling requires privilege separation");
2177 debug_f("signal %s, killpg(%ld, %d)", signame, (long)s->pid, sig);
2178 temporarily_use_uid(s->pw);
2179 r = killpg(s->pid, sig);
2182 error_f("killpg(%ld, %d): %s", (long)s->pid,
2183 sig, strerror(errno));
2195 session_auth_agent_req(struct ssh *ssh, Session *s)
2197 static int called = 0;
2200 if ((r = sshpkt_get_end(ssh)) != 0)
2201 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2202 if (!auth_opts->permit_agent_forwarding_flag ||
2203 !options.allow_agent_forwarding) {
2204 debug_f("agent forwarding disabled");
2211 return auth_input_request_forwarding(ssh, s->pw);
2216 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2221 if ((s = session_by_channel(c->self)) == NULL) {
2222 logit_f("no session %d req %.100s", c->self, rtype);
2225 debug_f("session %d req %s", s->self, rtype);
2228 * a session is in LARVAL state until a shell, a command
2229 * or a subsystem is executed
2231 if (c->type == SSH_CHANNEL_LARVAL) {
2232 if (strcmp(rtype, "shell") == 0) {
2233 success = session_shell_req(ssh, s);
2234 } else if (strcmp(rtype, "exec") == 0) {
2235 success = session_exec_req(ssh, s);
2236 } else if (strcmp(rtype, "pty-req") == 0) {
2237 success = session_pty_req(ssh, s);
2238 } else if (strcmp(rtype, "x11-req") == 0) {
2239 success = session_x11_req(ssh, s);
2240 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2241 success = session_auth_agent_req(ssh, s);
2242 } else if (strcmp(rtype, "subsystem") == 0) {
2243 success = session_subsystem_req(ssh, s);
2244 } else if (strcmp(rtype, "env") == 0) {
2245 success = session_env_req(ssh, s);
2248 if (strcmp(rtype, "window-change") == 0) {
2249 success = session_window_change_req(ssh, s);
2250 } else if (strcmp(rtype, "break") == 0) {
2251 success = session_break_req(ssh, s);
2252 } else if (strcmp(rtype, "signal") == 0) {
2253 success = session_signal_req(ssh, s);
2260 session_set_fds(struct ssh *ssh, Session *s,
2261 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2264 * now that have a child and a pipe to the child,
2265 * we can activate our channel and register the fd's
2267 if (s->chanid == -1)
2268 fatal("no channel for session %d", s->self);
2269 channel_set_fds(ssh, s->chanid,
2271 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2272 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2276 * Function to perform pty cleanup. Also called if we get aborted abnormally
2277 * (e.g., due to a dropped connection).
2280 session_pty_cleanup2(Session *s)
2283 error_f("no session");
2289 debug_f("session %d release %s", s->self, s->tty);
2291 /* Record that the user has logged out. */
2293 record_logout(s->pid, s->tty, s->pw->pw_name);
2295 /* Release the pseudo-tty. */
2297 pty_release(s->tty);
2300 * Close the server side of the socket pairs. We must do this after
2301 * the pty cleanup, so that another process doesn't get this pty
2302 * while we're still cleaning up.
2304 if (s->ptymaster != -1 && close(s->ptymaster) == -1)
2305 error("close(s->ptymaster/%d): %s",
2306 s->ptymaster, strerror(errno));
2308 /* unlink pty from session */
2313 session_pty_cleanup(Session *s)
2315 PRIVSEP(session_pty_cleanup2(s));
2321 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2336 return "SIG@openssh.com";
2340 session_close_x11(struct ssh *ssh, int id)
2344 if ((c = channel_by_id(ssh, id)) == NULL) {
2345 debug_f("x11 channel %d missing", id);
2347 /* Detach X11 listener */
2348 debug_f("detach x11 channel %d", id);
2349 channel_cancel_cleanup(ssh, id);
2350 if (c->ostate != CHAN_OUTPUT_CLOSED)
2351 chan_mark_dead(ssh, c);
2356 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2361 debug3_f("channel %d", id);
2362 channel_cancel_cleanup(ssh, id);
2363 if ((s = session_by_x11_channel(id)) == NULL)
2364 fatal_f("no x11 channel %d", id);
2365 for (i = 0; s->x11_chanids[i] != -1; i++) {
2366 debug_f("session %d: closing channel %d",
2367 s->self, s->x11_chanids[i]);
2369 * The channel "id" is already closing, but make sure we
2370 * close all of its siblings.
2372 if (s->x11_chanids[i] != id)
2373 session_close_x11(ssh, s->x11_chanids[i]);
2375 free(s->x11_chanids);
2376 s->x11_chanids = NULL;
2379 free(s->auth_proto);
2380 s->auth_proto = NULL;
2382 s->auth_data = NULL;
2383 free(s->auth_display);
2384 s->auth_display = NULL;
2388 session_exit_message(struct ssh *ssh, Session *s, int status)
2393 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2394 fatal_f("session %d: no channel %d", s->self, s->chanid);
2395 debug_f("session %d channel %d pid %ld",
2396 s->self, s->chanid, (long)s->pid);
2398 if (WIFEXITED(status)) {
2399 channel_request_start(ssh, s->chanid, "exit-status", 0);
2400 if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 ||
2401 (r = sshpkt_send(ssh)) != 0)
2402 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2403 } else if (WIFSIGNALED(status)) {
2404 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2406 # define WCOREDUMP(x) (0)
2408 if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 ||
2409 (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 ||
2410 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2411 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2412 (r = sshpkt_send(ssh)) != 0)
2413 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2415 /* Some weird exit cause. Just exit. */
2416 ssh_packet_disconnect(ssh, "wait returned status %04x.", status);
2419 /* disconnect channel */
2420 debug_f("release channel %d", s->chanid);
2423 * Adjust cleanup callback attachment to send close messages when
2424 * the channel gets EOF. The session will be then be closed
2425 * by session_close_by_channel when the child sessions close their fds.
2427 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2430 * emulate a write failure with 'chan_write_failed', nobody will be
2431 * interested in data we write.
2432 * Note that we must not call 'chan_read_failed', since there could
2433 * be some more data waiting in the pipe.
2435 if (c->ostate != CHAN_OUTPUT_CLOSED)
2436 chan_write_failed(ssh, c);
2440 session_close(struct ssh *ssh, Session *s)
2444 verbose("Close session: user %s from %.200s port %d id %d",
2446 ssh_remote_ipaddr(ssh),
2447 ssh_remote_port(ssh),
2451 session_pty_cleanup(s);
2454 free(s->x11_chanids);
2455 free(s->auth_display);
2457 free(s->auth_proto);
2459 if (s->env != NULL) {
2460 for (i = 0; i < s->num_env; i++) {
2461 free(s->env[i].name);
2462 free(s->env[i].val);
2466 session_proctitle(s);
2467 session_unused(s->self);
2471 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2473 Session *s = session_by_pid(pid);
2475 debug_f("no session for pid %ld", (long)pid);
2478 if (s->chanid != -1)
2479 session_exit_message(ssh, s, status);
2481 session_pty_cleanup(s);
2486 * this is called when a channel dies before
2487 * the session 'child' itself dies
2490 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2492 Session *s = session_by_channel(id);
2496 debug_f("no session for id %d", id);
2499 debug_f("channel %d child %ld", id, (long)s->pid);
2501 debug_f("channel %d: has child, ttyfd %d", id, s->ttyfd);
2503 * delay detach of session, but release pty, since
2504 * the fd's to the child are already closed
2507 session_pty_cleanup(s);
2510 /* detach by removing callback */
2511 channel_cancel_cleanup(ssh, s->chanid);
2513 /* Close any X11 listeners associated with this session */
2514 if (s->x11_chanids != NULL) {
2515 for (i = 0; s->x11_chanids[i] != -1; i++) {
2516 session_close_x11(ssh, s->x11_chanids[i]);
2517 s->x11_chanids[i] = -1;
2522 session_close(ssh, s);
2526 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2529 for (i = 0; i < sessions_nalloc; i++) {
2530 Session *s = &sessions[i];
2532 if (closefunc != NULL)
2535 session_close(ssh, s);
2541 session_tty_list(void)
2543 static char buf[1024];
2548 for (i = 0; i < sessions_nalloc; i++) {
2549 Session *s = &sessions[i];
2550 if (s->used && s->ttyfd != -1) {
2552 if (strncmp(s->tty, "/dev/", 5) != 0) {
2553 cp = strrchr(s->tty, '/');
2554 cp = (cp == NULL) ? s->tty : cp + 1;
2559 strlcat(buf, ",", sizeof buf);
2560 strlcat(buf, cp, sizeof buf);
2564 strlcpy(buf, "notty", sizeof buf);
2569 session_proctitle(Session *s)
2572 error("no user for session %d", s->self);
2574 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2578 session_setup_x11fwd(struct ssh *ssh, Session *s)
2581 char display[512], auth_display[512];
2582 char hostname[NI_MAXHOST];
2585 if (!auth_opts->permit_x11_forwarding_flag) {
2586 ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options.");
2589 if (!options.x11_forwarding) {
2590 debug("X11 forwarding disabled in server configuration file.");
2593 if (options.xauth_location == NULL ||
2594 (stat(options.xauth_location, &st) == -1)) {
2595 ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11.");
2598 if (s->display != NULL) {
2599 debug("X11 display already set.");
2602 if (x11_create_display_inet(ssh, options.x11_display_offset,
2603 options.x11_use_localhost, s->single_connection,
2604 &s->display_number, &s->x11_chanids) == -1) {
2605 debug("x11_create_display_inet failed.");
2608 for (i = 0; s->x11_chanids[i] != -1; i++) {
2609 channel_register_cleanup(ssh, s->x11_chanids[i],
2610 session_close_single_x11, 0);
2613 /* Set up a suitable value for the DISPLAY variable. */
2614 if (gethostname(hostname, sizeof(hostname)) == -1)
2615 fatal("gethostname: %.100s", strerror(errno));
2617 * auth_display must be used as the displayname when the
2618 * authorization entry is added with xauth(1). This will be
2619 * different than the DISPLAY string for localhost displays.
2621 if (options.x11_use_localhost) {
2622 snprintf(display, sizeof display, "localhost:%u.%u",
2623 s->display_number, s->screen);
2624 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2625 s->display_number, s->screen);
2626 s->display = xstrdup(display);
2627 s->auth_display = xstrdup(auth_display);
2629 #ifdef IPADDR_IN_DISPLAY
2631 struct in_addr my_addr;
2633 he = gethostbyname(hostname);
2635 error("Can't get IP address for X11 DISPLAY.");
2636 ssh_packet_send_debug(ssh, "Can't get IP address for X11 DISPLAY.");
2639 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2640 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2641 s->display_number, s->screen);
2643 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2644 s->display_number, s->screen);
2646 s->display = xstrdup(display);
2647 s->auth_display = xstrdup(display);
2654 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2656 server_loop2(ssh, authctxt);
2660 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2662 static int called = 0;
2664 debug("do_cleanup");
2666 /* no cleanup if we're in the child for login shell */
2670 /* avoid double cleanup */
2675 if (authctxt == NULL)
2679 if (options.use_pam) {
2681 sshpam_thread_cleanup();
2685 if (!authctxt->authenticated)
2689 if (options.kerberos_ticket_cleanup &&
2691 krb5_cleanup_proc(authctxt);
2695 if (options.gss_cleanup_creds)
2696 ssh_gssapi_cleanup_creds();
2699 /* remove agent socket */
2700 auth_sock_cleanup_proc(authctxt->pw);
2702 /* remove userauth info */
2703 if (auth_info_file != NULL) {
2704 temporarily_use_uid(authctxt->pw);
2705 unlink(auth_info_file);
2707 free(auth_info_file);
2708 auth_info_file = NULL;
2712 * Cleanup ptys/utmp only if privsep is disabled,
2713 * or if running in monitor.
2715 if (!use_privsep || mm_is_monitor())
2716 session_destroy_all(ssh, session_pty_cleanup2);
2719 /* Return a name for the remote host that fits inside utmp_size */
2722 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2724 const char *remote = "";
2727 remote = auth_get_canonical_hostname(ssh, use_dns);
2728 if (utmp_size == 0 || strlen(remote) > utmp_size)
2729 remote = ssh_remote_ipaddr(ssh);