1 /* $OpenBSD: session.c,v 1.307 2018/10/04 00:10:11 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 *);
127 #ifdef LOGIN_NEEDS_UTMPX
128 static void do_pre_login(Session *s);
131 int check_quietlogin(Session *, const char *);
133 static void do_authenticated2(struct ssh *, Authctxt *);
135 static int session_pty_req(struct ssh *, Session *);
138 extern ServerOptions options;
139 extern char *__progname;
140 extern int debug_flag;
141 extern u_int utmp_len;
142 extern int startup_pipe;
143 extern void destroy_sensitive_data(void);
144 extern struct sshbuf *loginmsg;
145 extern struct sshauthopt *auth_opts;
146 extern char *tun_fwd_ifnames; /* serverloop.c */
148 /* original command from peer. */
149 const char *original_command = NULL;
152 static int sessions_first_unused = -1;
153 static int sessions_nalloc = 0;
154 static Session *sessions = NULL;
156 #define SUBSYSTEM_NONE 0
157 #define SUBSYSTEM_EXT 1
158 #define SUBSYSTEM_INT_SFTP 2
159 #define SUBSYSTEM_INT_SFTP_ERROR 3
161 #ifdef HAVE_LOGIN_CAP
165 static int is_child = 0;
166 static int in_chroot = 0;
168 /* File containing userauth info, if ExposeAuthInfo set */
169 static char *auth_info_file = NULL;
171 /* Name and directory of socket for authentication agent forwarding. */
172 static char *auth_sock_name = NULL;
173 static char *auth_sock_dir = NULL;
175 /* removes the agent forwarding socket */
178 auth_sock_cleanup_proc(struct passwd *pw)
180 if (auth_sock_name != NULL) {
181 temporarily_use_uid(pw);
182 unlink(auth_sock_name);
183 rmdir(auth_sock_dir);
184 auth_sock_name = NULL;
190 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
195 if (auth_sock_name != NULL) {
196 error("authentication forwarding requested twice.");
200 /* Temporarily drop privileged uid for mkdir/bind. */
201 temporarily_use_uid(pw);
203 /* Allocate a buffer for the socket name, and format the name. */
204 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
206 /* Create private directory for socket */
207 if (mkdtemp(auth_sock_dir) == NULL) {
208 packet_send_debug("Agent forwarding disabled: "
209 "mkdtemp() failed: %.100s", strerror(errno));
212 auth_sock_dir = NULL;
216 xasprintf(&auth_sock_name, "%s/agent.%ld",
217 auth_sock_dir, (long) getpid());
219 /* Start a Unix listener on auth_sock_name. */
220 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
222 /* Restore the privileged uid. */
225 /* Check for socket/bind/listen failure. */
229 /* Allocate a channel for the authentication agent socket. */
230 nc = channel_new(ssh, "auth socket",
231 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
232 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
233 0, "auth socket", 1);
234 nc->path = xstrdup(auth_sock_name);
238 free(auth_sock_name);
239 if (auth_sock_dir != NULL) {
240 rmdir(auth_sock_dir);
245 auth_sock_name = NULL;
246 auth_sock_dir = NULL;
251 display_loginmsg(void)
255 if (sshbuf_len(loginmsg) == 0)
257 if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
258 fatal("%s: buffer error: %s", __func__, ssh_err(r));
259 printf("%s", (char *)sshbuf_ptr(loginmsg));
260 sshbuf_reset(loginmsg);
264 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
266 int fd = -1, success = 0;
268 if (!options.expose_userauth_info || info == NULL)
271 temporarily_use_uid(pw);
272 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
273 if ((fd = mkstemp(auth_info_file)) == -1) {
274 error("%s: mkstemp: %s", __func__, strerror(errno));
277 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
278 sshbuf_len(info)) != sshbuf_len(info)) {
279 error("%s: write: %s", __func__, strerror(errno));
282 if (close(fd) != 0) {
283 error("%s: close: %s", __func__, strerror(errno));
291 free(auth_info_file);
292 auth_info_file = NULL;
298 set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
300 char *tmp, *cp, *host;
304 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
305 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
306 for (i = 0; i < auth_opts->npermitopen; i++) {
307 tmp = cp = xstrdup(auth_opts->permitopen[i]);
308 /* This shouldn't fail as it has already been checked */
309 if ((host = hpdelim(&cp)) == NULL)
310 fatal("%s: internal error: hpdelim", __func__);
311 host = cleanhostname(host);
312 if (cp == NULL || (port = permitopen_port(cp)) < 0)
313 fatal("%s: internal error: permitopen port",
315 channel_add_permission(ssh,
316 FORWARD_USER, FORWARD_LOCAL, host, port);
320 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
321 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
322 for (i = 0; i < auth_opts->npermitlisten; i++) {
323 tmp = cp = xstrdup(auth_opts->permitlisten[i]);
324 /* This shouldn't fail as it has already been checked */
325 if ((host = hpdelim(&cp)) == NULL)
326 fatal("%s: internal error: hpdelim", __func__);
327 host = cleanhostname(host);
328 if (cp == NULL || (port = permitopen_port(cp)) < 0)
329 fatal("%s: internal error: permitlisten port",
331 channel_add_permission(ssh,
332 FORWARD_USER, FORWARD_REMOTE, host, port);
339 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
341 setproctitle("%s", authctxt->pw->pw_name);
343 auth_log_authopts("active", auth_opts, 0);
345 /* setup the channel layer */
346 /* XXX - streamlocal? */
347 set_fwdpermit_from_authopts(ssh, auth_opts);
349 if (!auth_opts->permit_port_forwarding_flag ||
350 options.disable_forwarding) {
351 channel_disable_admin(ssh, FORWARD_LOCAL);
352 channel_disable_admin(ssh, FORWARD_REMOTE);
354 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
355 channel_disable_admin(ssh, FORWARD_LOCAL);
357 channel_permit_all(ssh, FORWARD_LOCAL);
358 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
359 channel_disable_admin(ssh, FORWARD_REMOTE);
361 channel_permit_all(ssh, FORWARD_REMOTE);
365 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
367 do_authenticated2(ssh, authctxt);
369 do_cleanup(ssh, authctxt);
372 /* Check untrusted xauth strings for metacharacters */
374 xauth_valid_string(const char *s)
378 for (i = 0; s[i] != '\0'; i++) {
379 if (!isalnum((u_char)s[i]) &&
380 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
381 s[i] != '-' && s[i] != '_')
389 * This is called to fork and execute a command when we have no tty. This
390 * will call do_child from the child, and server_loop from the parent after
391 * setting up file descriptors and such.
394 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
398 int pin[2], pout[2], perr[2];
401 fatal("do_exec_no_pty: no session");
403 /* Allocate pipes for communicating with the program. */
405 error("%s: pipe in: %.100s", __func__, strerror(errno));
408 if (pipe(pout) < 0) {
409 error("%s: pipe out: %.100s", __func__, strerror(errno));
414 if (pipe(perr) < 0) {
415 error("%s: pipe err: %.100s", __func__,
424 int inout[2], err[2];
427 fatal("do_exec_no_pty: no session");
429 /* Uses socket pairs to communicate with the program. */
430 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
431 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
434 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
435 error("%s: socketpair #2: %.100s", __func__,
443 session_proctitle(s);
445 /* Fork the child. */
446 switch ((pid = fork())) {
448 error("%s: fork: %.100s", __func__, strerror(errno));
467 * Create a new session and process group since the 4.4BSD
468 * setlogin() affects the entire process group.
471 error("setsid failed: %.100s", strerror(errno));
475 * Redirect stdin. We close the parent side of the socket
476 * pair, and make the child side the standard input.
479 if (dup2(pin[0], 0) < 0)
480 perror("dup2 stdin");
483 /* Redirect stdout. */
485 if (dup2(pout[1], 1) < 0)
486 perror("dup2 stdout");
489 /* Redirect stderr. */
491 if (dup2(perr[1], 2) < 0)
492 perror("dup2 stderr");
496 * Redirect stdin, stdout, and stderr. Stdin and stdout will
497 * use the same socket, as some programs (particularly rdist)
498 * seem to depend on it.
502 if (dup2(inout[0], 0) < 0) /* stdin */
503 perror("dup2 stdin");
504 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
505 perror("dup2 stdout");
507 if (dup2(err[0], 2) < 0) /* stderr */
508 perror("dup2 stderr");
512 /* Do processing for the child (exec command etc). */
513 do_child(ssh, s, command);
520 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
524 /* Set interactive/non-interactive mode. */
525 packet_set_interactive(s->display != NULL,
526 options.ip_qos_interactive, options.ip_qos_bulk);
529 * Clear loginmsg, since it's the child's responsibility to display
530 * it to the user, otherwise multiple sessions may accumulate
531 * multiple copies of the login messages.
533 sshbuf_reset(loginmsg);
536 /* We are the parent. Close the child sides of the pipes. */
541 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
544 /* We are the parent. Close the child sides of the socket pairs. */
549 * Enter the interactive session. Note: server_loop must be able to
550 * handle the case that fdin and fdout are the same.
552 session_set_fds(s, inout[1], inout[1], err[1],
559 * This is called to fork and execute a command when we have a tty. This
560 * will call do_child from the child, and server_loop from the parent after
561 * setting up file descriptors, controlling tty, updating wtmp, utmp,
562 * lastlog, and other such operations.
565 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
567 int fdout, ptyfd, ttyfd, ptymaster;
571 fatal("do_exec_pty: no session");
576 * Create another descriptor of the pty master side for use as the
577 * standard input. We could use the original descriptor, but this
578 * simplifies code in server_loop. The descriptor is bidirectional.
579 * Do this before forking (and cleanup in the child) so as to
580 * detect and gracefully fail out-of-fd conditions.
582 if ((fdout = dup(ptyfd)) < 0) {
583 error("%s: dup #1: %s", __func__, strerror(errno));
588 /* we keep a reference to the pty master */
589 if ((ptymaster = dup(ptyfd)) < 0) {
590 error("%s: dup #2: %s", __func__, strerror(errno));
597 /* Fork the child. */
598 switch ((pid = fork())) {
600 error("%s: fork: %.100s", __func__, strerror(errno));
612 /* Close the master side of the pseudo tty. */
615 /* Make the pseudo tty our controlling tty. */
616 pty_make_controlling_tty(&ttyfd, s->tty);
618 /* Redirect stdin/stdout/stderr from the pseudo tty. */
619 if (dup2(ttyfd, 0) < 0)
620 error("dup2 stdin: %s", strerror(errno));
621 if (dup2(ttyfd, 1) < 0)
622 error("dup2 stdout: %s", strerror(errno));
623 if (dup2(ttyfd, 2) < 0)
624 error("dup2 stderr: %s", strerror(errno));
626 /* Close the extra descriptor for the pseudo tty. */
629 /* record login, etc. similar to login(1) */
631 do_login(ssh, s, command);
634 * Do common processing for the child, such as execing
637 do_child(ssh, s, command);
644 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
649 /* Parent. Close the slave side of the pseudo tty. */
652 /* Enter interactive session. */
653 s->ptymaster = ptymaster;
654 packet_set_interactive(1,
655 options.ip_qos_interactive, options.ip_qos_bulk);
656 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
660 #ifdef LOGIN_NEEDS_UTMPX
662 do_pre_login(Session *s)
664 struct ssh *ssh = active_state; /* XXX */
666 struct sockaddr_storage from;
667 pid_t pid = getpid();
670 * Get IP address of client. If the connection is not a socket, let
671 * the address be 0.0.0.0.
673 memset(&from, 0, sizeof(from));
674 fromlen = sizeof(from);
675 if (packet_connection_is_on_socket()) {
676 if (getpeername(packet_get_connection_in(),
677 (struct sockaddr *)&from, &fromlen) < 0) {
678 debug("getpeername: %.100s", strerror(errno));
683 record_utmp_only(pid, s->tty, s->pw->pw_name,
684 session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
685 (struct sockaddr *)&from, fromlen);
690 * This is called to fork and execute a command. If another command is
691 * to be forced, execute that instead.
694 do_exec(struct ssh *ssh, Session *s, const char *command)
697 const char *forced = NULL, *tty = NULL;
698 char session_type[1024];
700 if (options.adm_forced_command) {
701 original_command = command;
702 command = options.adm_forced_command;
704 } else if (auth_opts->force_command != NULL) {
705 original_command = command;
706 command = auth_opts->force_command;
707 forced = "(key-option)";
710 if (forced != NULL) {
712 if (IS_INTERNAL_SFTP(command)) {
713 s->is_subsystem = s->is_subsystem ?
714 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
715 } else if (s->is_subsystem)
716 s->is_subsystem = SUBSYSTEM_EXT;
717 snprintf(session_type, sizeof(session_type),
718 "forced-command %s '%.900s'", forced, command);
719 } else if (s->is_subsystem) {
720 snprintf(session_type, sizeof(session_type),
721 "subsystem '%.900s'", s->subsys);
722 } else if (command == NULL) {
723 snprintf(session_type, sizeof(session_type), "shell");
725 /* NB. we don't log unforced commands to preserve privacy */
726 snprintf(session_type, sizeof(session_type), "command");
729 if (s->ttyfd != -1) {
731 if (strncmp(tty, "/dev/", 5) == 0)
735 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
737 tty == NULL ? "" : " on ",
738 tty == NULL ? "" : tty,
740 ssh_remote_ipaddr(ssh),
741 ssh_remote_port(ssh),
744 #ifdef SSH_AUDIT_EVENTS
746 PRIVSEP(audit_run_command(command));
747 else if (s->ttyfd == -1) {
748 char *shell = s->pw->pw_shell;
750 if (shell[0] == '\0') /* empty shell means /bin/sh */
752 PRIVSEP(audit_run_command(shell));
756 ret = do_exec_pty(ssh, s, command);
758 ret = do_exec_no_pty(ssh, s, command);
760 original_command = NULL;
763 * Clear loginmsg: it's the child's responsibility to display
764 * it to the user, otherwise multiple sessions may accumulate
765 * multiple copies of the login messages.
767 sshbuf_reset(loginmsg);
772 /* administrative, login(1)-like work */
774 do_login(struct ssh *ssh, Session *s, const char *command)
777 struct sockaddr_storage from;
778 struct passwd * pw = s->pw;
779 pid_t pid = getpid();
782 * Get IP address of client. If the connection is not a socket, let
783 * the address be 0.0.0.0.
785 memset(&from, 0, sizeof(from));
786 fromlen = sizeof(from);
787 if (packet_connection_is_on_socket()) {
788 if (getpeername(packet_get_connection_in(),
789 (struct sockaddr *)&from, &fromlen) < 0) {
790 debug("getpeername: %.100s", strerror(errno));
795 /* Record that there was a login on that tty from the remote host. */
797 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
798 session_get_remote_name_or_ip(ssh, utmp_len,
800 (struct sockaddr *)&from, fromlen);
804 * If password change is needed, do it now.
805 * This needs to occur before the ~/.hushlogin check.
807 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
810 s->authctxt->force_pwchange = 0;
811 /* XXX - signal [net] parent to enable forwardings */
815 if (check_quietlogin(s, command))
824 * Display the message of the day.
832 if (options.print_motd) {
833 #ifdef HAVE_LOGIN_CAP
834 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
837 f = fopen("/etc/motd", "r");
840 while (fgets(buf, sizeof(buf), f))
849 * Check for quiet login, either .hushlogin or command given.
852 check_quietlogin(Session *s, const char *command)
855 struct passwd *pw = s->pw;
858 /* Return 1 if .hushlogin exists or a command given. */
861 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
862 #ifdef HAVE_LOGIN_CAP
863 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
866 if (stat(buf, &st) >= 0)
873 * Reads environment variables from the given file and adds/overrides them
874 * into the environment. If the file does not exist, this does nothing.
875 * Otherwise, it must consist of empty lines, comments (line starts with '#')
876 * and assignments of the form name=value. No other forms are allowed.
877 * If whitelist is not NULL, then it is interpreted as a pattern list and
878 * only variable names that match it will be accepted.
881 read_environment_file(char ***env, u_int *envsize,
882 const char *filename, const char *whitelist)
885 char *line = NULL, *cp, *value;
889 f = fopen(filename, "r");
893 while (getline(&line, &linesize, f) != -1) {
895 fatal("Too many lines in environment file %s", filename);
896 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
898 if (!*cp || *cp == '#' || *cp == '\n')
901 cp[strcspn(cp, "\n")] = '\0';
903 value = strchr(cp, '=');
905 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
910 * Replace the equals sign by nul, and advance value to
915 if (whitelist != NULL &&
916 match_pattern_list(cp, whitelist, 0) != 1)
918 child_set_env(env, envsize, cp, value);
924 #ifdef HAVE_ETC_DEFAULT_LOGIN
926 * Return named variable from specified environment, or NULL if not present.
929 child_get_env(char **env, const char *name)
935 for (i=0; env[i] != NULL; i++)
936 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
937 return(env[i] + len + 1);
942 * Read /etc/default/login.
943 * We pick up the PATH (or SUPATH for root) and UMASK.
946 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
948 char **tmpenv = NULL, *var;
949 u_int i, tmpenvsize = 0;
953 * We don't want to copy the whole file to the child's environment,
954 * so we use a temporary environment and copy the variables we're
957 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
958 options.permit_user_env_whitelist);
964 var = child_get_env(tmpenv, "SUPATH");
966 var = child_get_env(tmpenv, "PATH");
968 child_set_env(env, envsize, "PATH", var);
970 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
971 if (sscanf(var, "%5lo", &mask) == 1)
974 for (i = 0; tmpenv[i] != NULL; i++)
978 #endif /* HAVE_ETC_DEFAULT_LOGIN */
981 copy_environment_blacklist(char **source, char ***env, u_int *envsize,
982 const char *blacklist)
984 char *var_name, *var_val;
990 for(i = 0; source[i] != NULL; i++) {
991 var_name = xstrdup(source[i]);
992 if ((var_val = strstr(var_name, "=")) == NULL) {
998 if (blacklist == NULL ||
999 match_pattern_list(var_name, blacklist, 0) != 1) {
1000 debug3("Copy environment: %s=%s", var_name, var_val);
1001 child_set_env(env, envsize, var_name, var_val);
1009 copy_environment(char **source, char ***env, u_int *envsize)
1011 copy_environment_blacklist(source, env, envsize, NULL);
1015 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
1020 char *ocp, *cp, *value, **env, *laddr;
1021 struct passwd *pw = s->pw;
1022 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1025 extern char **environ;
1026 char **senv, **var, *val;
1029 /* Initialize the environment. */
1031 env = xcalloc(envsize, sizeof(char *));
1036 * The Windows environment contains some setting which are
1037 * important for a running system. They must not be dropped.
1042 p = fetch_windows_environment();
1043 copy_environment(p, &env, &envsize);
1044 free_windows_environment(p);
1049 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1052 /* Allow any GSSAPI methods that we've used to alter
1053 * the childs environment as they see fit
1055 ssh_gssapi_do_child(&env, &envsize);
1058 /* Set basic environment. */
1059 for (i = 0; i < s->num_env; i++)
1060 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1062 child_set_env(&env, &envsize, "USER", pw->pw_name);
1063 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1065 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1067 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1068 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1069 child_set_env(&env, &envsize, "MAIL", buf);
1070 #ifdef HAVE_LOGIN_CAP
1071 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1072 child_set_env(&env, &envsize, "TERM", "su");
1074 * Temporarily swap out our real environment with an empty one,
1075 * let setusercontext() apply any environment variables defined
1076 * for the user's login class, copy those variables to the child,
1077 * free the temporary environment, and restore the original.
1080 environ = xmalloc(sizeof(*environ));
1082 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1083 for (var = environ; *var != NULL; ++var) {
1084 if ((val = strchr(*var, '=')) != NULL) {
1086 child_set_env(&env, &envsize, *var, val);
1092 #else /* HAVE_LOGIN_CAP */
1093 # ifndef HAVE_CYGWIN
1095 * There's no standard path on Windows. The path contains
1096 * important components pointing to the system directories,
1097 * needed for loading shared libraries. So the path better
1098 * remains intact here.
1100 # ifdef HAVE_ETC_DEFAULT_LOGIN
1101 read_etc_default_login(&env, &envsize, pw->pw_uid);
1102 path = child_get_env(env, "PATH");
1103 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1104 if (path == NULL || *path == '\0') {
1105 child_set_env(&env, &envsize, "PATH",
1106 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1108 # endif /* HAVE_CYGWIN */
1109 #endif /* HAVE_LOGIN_CAP */
1111 /* Normal systems set SHELL by default. */
1112 child_set_env(&env, &envsize, "SHELL", shell);
1115 child_set_env(&env, &envsize, "TERM", s->term);
1117 child_set_env(&env, &envsize, "DISPLAY", s->display);
1120 * Since we clear KRB5CCNAME at startup, if it's set now then it
1121 * must have been set by a native authentication method (eg AIX or
1122 * SIA), so copy it to the child.
1127 if ((cp = getenv("KRB5CCNAME")) != NULL)
1128 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1135 if ((cp = getenv("AUTHSTATE")) != NULL)
1136 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1137 read_environment_file(&env, &envsize, "/etc/environment",
1138 options.permit_user_env_whitelist);
1142 if (s->authctxt->krb5_ccname)
1143 child_set_env(&env, &envsize, "KRB5CCNAME",
1144 s->authctxt->krb5_ccname);
1146 if (auth_sock_name != NULL)
1147 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1151 /* Set custom environment options from pubkey authentication. */
1152 if (options.permit_user_env) {
1153 for (n = 0 ; n < auth_opts->nenv; n++) {
1154 ocp = xstrdup(auth_opts->env[n]);
1155 cp = strchr(ocp, '=');
1158 /* Apply PermitUserEnvironment whitelist */
1159 if (options.permit_user_env_whitelist == NULL ||
1160 match_pattern_list(ocp,
1161 options.permit_user_env_whitelist, 0) == 1)
1162 child_set_env(&env, &envsize,
1169 /* read $HOME/.ssh/environment. */
1170 if (options.permit_user_env) {
1171 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1173 read_environment_file(&env, &envsize, buf,
1174 options.permit_user_env_whitelist);
1179 * Pull in any environment variables that may have
1182 if (options.use_pam) {
1186 * Don't allow SSH_AUTH_INFO variables posted to PAM to leak
1187 * back into the environment.
1189 p = fetch_pam_child_environment();
1190 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1191 free_pam_environment(p);
1193 p = fetch_pam_environment();
1194 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1195 free_pam_environment(p);
1197 #endif /* USE_PAM */
1199 /* Environment specified by admin */
1200 for (i = 0; i < options.num_setenv; i++) {
1201 cp = xstrdup(options.setenv[i]);
1202 if ((value = strchr(cp, '=')) == NULL) {
1203 /* shouldn't happen; vars are checked in servconf.c */
1204 fatal("Invalid config SetEnv: %s", options.setenv[i]);
1207 child_set_env(&env, &envsize, cp, value);
1210 /* SSH_CLIENT deprecated */
1211 snprintf(buf, sizeof buf, "%.50s %d %d",
1212 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1213 ssh_local_port(ssh));
1214 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1216 laddr = get_local_ipaddr(packet_get_connection_in());
1217 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1218 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1219 laddr, ssh_local_port(ssh));
1221 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1223 if (tun_fwd_ifnames != NULL)
1224 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1225 if (auth_info_file != NULL)
1226 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1228 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1229 if (original_command)
1230 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1234 /* dump the environment */
1235 fprintf(stderr, "Environment:\n");
1236 for (i = 0; env[i]; i++)
1237 fprintf(stderr, " %.200s\n", env[i]);
1243 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1244 * first in this order).
1247 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1255 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1257 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1258 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1259 auth_opts->permit_user_rc && options.permit_user_rc &&
1260 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1261 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1262 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1264 fprintf(stderr, "Running %s\n", cmd);
1265 f = popen(cmd, "w");
1268 fprintf(f, "%s %s\n", s->auth_proto,
1272 fprintf(stderr, "Could not run %s\n",
1274 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1276 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1277 _PATH_SSH_SYSTEM_RC);
1278 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1281 fprintf(f, "%s %s\n", s->auth_proto,
1285 fprintf(stderr, "Could not run %s\n",
1286 _PATH_SSH_SYSTEM_RC);
1287 } else if (do_xauth && options.xauth_location != NULL) {
1288 /* Add authority data to .Xauthority if appropriate. */
1291 "Running %.500s remove %.100s\n",
1292 options.xauth_location, s->auth_display);
1294 "%.500s add %.100s %.100s %.100s\n",
1295 options.xauth_location, s->auth_display,
1296 s->auth_proto, s->auth_data);
1298 snprintf(cmd, sizeof cmd, "%s -q -",
1299 options.xauth_location);
1300 f = popen(cmd, "w");
1302 fprintf(f, "remove %s\n",
1304 fprintf(f, "add %s %s %s\n",
1305 s->auth_display, s->auth_proto,
1309 fprintf(stderr, "Could not run %s\n",
1316 do_nologin(struct passwd *pw)
1320 char buf[1024], *def_nl = _PATH_NOLOGIN;
1323 #ifdef HAVE_LOGIN_CAP
1324 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1326 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1328 if (pw->pw_uid == 0)
1332 if (stat(nl, &sb) == -1)
1335 /* /etc/nologin exists. Print its contents if we can and exit. */
1336 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1337 if ((f = fopen(nl, "r")) != NULL) {
1338 while (fgets(buf, sizeof(buf), f))
1346 * Chroot into a directory after checking it for safety: all path components
1347 * must be root-owned directories with strict permissions.
1350 safely_chroot(const char *path, uid_t uid)
1353 char component[PATH_MAX];
1357 fatal("chroot path does not begin at root");
1358 if (strlen(path) >= sizeof(component))
1359 fatal("chroot path too long");
1362 * Descend the path, checking that each component is a
1363 * root-owned directory with strict permissions.
1365 for (cp = path; cp != NULL;) {
1366 if ((cp = strchr(cp, '/')) == NULL)
1367 strlcpy(component, path, sizeof(component));
1370 memcpy(component, path, cp - path);
1371 component[cp - path] = '\0';
1374 debug3("%s: checking '%s'", __func__, component);
1376 if (stat(component, &st) != 0)
1377 fatal("%s: stat(\"%s\"): %s", __func__,
1378 component, strerror(errno));
1379 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1380 fatal("bad ownership or modes for chroot "
1381 "directory %s\"%s\"",
1382 cp == NULL ? "" : "component ", component);
1383 if (!S_ISDIR(st.st_mode))
1384 fatal("chroot path %s\"%s\" is not a directory",
1385 cp == NULL ? "" : "component ", component);
1389 if (chdir(path) == -1)
1390 fatal("Unable to chdir to chroot path \"%s\": "
1391 "%s", path, strerror(errno));
1392 if (chroot(path) == -1)
1393 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1394 if (chdir("/") == -1)
1395 fatal("%s: chdir(/) after chroot: %s",
1396 __func__, strerror(errno));
1397 verbose("Changed root directory to \"%s\"", path);
1400 /* Set login name, uid, gid, and groups. */
1402 do_setusercontext(struct passwd *pw)
1404 char uidstr[32], *chroot_path, *tmp;
1406 platform_setusercontext(pw);
1408 if (platform_privileged_uidswap()) {
1409 #ifdef HAVE_LOGIN_CAP
1410 if (setusercontext(lc, pw, pw->pw_uid,
1411 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1412 perror("unable to set user context");
1416 if (setlogin(pw->pw_name) < 0)
1417 error("setlogin failed: %s", strerror(errno));
1418 if (setgid(pw->pw_gid) < 0) {
1422 /* Initialize the group list. */
1423 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1424 perror("initgroups");
1430 platform_setusercontext_post_groups(pw);
1432 if (!in_chroot && options.chroot_directory != NULL &&
1433 strcasecmp(options.chroot_directory, "none") != 0) {
1434 tmp = tilde_expand_filename(options.chroot_directory,
1436 snprintf(uidstr, sizeof(uidstr), "%llu",
1437 (unsigned long long)pw->pw_uid);
1438 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1439 "u", pw->pw_name, "U", uidstr, (char *)NULL);
1440 safely_chroot(chroot_path, pw->pw_uid);
1443 /* Make sure we don't attempt to chroot again */
1444 free(options.chroot_directory);
1445 options.chroot_directory = NULL;
1449 #ifdef HAVE_LOGIN_CAP
1450 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1451 perror("unable to set user context (setuser)");
1455 * FreeBSD's setusercontext() will not apply the user's
1456 * own umask setting unless running with the user's UID.
1458 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1462 * In a chroot environment, the set_id() will always fail;
1463 * typically because of the lack of necessary authentication
1464 * services and runtime such as ./usr/lib/libiaf.so,
1465 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1466 * internal sftp chroot case. We'll lose auditing and ACLs but
1467 * permanently_set_uid will take care of the rest.
1469 if (!in_chroot && set_id(pw->pw_name) != 0)
1470 fatal("set_id(%s) Failed", pw->pw_name);
1471 # endif /* USE_LIBIAF */
1472 /* Permanently switch to the desired uid. */
1473 permanently_set_uid(pw);
1475 } else if (options.chroot_directory != NULL &&
1476 strcasecmp(options.chroot_directory, "none") != 0) {
1477 fatal("server lacks privileges to chroot to ChrootDirectory");
1480 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1481 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1485 do_pwchange(Session *s)
1488 fprintf(stderr, "WARNING: Your password has expired.\n");
1489 if (s->ttyfd != -1) {
1491 "You must change your password now and login again!\n");
1495 #ifdef PASSWD_NEEDS_USERNAME
1496 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1499 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1504 "Password change required but no TTY available.\n");
1510 child_close_fds(struct ssh *ssh)
1512 extern int auth_sock;
1514 if (auth_sock != -1) {
1519 if (packet_get_connection_in() == packet_get_connection_out())
1520 close(packet_get_connection_in());
1522 close(packet_get_connection_in());
1523 close(packet_get_connection_out());
1526 * Close all descriptors related to channels. They will still remain
1527 * open in the parent.
1529 /* XXX better use close-on-exec? -markus */
1530 channel_close_all(ssh);
1533 * Close any extra file descriptors. Note that there may still be
1534 * descriptors left by system functions. They will be closed later.
1539 * Close any extra open file descriptors so that we don't have them
1540 * hanging around in clients. Note that we want to do this after
1541 * initgroups, because at least on Solaris 2.3 it leaves file
1544 closefrom(STDERR_FILENO + 1);
1548 * Performs common processing for the child, such as setting up the
1549 * environment, closing extra file descriptors, setting the user and group
1550 * ids, and executing the command or shell.
1554 do_child(struct ssh *ssh, Session *s, const char *command)
1556 extern char **environ;
1558 char *argv[ARGV_MAX];
1559 const char *shell, *shell0;
1560 struct passwd *pw = s->pw;
1563 /* remove hostkey from the child's memory */
1564 destroy_sensitive_data();
1565 packet_clear_keys();
1567 /* Force a password change */
1568 if (s->authctxt->force_pwchange) {
1569 do_setusercontext(pw);
1570 child_close_fds(ssh);
1576 * Login(1) does this as well, and it needs uid 0 for the "-h"
1577 * switch, so we let login(1) to this for us.
1580 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1581 if (!check_quietlogin(s, command))
1583 #else /* HAVE_OSF_SIA */
1584 /* When PAM is enabled we rely on it to do the nologin check */
1585 if (!options.use_pam)
1587 do_setusercontext(pw);
1589 * PAM session modules in do_setusercontext may have
1590 * generated messages, so if this in an interactive
1591 * login then display them too.
1593 if (!check_quietlogin(s, command))
1595 #endif /* HAVE_OSF_SIA */
1598 if (options.use_pam && !is_pam_session_open()) {
1599 debug3("PAM session not opened, exiting");
1606 * Get the shell from the password data. An empty shell field is
1607 * legal, and means /bin/sh.
1609 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1612 * Make sure $SHELL points to the shell from the password file,
1613 * even if shell is overridden from login.conf
1615 env = do_setup_env(ssh, s, shell);
1617 #ifdef HAVE_LOGIN_CAP
1618 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1622 * Close the connection descriptors; note that this is the child, and
1623 * the server will still have the socket open, and it is important
1624 * that we do not shutdown it. Note that the descriptors cannot be
1625 * closed before building the environment, as we call
1626 * ssh_remote_ipaddr there.
1628 child_close_fds(ssh);
1631 * Must take new environment into use so that .ssh/rc,
1632 * /etc/ssh/sshrc and xauth are run in the proper environment.
1636 #if defined(KRB5) && defined(USE_AFS)
1638 * At this point, we check to see if AFS is active and if we have
1639 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1640 * if we can (and need to) extend the ticket into an AFS token. If
1641 * we don't do this, we run into potential problems if the user's
1642 * home directory is in AFS and it's not world-readable.
1645 if (options.kerberos_get_afs_token && k_hasafs() &&
1646 (s->authctxt->krb5_ctx != NULL)) {
1649 debug("Getting AFS token");
1653 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1654 krb5_afslog(s->authctxt->krb5_ctx,
1655 s->authctxt->krb5_fwd_ccache, cell, NULL);
1657 krb5_afslog_home(s->authctxt->krb5_ctx,
1658 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1662 /* Change current directory to the user's home directory. */
1663 if (chdir(pw->pw_dir) < 0) {
1664 /* Suppress missing homedir warning for chroot case */
1665 #ifdef HAVE_LOGIN_CAP
1666 r = login_getcapbool(lc, "requirehome", 0);
1668 if (r || !in_chroot) {
1669 fprintf(stderr, "Could not chdir to home "
1670 "directory %s: %s\n", pw->pw_dir,
1677 closefrom(STDERR_FILENO + 1);
1679 do_rc_files(ssh, s, shell);
1681 /* restore SIGPIPE for child */
1682 signal(SIGPIPE, SIG_DFL);
1684 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1685 printf("This service allows sftp connections only.\n");
1688 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1689 extern int optind, optreset;
1693 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1694 args = xstrdup(command ? command : "sftp-server");
1695 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1696 if (i < ARGV_MAX - 1)
1699 optind = optreset = 1;
1700 __progname = argv[0];
1702 ssh_selinux_change_context("sftpd_t");
1704 exit(sftp_server_main(i, argv, s->pw));
1709 /* Get the last component of the shell name. */
1710 if ((shell0 = strrchr(shell, '/')) != NULL)
1716 * If we have no command, execute the shell. In this case, the shell
1717 * name to be passed in argv[0] is preceded by '-' to indicate that
1718 * this is a login shell.
1723 /* Start the shell. Set initial character to '-'. */
1726 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1727 >= sizeof(argv0) - 1) {
1733 /* Execute the shell. */
1736 execve(shell, argv, env);
1738 /* Executing the shell failed. */
1743 * Execute the command using the user's shell. This uses the -c
1744 * option to execute the command.
1746 argv[0] = (char *) shell0;
1748 argv[2] = (char *) command;
1750 execve(shell, argv, env);
1756 session_unused(int id)
1758 debug3("%s: session id %d unused", __func__, id);
1759 if (id >= options.max_sessions ||
1760 id >= sessions_nalloc) {
1761 fatal("%s: insane session id %d (max %d nalloc %d)",
1762 __func__, id, options.max_sessions, sessions_nalloc);
1764 memset(&sessions[id], 0, sizeof(*sessions));
1765 sessions[id].self = id;
1766 sessions[id].used = 0;
1767 sessions[id].chanid = -1;
1768 sessions[id].ptyfd = -1;
1769 sessions[id].ttyfd = -1;
1770 sessions[id].ptymaster = -1;
1771 sessions[id].x11_chanids = NULL;
1772 sessions[id].next_unused = sessions_first_unused;
1773 sessions_first_unused = id;
1781 if (sessions_first_unused == -1) {
1782 if (sessions_nalloc >= options.max_sessions)
1784 debug2("%s: allocate (allocated %d max %d)",
1785 __func__, sessions_nalloc, options.max_sessions);
1786 tmp = xrecallocarray(sessions, sessions_nalloc,
1787 sessions_nalloc + 1, sizeof(*sessions));
1789 error("%s: cannot allocate %d sessions",
1790 __func__, sessions_nalloc + 1);
1794 session_unused(sessions_nalloc++);
1797 if (sessions_first_unused >= sessions_nalloc ||
1798 sessions_first_unused < 0) {
1799 fatal("%s: insane first_unused %d max %d nalloc %d",
1800 __func__, sessions_first_unused, options.max_sessions,
1804 s = &sessions[sessions_first_unused];
1806 fatal("%s: session %d already used",
1807 __func__, sessions_first_unused);
1809 sessions_first_unused = s->next_unused;
1811 s->next_unused = -1;
1812 debug("session_new: session %d", s->self);
1821 for (i = 0; i < sessions_nalloc; i++) {
1822 Session *s = &sessions[i];
1824 debug("dump: used %d next_unused %d session %d %p "
1825 "channel %d pid %ld",
1836 session_open(Authctxt *authctxt, int chanid)
1838 Session *s = session_new();
1839 debug("session_open: channel %d", chanid);
1841 error("no more sessions");
1844 s->authctxt = authctxt;
1845 s->pw = authctxt->pw;
1846 if (s->pw == NULL || !authctxt->valid)
1847 fatal("no user for session %d", s->self);
1848 debug("session_open: session %d: link with channel %d", s->self, chanid);
1854 session_by_tty(char *tty)
1857 for (i = 0; i < sessions_nalloc; i++) {
1858 Session *s = &sessions[i];
1859 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1860 debug("session_by_tty: session %d tty %s", i, tty);
1864 debug("session_by_tty: unknown tty %.100s", tty);
1870 session_by_channel(int id)
1873 for (i = 0; i < sessions_nalloc; i++) {
1874 Session *s = &sessions[i];
1875 if (s->used && s->chanid == id) {
1876 debug("session_by_channel: session %d channel %d",
1881 debug("session_by_channel: unknown channel %d", id);
1887 session_by_x11_channel(int id)
1891 for (i = 0; i < sessions_nalloc; i++) {
1892 Session *s = &sessions[i];
1894 if (s->x11_chanids == NULL || !s->used)
1896 for (j = 0; s->x11_chanids[j] != -1; j++) {
1897 if (s->x11_chanids[j] == id) {
1898 debug("session_by_x11_channel: session %d "
1899 "channel %d", s->self, id);
1904 debug("session_by_x11_channel: unknown channel %d", id);
1910 session_by_pid(pid_t pid)
1913 debug("session_by_pid: pid %ld", (long)pid);
1914 for (i = 0; i < sessions_nalloc; i++) {
1915 Session *s = &sessions[i];
1916 if (s->used && s->pid == pid)
1919 error("session_by_pid: unknown pid %ld", (long)pid);
1925 session_window_change_req(struct ssh *ssh, Session *s)
1927 s->col = packet_get_int();
1928 s->row = packet_get_int();
1929 s->xpixel = packet_get_int();
1930 s->ypixel = packet_get_int();
1932 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1937 session_pty_req(struct ssh *ssh, Session *s)
1941 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1942 debug("Allocating a pty not permitted for this connection.");
1945 if (s->ttyfd != -1) {
1946 packet_disconnect("Protocol error: you already have a pty.");
1950 s->term = packet_get_string(&len);
1951 s->col = packet_get_int();
1952 s->row = packet_get_int();
1953 s->xpixel = packet_get_int();
1954 s->ypixel = packet_get_int();
1956 if (strcmp(s->term, "") == 0) {
1961 /* Allocate a pty and open it. */
1962 debug("Allocating pty.");
1963 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1969 error("session_pty_req: session %d alloc failed", s->self);
1972 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1974 ssh_tty_parse_modes(ssh, s->ttyfd);
1977 pty_setowner(s->pw, s->tty);
1979 /* Set window size from the packet. */
1980 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1983 session_proctitle(s);
1988 session_subsystem_req(struct ssh *ssh, Session *s)
1996 s->subsys = packet_get_string(&len);
1998 debug2("subsystem request for %.100s by user %s", s->subsys,
2001 for (i = 0; i < options.num_subsystems; i++) {
2002 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
2003 prog = options.subsystem_command[i];
2004 cmd = options.subsystem_args[i];
2005 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2006 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2007 debug("subsystem: %s", prog);
2009 if (stat(prog, &st) < 0)
2010 debug("subsystem: cannot stat %s: %s",
2011 prog, strerror(errno));
2012 s->is_subsystem = SUBSYSTEM_EXT;
2013 debug("subsystem: exec() %s", cmd);
2015 success = do_exec(ssh, s, cmd) == 0;
2021 logit("subsystem request for %.100s by user %s failed, "
2022 "subsystem not found", s->subsys, s->pw->pw_name);
2028 session_x11_req(struct ssh *ssh, Session *s)
2032 if (s->auth_proto != NULL || s->auth_data != NULL) {
2033 error("session_x11_req: session %d: "
2034 "x11 forwarding already active", s->self);
2037 s->single_connection = packet_get_char();
2038 s->auth_proto = packet_get_string(NULL);
2039 s->auth_data = packet_get_string(NULL);
2040 s->screen = packet_get_int();
2043 if (xauth_valid_string(s->auth_proto) &&
2044 xauth_valid_string(s->auth_data))
2045 success = session_setup_x11fwd(ssh, s);
2048 error("Invalid X11 forwarding data");
2051 free(s->auth_proto);
2053 s->auth_proto = NULL;
2054 s->auth_data = NULL;
2060 session_shell_req(struct ssh *ssh, Session *s)
2063 return do_exec(ssh, s, NULL) == 0;
2067 session_exec_req(struct ssh *ssh, Session *s)
2071 char *command = packet_get_string(&len);
2073 success = do_exec(ssh, s, command) == 0;
2079 session_break_req(struct ssh *ssh, Session *s)
2082 packet_get_int(); /* ignored */
2085 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2091 session_env_req(struct ssh *ssh, Session *s)
2094 u_int name_len, val_len, i;
2096 name = packet_get_cstring(&name_len);
2097 val = packet_get_cstring(&val_len);
2100 /* Don't set too many environment variables */
2101 if (s->num_env > 128) {
2102 debug2("Ignoring env request %s: too many env vars", name);
2106 for (i = 0; i < options.num_accept_env; i++) {
2107 if (match_pattern(name, options.accept_env[i])) {
2108 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2109 s->env = xrecallocarray(s->env, s->num_env,
2110 s->num_env + 1, sizeof(*s->env));
2111 s->env[s->num_env].name = name;
2112 s->env[s->num_env].val = val;
2117 debug2("Ignoring env request %s: disallowed name", name);
2126 * Conversion of signals from ssh channel request names.
2127 * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
2131 name2sig(char *name)
2133 #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
2143 if (strcmp(name, "INFO@openssh.com") == 0)
2150 session_signal_req(struct ssh *ssh, Session *s)
2152 char *signame = NULL;
2153 int r, sig, success = 0;
2155 if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
2156 (r = sshpkt_get_end(ssh)) != 0) {
2157 error("%s: parse packet: %s", __func__, ssh_err(r));
2160 if ((sig = name2sig(signame)) == -1) {
2161 error("%s: unsupported signal \"%s\"", __func__, signame);
2165 error("%s: no pid for session %d", __func__, s->self);
2168 if (s->forced || s->is_subsystem) {
2169 error("%s: refusing to send signal %s to %s session", __func__,
2170 signame, s->forced ? "forced-command" : "subsystem");
2173 if (!use_privsep || mm_is_monitor()) {
2174 error("%s: session signalling requires privilege separation",
2179 debug("%s: signal %s, killpg(%ld, %d)", __func__, signame,
2181 temporarily_use_uid(s->pw);
2182 r = killpg(s->pid, sig);
2185 error("%s: killpg(%ld, %d): %s", __func__, (long)s->pid,
2186 sig, strerror(errno));
2198 session_auth_agent_req(struct ssh *ssh, Session *s)
2200 static int called = 0;
2203 if (!auth_opts->permit_agent_forwarding_flag ||
2204 !options.allow_agent_forwarding) {
2205 debug("%s: agent forwarding disabled", __func__);
2212 return auth_input_request_forwarding(ssh, s->pw);
2217 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2222 if ((s = session_by_channel(c->self)) == NULL) {
2223 logit("%s: no session %d req %.100s", __func__, c->self, rtype);
2226 debug("%s: session %d req %s", __func__, s->self, rtype);
2229 * a session is in LARVAL state until a shell, a command
2230 * or a subsystem is executed
2232 if (c->type == SSH_CHANNEL_LARVAL) {
2233 if (strcmp(rtype, "shell") == 0) {
2234 success = session_shell_req(ssh, s);
2235 } else if (strcmp(rtype, "exec") == 0) {
2236 success = session_exec_req(ssh, s);
2237 } else if (strcmp(rtype, "pty-req") == 0) {
2238 success = session_pty_req(ssh, s);
2239 } else if (strcmp(rtype, "x11-req") == 0) {
2240 success = session_x11_req(ssh, s);
2241 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2242 success = session_auth_agent_req(ssh, s);
2243 } else if (strcmp(rtype, "subsystem") == 0) {
2244 success = session_subsystem_req(ssh, s);
2245 } else if (strcmp(rtype, "env") == 0) {
2246 success = session_env_req(ssh, s);
2249 if (strcmp(rtype, "window-change") == 0) {
2250 success = session_window_change_req(ssh, s);
2251 } else if (strcmp(rtype, "break") == 0) {
2252 success = session_break_req(ssh, s);
2253 } else if (strcmp(rtype, "signal") == 0) {
2254 success = session_signal_req(ssh, s);
2261 session_set_fds(struct ssh *ssh, Session *s,
2262 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2265 * now that have a child and a pipe to the child,
2266 * we can activate our channel and register the fd's
2268 if (s->chanid == -1)
2269 fatal("no channel for session %d", s->self);
2270 channel_set_fds(ssh, s->chanid,
2272 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2273 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2277 * Function to perform pty cleanup. Also called if we get aborted abnormally
2278 * (e.g., due to a dropped connection).
2281 session_pty_cleanup2(Session *s)
2284 error("%s: no session", __func__);
2290 debug("%s: session %d release %s", __func__, s->self, s->tty);
2292 /* Record that the user has logged out. */
2294 record_logout(s->pid, s->tty, s->pw->pw_name);
2296 /* Release the pseudo-tty. */
2298 pty_release(s->tty);
2301 * Close the server side of the socket pairs. We must do this after
2302 * the pty cleanup, so that another process doesn't get this pty
2303 * while we're still cleaning up.
2305 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2306 error("close(s->ptymaster/%d): %s",
2307 s->ptymaster, strerror(errno));
2309 /* unlink pty from session */
2314 session_pty_cleanup(Session *s)
2316 PRIVSEP(session_pty_cleanup2(s));
2322 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2337 return "SIG@openssh.com";
2341 session_close_x11(struct ssh *ssh, int id)
2345 if ((c = channel_by_id(ssh, id)) == NULL) {
2346 debug("%s: x11 channel %d missing", __func__, id);
2348 /* Detach X11 listener */
2349 debug("%s: detach x11 channel %d", __func__, id);
2350 channel_cancel_cleanup(ssh, id);
2351 if (c->ostate != CHAN_OUTPUT_CLOSED)
2352 chan_mark_dead(ssh, c);
2357 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2362 debug3("%s: channel %d", __func__, id);
2363 channel_cancel_cleanup(ssh, id);
2364 if ((s = session_by_x11_channel(id)) == NULL)
2365 fatal("%s: no x11 channel %d", __func__, id);
2366 for (i = 0; s->x11_chanids[i] != -1; i++) {
2367 debug("%s: session %d: closing channel %d",
2368 __func__, s->self, s->x11_chanids[i]);
2370 * The channel "id" is already closing, but make sure we
2371 * close all of its siblings.
2373 if (s->x11_chanids[i] != id)
2374 session_close_x11(ssh, s->x11_chanids[i]);
2376 free(s->x11_chanids);
2377 s->x11_chanids = NULL;
2380 free(s->auth_proto);
2381 s->auth_proto = NULL;
2383 s->auth_data = NULL;
2384 free(s->auth_display);
2385 s->auth_display = NULL;
2389 session_exit_message(struct ssh *ssh, Session *s, int status)
2393 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2394 fatal("%s: session %d: no channel %d",
2395 __func__, s->self, s->chanid);
2396 debug("%s: session %d channel %d pid %ld",
2397 __func__, s->self, s->chanid, (long)s->pid);
2399 if (WIFEXITED(status)) {
2400 channel_request_start(ssh, s->chanid, "exit-status", 0);
2401 packet_put_int(WEXITSTATUS(status));
2403 } else if (WIFSIGNALED(status)) {
2404 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2405 packet_put_cstring(sig2name(WTERMSIG(status)));
2407 packet_put_char(WCOREDUMP(status)? 1 : 0);
2408 #else /* WCOREDUMP */
2410 #endif /* WCOREDUMP */
2411 packet_put_cstring("");
2412 packet_put_cstring("");
2415 /* Some weird exit cause. Just exit. */
2416 packet_disconnect("wait returned status %04x.", status);
2419 /* disconnect channel */
2420 debug("%s: release channel %d", __func__, 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 childs 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("%s: no session for pid %ld", __func__, (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("%s: no session for id %d", __func__, id);
2499 debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
2501 debug("%s: channel %d: has child, ttyfd %d",
2502 __func__, id, s->ttyfd);
2504 * delay detach of session, but release pty, since
2505 * the fd's to the child are already closed
2508 session_pty_cleanup(s);
2511 /* detach by removing callback */
2512 channel_cancel_cleanup(ssh, s->chanid);
2514 /* Close any X11 listeners associated with this session */
2515 if (s->x11_chanids != NULL) {
2516 for (i = 0; s->x11_chanids[i] != -1; i++) {
2517 session_close_x11(ssh, s->x11_chanids[i]);
2518 s->x11_chanids[i] = -1;
2523 session_close(ssh, s);
2527 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2530 for (i = 0; i < sessions_nalloc; i++) {
2531 Session *s = &sessions[i];
2533 if (closefunc != NULL)
2536 session_close(ssh, s);
2542 session_tty_list(void)
2544 static char buf[1024];
2549 for (i = 0; i < sessions_nalloc; i++) {
2550 Session *s = &sessions[i];
2551 if (s->used && s->ttyfd != -1) {
2553 if (strncmp(s->tty, "/dev/", 5) != 0) {
2554 cp = strrchr(s->tty, '/');
2555 cp = (cp == NULL) ? s->tty : cp + 1;
2560 strlcat(buf, ",", sizeof buf);
2561 strlcat(buf, cp, sizeof buf);
2565 strlcpy(buf, "notty", sizeof buf);
2570 session_proctitle(Session *s)
2573 error("no user for session %d", s->self);
2575 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2579 session_setup_x11fwd(struct ssh *ssh, Session *s)
2582 char display[512], auth_display[512];
2583 char hostname[NI_MAXHOST];
2586 if (!auth_opts->permit_x11_forwarding_flag) {
2587 packet_send_debug("X11 forwarding disabled by key options.");
2590 if (!options.x11_forwarding) {
2591 debug("X11 forwarding disabled in server configuration file.");
2594 if (options.xauth_location == NULL ||
2595 (stat(options.xauth_location, &st) == -1)) {
2596 packet_send_debug("No xauth program; cannot forward X11.");
2599 if (s->display != NULL) {
2600 debug("X11 display already set.");
2603 if (x11_create_display_inet(ssh, options.x11_display_offset,
2604 options.x11_use_localhost, s->single_connection,
2605 &s->display_number, &s->x11_chanids) == -1) {
2606 debug("x11_create_display_inet failed.");
2609 for (i = 0; s->x11_chanids[i] != -1; i++) {
2610 channel_register_cleanup(ssh, s->x11_chanids[i],
2611 session_close_single_x11, 0);
2614 /* Set up a suitable value for the DISPLAY variable. */
2615 if (gethostname(hostname, sizeof(hostname)) < 0)
2616 fatal("gethostname: %.100s", strerror(errno));
2618 * auth_display must be used as the displayname when the
2619 * authorization entry is added with xauth(1). This will be
2620 * different than the DISPLAY string for localhost displays.
2622 if (options.x11_use_localhost) {
2623 snprintf(display, sizeof display, "localhost:%u.%u",
2624 s->display_number, s->screen);
2625 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2626 s->display_number, s->screen);
2627 s->display = xstrdup(display);
2628 s->auth_display = xstrdup(auth_display);
2630 #ifdef IPADDR_IN_DISPLAY
2632 struct in_addr my_addr;
2634 he = gethostbyname(hostname);
2636 error("Can't get IP address for X11 DISPLAY.");
2637 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2640 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2641 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2642 s->display_number, s->screen);
2644 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2645 s->display_number, s->screen);
2647 s->display = xstrdup(display);
2648 s->auth_display = xstrdup(display);
2655 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2657 server_loop2(ssh, authctxt);
2661 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2663 static int called = 0;
2665 debug("do_cleanup");
2667 /* no cleanup if we're in the child for login shell */
2671 /* avoid double cleanup */
2676 if (authctxt == NULL)
2680 if (options.use_pam) {
2682 sshpam_thread_cleanup();
2686 if (!authctxt->authenticated)
2690 if (options.kerberos_ticket_cleanup &&
2692 krb5_cleanup_proc(authctxt);
2696 if (options.gss_cleanup_creds)
2697 ssh_gssapi_cleanup_creds();
2700 /* remove agent socket */
2701 auth_sock_cleanup_proc(authctxt->pw);
2703 /* remove userauth info */
2704 if (auth_info_file != NULL) {
2705 temporarily_use_uid(authctxt->pw);
2706 unlink(auth_info_file);
2708 free(auth_info_file);
2709 auth_info_file = NULL;
2713 * Cleanup ptys/utmp only if privsep is disabled,
2714 * or if running in monitor.
2716 if (!use_privsep || mm_is_monitor())
2717 session_destroy_all(ssh, session_pty_cleanup2);
2720 /* Return a name for the remote host that fits inside utmp_size */
2723 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2725 const char *remote = "";
2728 remote = auth_get_canonical_hostname(ssh, use_dns);
2729 if (utmp_size == 0 || strlen(remote) > utmp_size)
2730 remote = ssh_remote_ipaddr(ssh);