1 /* $OpenBSD: session.c,v 1.305 2018/07/25 13:56:23 deraadt 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 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)";
709 if (forced != NULL) {
710 if (IS_INTERNAL_SFTP(command)) {
711 s->is_subsystem = s->is_subsystem ?
712 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
713 } else if (s->is_subsystem)
714 s->is_subsystem = SUBSYSTEM_EXT;
715 snprintf(session_type, sizeof(session_type),
716 "forced-command %s '%.900s'", forced, command);
717 } else if (s->is_subsystem) {
718 snprintf(session_type, sizeof(session_type),
719 "subsystem '%.900s'", s->subsys);
720 } else if (command == NULL) {
721 snprintf(session_type, sizeof(session_type), "shell");
723 /* NB. we don't log unforced commands to preserve privacy */
724 snprintf(session_type, sizeof(session_type), "command");
727 if (s->ttyfd != -1) {
729 if (strncmp(tty, "/dev/", 5) == 0)
733 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
735 tty == NULL ? "" : " on ",
736 tty == NULL ? "" : tty,
738 ssh_remote_ipaddr(ssh),
739 ssh_remote_port(ssh),
742 #ifdef SSH_AUDIT_EVENTS
744 PRIVSEP(audit_run_command(command));
745 else if (s->ttyfd == -1) {
746 char *shell = s->pw->pw_shell;
748 if (shell[0] == '\0') /* empty shell means /bin/sh */
750 PRIVSEP(audit_run_command(shell));
754 ret = do_exec_pty(ssh, s, command);
756 ret = do_exec_no_pty(ssh, s, command);
758 original_command = NULL;
761 * Clear loginmsg: it's the child's responsibility to display
762 * it to the user, otherwise multiple sessions may accumulate
763 * multiple copies of the login messages.
765 sshbuf_reset(loginmsg);
770 /* administrative, login(1)-like work */
772 do_login(struct ssh *ssh, Session *s, const char *command)
775 struct sockaddr_storage from;
776 struct passwd * pw = s->pw;
777 pid_t pid = getpid();
780 * Get IP address of client. If the connection is not a socket, let
781 * the address be 0.0.0.0.
783 memset(&from, 0, sizeof(from));
784 fromlen = sizeof(from);
785 if (packet_connection_is_on_socket()) {
786 if (getpeername(packet_get_connection_in(),
787 (struct sockaddr *)&from, &fromlen) < 0) {
788 debug("getpeername: %.100s", strerror(errno));
793 /* Record that there was a login on that tty from the remote host. */
795 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
796 session_get_remote_name_or_ip(ssh, utmp_len,
798 (struct sockaddr *)&from, fromlen);
802 * If password change is needed, do it now.
803 * This needs to occur before the ~/.hushlogin check.
805 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
808 s->authctxt->force_pwchange = 0;
809 /* XXX - signal [net] parent to enable forwardings */
813 if (check_quietlogin(s, command))
822 * Display the message of the day.
830 if (options.print_motd) {
831 #ifdef HAVE_LOGIN_CAP
832 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
835 f = fopen("/etc/motd", "r");
838 while (fgets(buf, sizeof(buf), f))
847 * Check for quiet login, either .hushlogin or command given.
850 check_quietlogin(Session *s, const char *command)
853 struct passwd *pw = s->pw;
856 /* Return 1 if .hushlogin exists or a command given. */
859 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
860 #ifdef HAVE_LOGIN_CAP
861 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
864 if (stat(buf, &st) >= 0)
871 * Reads environment variables from the given file and adds/overrides them
872 * into the environment. If the file does not exist, this does nothing.
873 * Otherwise, it must consist of empty lines, comments (line starts with '#')
874 * and assignments of the form name=value. No other forms are allowed.
875 * If whitelist is not NULL, then it is interpreted as a pattern list and
876 * only variable names that match it will be accepted.
879 read_environment_file(char ***env, u_int *envsize,
880 const char *filename, const char *whitelist)
883 char *line = NULL, *cp, *value;
887 f = fopen(filename, "r");
891 while (getline(&line, &linesize, f) != -1) {
893 fatal("Too many lines in environment file %s", filename);
894 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
896 if (!*cp || *cp == '#' || *cp == '\n')
899 cp[strcspn(cp, "\n")] = '\0';
901 value = strchr(cp, '=');
903 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
908 * Replace the equals sign by nul, and advance value to
913 if (whitelist != NULL &&
914 match_pattern_list(cp, whitelist, 0) != 1)
916 child_set_env(env, envsize, cp, value);
922 #ifdef HAVE_ETC_DEFAULT_LOGIN
924 * Return named variable from specified environment, or NULL if not present.
927 child_get_env(char **env, const char *name)
933 for (i=0; env[i] != NULL; i++)
934 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
935 return(env[i] + len + 1);
940 * Read /etc/default/login.
941 * We pick up the PATH (or SUPATH for root) and UMASK.
944 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
946 char **tmpenv = NULL, *var;
947 u_int i, tmpenvsize = 0;
951 * We don't want to copy the whole file to the child's environment,
952 * so we use a temporary environment and copy the variables we're
955 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
956 options.permit_user_env_whitelist);
962 var = child_get_env(tmpenv, "SUPATH");
964 var = child_get_env(tmpenv, "PATH");
966 child_set_env(env, envsize, "PATH", var);
968 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
969 if (sscanf(var, "%5lo", &mask) == 1)
972 for (i = 0; tmpenv[i] != NULL; i++)
976 #endif /* HAVE_ETC_DEFAULT_LOGIN */
979 copy_environment_blacklist(char **source, char ***env, u_int *envsize,
980 const char *blacklist)
982 char *var_name, *var_val;
988 for(i = 0; source[i] != NULL; i++) {
989 var_name = xstrdup(source[i]);
990 if ((var_val = strstr(var_name, "=")) == NULL) {
996 if (blacklist == NULL ||
997 match_pattern_list(var_name, blacklist, 0) != 1) {
998 debug3("Copy environment: %s=%s", var_name, var_val);
999 child_set_env(env, envsize, var_name, var_val);
1007 copy_environment(char **source, char ***env, u_int *envsize)
1009 copy_environment_blacklist(source, env, envsize, NULL);
1013 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
1018 char *ocp, *cp, *value, **env, *laddr;
1019 struct passwd *pw = s->pw;
1020 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1023 extern char **environ;
1024 char **senv, **var, *val;
1027 /* Initialize the environment. */
1029 env = xcalloc(envsize, sizeof(char *));
1034 * The Windows environment contains some setting which are
1035 * important for a running system. They must not be dropped.
1040 p = fetch_windows_environment();
1041 copy_environment(p, &env, &envsize);
1042 free_windows_environment(p);
1047 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1050 /* Allow any GSSAPI methods that we've used to alter
1051 * the childs environment as they see fit
1053 ssh_gssapi_do_child(&env, &envsize);
1056 /* Set basic environment. */
1057 for (i = 0; i < s->num_env; i++)
1058 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1060 child_set_env(&env, &envsize, "USER", pw->pw_name);
1061 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1063 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1065 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1066 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
1067 child_set_env(&env, &envsize, "MAIL", buf);
1068 #ifdef HAVE_LOGIN_CAP
1069 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1070 child_set_env(&env, &envsize, "TERM", "su");
1072 * Temporarily swap out our real environment with an empty one,
1073 * let setusercontext() apply any environment variables defined
1074 * for the user's login class, copy those variables to the child,
1075 * free the temporary environment, and restore the original.
1078 environ = xmalloc(sizeof(*environ));
1080 (void)setusercontext(lc, pw, pw->pw_uid, LOGIN_SETENV|LOGIN_SETPATH);
1081 for (var = environ; *var != NULL; ++var) {
1082 if ((val = strchr(*var, '=')) != NULL) {
1084 child_set_env(&env, &envsize, *var, val);
1090 #else /* HAVE_LOGIN_CAP */
1091 # ifndef HAVE_CYGWIN
1093 * There's no standard path on Windows. The path contains
1094 * important components pointing to the system directories,
1095 * needed for loading shared libraries. So the path better
1096 * remains intact here.
1098 # ifdef HAVE_ETC_DEFAULT_LOGIN
1099 read_etc_default_login(&env, &envsize, pw->pw_uid);
1100 path = child_get_env(env, "PATH");
1101 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1102 if (path == NULL || *path == '\0') {
1103 child_set_env(&env, &envsize, "PATH",
1104 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1106 # endif /* HAVE_CYGWIN */
1107 #endif /* HAVE_LOGIN_CAP */
1109 /* Normal systems set SHELL by default. */
1110 child_set_env(&env, &envsize, "SHELL", shell);
1113 child_set_env(&env, &envsize, "TERM", s->term);
1115 child_set_env(&env, &envsize, "DISPLAY", s->display);
1118 * Since we clear KRB5CCNAME at startup, if it's set now then it
1119 * must have been set by a native authentication method (eg AIX or
1120 * SIA), so copy it to the child.
1125 if ((cp = getenv("KRB5CCNAME")) != NULL)
1126 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1133 if ((cp = getenv("AUTHSTATE")) != NULL)
1134 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1135 read_environment_file(&env, &envsize, "/etc/environment",
1136 options.permit_user_env_whitelist);
1140 if (s->authctxt->krb5_ccname)
1141 child_set_env(&env, &envsize, "KRB5CCNAME",
1142 s->authctxt->krb5_ccname);
1144 if (auth_sock_name != NULL)
1145 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1149 /* Set custom environment options from pubkey authentication. */
1150 if (options.permit_user_env) {
1151 for (n = 0 ; n < auth_opts->nenv; n++) {
1152 ocp = xstrdup(auth_opts->env[n]);
1153 cp = strchr(ocp, '=');
1156 /* Apply PermitUserEnvironment whitelist */
1157 if (options.permit_user_env_whitelist == NULL ||
1158 match_pattern_list(ocp,
1159 options.permit_user_env_whitelist, 0) == 1)
1160 child_set_env(&env, &envsize,
1167 /* read $HOME/.ssh/environment. */
1168 if (options.permit_user_env) {
1169 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1171 read_environment_file(&env, &envsize, buf,
1172 options.permit_user_env_whitelist);
1177 * Pull in any environment variables that may have
1180 if (options.use_pam) {
1184 * Don't allow SSH_AUTH_INFO variables posted to PAM to leak
1185 * back into the environment.
1187 p = fetch_pam_child_environment();
1188 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1189 free_pam_environment(p);
1191 p = fetch_pam_environment();
1192 copy_environment_blacklist(p, &env, &envsize, "SSH_AUTH_INFO*");
1193 free_pam_environment(p);
1195 #endif /* USE_PAM */
1197 /* Environment specified by admin */
1198 for (i = 0; i < options.num_setenv; i++) {
1199 cp = xstrdup(options.setenv[i]);
1200 if ((value = strchr(cp, '=')) == NULL) {
1201 /* shouldn't happen; vars are checked in servconf.c */
1202 fatal("Invalid config SetEnv: %s", options.setenv[i]);
1205 child_set_env(&env, &envsize, cp, value);
1208 /* SSH_CLIENT deprecated */
1209 snprintf(buf, sizeof buf, "%.50s %d %d",
1210 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1211 ssh_local_port(ssh));
1212 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1214 laddr = get_local_ipaddr(packet_get_connection_in());
1215 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1216 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1217 laddr, ssh_local_port(ssh));
1219 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1221 if (tun_fwd_ifnames != NULL)
1222 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1223 if (auth_info_file != NULL)
1224 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1226 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1227 if (original_command)
1228 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1232 /* dump the environment */
1233 fprintf(stderr, "Environment:\n");
1234 for (i = 0; env[i]; i++)
1235 fprintf(stderr, " %.200s\n", env[i]);
1241 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1242 * first in this order).
1245 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1253 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1255 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1256 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1257 auth_opts->permit_user_rc && options.permit_user_rc &&
1258 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1259 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1260 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1262 fprintf(stderr, "Running %s\n", cmd);
1263 f = popen(cmd, "w");
1266 fprintf(f, "%s %s\n", s->auth_proto,
1270 fprintf(stderr, "Could not run %s\n",
1272 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1274 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1275 _PATH_SSH_SYSTEM_RC);
1276 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1279 fprintf(f, "%s %s\n", s->auth_proto,
1283 fprintf(stderr, "Could not run %s\n",
1284 _PATH_SSH_SYSTEM_RC);
1285 } else if (do_xauth && options.xauth_location != NULL) {
1286 /* Add authority data to .Xauthority if appropriate. */
1289 "Running %.500s remove %.100s\n",
1290 options.xauth_location, s->auth_display);
1292 "%.500s add %.100s %.100s %.100s\n",
1293 options.xauth_location, s->auth_display,
1294 s->auth_proto, s->auth_data);
1296 snprintf(cmd, sizeof cmd, "%s -q -",
1297 options.xauth_location);
1298 f = popen(cmd, "w");
1300 fprintf(f, "remove %s\n",
1302 fprintf(f, "add %s %s %s\n",
1303 s->auth_display, s->auth_proto,
1307 fprintf(stderr, "Could not run %s\n",
1314 do_nologin(struct passwd *pw)
1318 char buf[1024], *def_nl = _PATH_NOLOGIN;
1321 #ifdef HAVE_LOGIN_CAP
1322 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1324 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1326 if (pw->pw_uid == 0)
1330 if (stat(nl, &sb) == -1)
1333 /* /etc/nologin exists. Print its contents if we can and exit. */
1334 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1335 if ((f = fopen(nl, "r")) != NULL) {
1336 while (fgets(buf, sizeof(buf), f))
1344 * Chroot into a directory after checking it for safety: all path components
1345 * must be root-owned directories with strict permissions.
1348 safely_chroot(const char *path, uid_t uid)
1351 char component[PATH_MAX];
1355 fatal("chroot path does not begin at root");
1356 if (strlen(path) >= sizeof(component))
1357 fatal("chroot path too long");
1360 * Descend the path, checking that each component is a
1361 * root-owned directory with strict permissions.
1363 for (cp = path; cp != NULL;) {
1364 if ((cp = strchr(cp, '/')) == NULL)
1365 strlcpy(component, path, sizeof(component));
1368 memcpy(component, path, cp - path);
1369 component[cp - path] = '\0';
1372 debug3("%s: checking '%s'", __func__, component);
1374 if (stat(component, &st) != 0)
1375 fatal("%s: stat(\"%s\"): %s", __func__,
1376 component, strerror(errno));
1377 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1378 fatal("bad ownership or modes for chroot "
1379 "directory %s\"%s\"",
1380 cp == NULL ? "" : "component ", component);
1381 if (!S_ISDIR(st.st_mode))
1382 fatal("chroot path %s\"%s\" is not a directory",
1383 cp == NULL ? "" : "component ", component);
1387 if (chdir(path) == -1)
1388 fatal("Unable to chdir to chroot path \"%s\": "
1389 "%s", path, strerror(errno));
1390 if (chroot(path) == -1)
1391 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1392 if (chdir("/") == -1)
1393 fatal("%s: chdir(/) after chroot: %s",
1394 __func__, strerror(errno));
1395 verbose("Changed root directory to \"%s\"", path);
1398 /* Set login name, uid, gid, and groups. */
1400 do_setusercontext(struct passwd *pw)
1402 char uidstr[32], *chroot_path, *tmp;
1404 platform_setusercontext(pw);
1406 if (platform_privileged_uidswap()) {
1407 #ifdef HAVE_LOGIN_CAP
1408 if (setusercontext(lc, pw, pw->pw_uid,
1409 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1410 perror("unable to set user context");
1414 if (setlogin(pw->pw_name) < 0)
1415 error("setlogin failed: %s", strerror(errno));
1416 if (setgid(pw->pw_gid) < 0) {
1420 /* Initialize the group list. */
1421 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1422 perror("initgroups");
1428 platform_setusercontext_post_groups(pw);
1430 if (!in_chroot && options.chroot_directory != NULL &&
1431 strcasecmp(options.chroot_directory, "none") != 0) {
1432 tmp = tilde_expand_filename(options.chroot_directory,
1434 snprintf(uidstr, sizeof(uidstr), "%llu",
1435 (unsigned long long)pw->pw_uid);
1436 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1437 "u", pw->pw_name, "U", uidstr, (char *)NULL);
1438 safely_chroot(chroot_path, pw->pw_uid);
1441 /* Make sure we don't attempt to chroot again */
1442 free(options.chroot_directory);
1443 options.chroot_directory = NULL;
1447 #ifdef HAVE_LOGIN_CAP
1448 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1449 perror("unable to set user context (setuser)");
1453 * FreeBSD's setusercontext() will not apply the user's
1454 * own umask setting unless running with the user's UID.
1456 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1460 * In a chroot environment, the set_id() will always fail;
1461 * typically because of the lack of necessary authentication
1462 * services and runtime such as ./usr/lib/libiaf.so,
1463 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1464 * internal sftp chroot case. We'll lose auditing and ACLs but
1465 * permanently_set_uid will take care of the rest.
1467 if (!in_chroot && set_id(pw->pw_name) != 0)
1468 fatal("set_id(%s) Failed", pw->pw_name);
1469 # endif /* USE_LIBIAF */
1470 /* Permanently switch to the desired uid. */
1471 permanently_set_uid(pw);
1473 } else if (options.chroot_directory != NULL &&
1474 strcasecmp(options.chroot_directory, "none") != 0) {
1475 fatal("server lacks privileges to chroot to ChrootDirectory");
1478 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1479 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1483 do_pwchange(Session *s)
1486 fprintf(stderr, "WARNING: Your password has expired.\n");
1487 if (s->ttyfd != -1) {
1489 "You must change your password now and login again!\n");
1493 #ifdef PASSWD_NEEDS_USERNAME
1494 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1497 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1502 "Password change required but no TTY available.\n");
1508 child_close_fds(struct ssh *ssh)
1510 extern int auth_sock;
1512 if (auth_sock != -1) {
1517 if (packet_get_connection_in() == packet_get_connection_out())
1518 close(packet_get_connection_in());
1520 close(packet_get_connection_in());
1521 close(packet_get_connection_out());
1524 * Close all descriptors related to channels. They will still remain
1525 * open in the parent.
1527 /* XXX better use close-on-exec? -markus */
1528 channel_close_all(ssh);
1531 * Close any extra file descriptors. Note that there may still be
1532 * descriptors left by system functions. They will be closed later.
1537 * Close any extra open file descriptors so that we don't have them
1538 * hanging around in clients. Note that we want to do this after
1539 * initgroups, because at least on Solaris 2.3 it leaves file
1542 closefrom(STDERR_FILENO + 1);
1546 * Performs common processing for the child, such as setting up the
1547 * environment, closing extra file descriptors, setting the user and group
1548 * ids, and executing the command or shell.
1552 do_child(struct ssh *ssh, Session *s, const char *command)
1554 extern char **environ;
1556 char *argv[ARGV_MAX];
1557 const char *shell, *shell0;
1558 struct passwd *pw = s->pw;
1561 /* remove hostkey from the child's memory */
1562 destroy_sensitive_data();
1563 packet_clear_keys();
1565 /* Force a password change */
1566 if (s->authctxt->force_pwchange) {
1567 do_setusercontext(pw);
1568 child_close_fds(ssh);
1574 * Login(1) does this as well, and it needs uid 0 for the "-h"
1575 * switch, so we let login(1) to this for us.
1578 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1579 if (!check_quietlogin(s, command))
1581 #else /* HAVE_OSF_SIA */
1582 /* When PAM is enabled we rely on it to do the nologin check */
1583 if (!options.use_pam)
1585 do_setusercontext(pw);
1587 * PAM session modules in do_setusercontext may have
1588 * generated messages, so if this in an interactive
1589 * login then display them too.
1591 if (!check_quietlogin(s, command))
1593 #endif /* HAVE_OSF_SIA */
1596 if (options.use_pam && !is_pam_session_open()) {
1597 debug3("PAM session not opened, exiting");
1604 * Get the shell from the password data. An empty shell field is
1605 * legal, and means /bin/sh.
1607 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1610 * Make sure $SHELL points to the shell from the password file,
1611 * even if shell is overridden from login.conf
1613 env = do_setup_env(ssh, s, shell);
1615 #ifdef HAVE_LOGIN_CAP
1616 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1620 * Close the connection descriptors; note that this is the child, and
1621 * the server will still have the socket open, and it is important
1622 * that we do not shutdown it. Note that the descriptors cannot be
1623 * closed before building the environment, as we call
1624 * ssh_remote_ipaddr there.
1626 child_close_fds(ssh);
1629 * Must take new environment into use so that .ssh/rc,
1630 * /etc/ssh/sshrc and xauth are run in the proper environment.
1634 #if defined(KRB5) && defined(USE_AFS)
1636 * At this point, we check to see if AFS is active and if we have
1637 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1638 * if we can (and need to) extend the ticket into an AFS token. If
1639 * we don't do this, we run into potential problems if the user's
1640 * home directory is in AFS and it's not world-readable.
1643 if (options.kerberos_get_afs_token && k_hasafs() &&
1644 (s->authctxt->krb5_ctx != NULL)) {
1647 debug("Getting AFS token");
1651 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1652 krb5_afslog(s->authctxt->krb5_ctx,
1653 s->authctxt->krb5_fwd_ccache, cell, NULL);
1655 krb5_afslog_home(s->authctxt->krb5_ctx,
1656 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1660 /* Change current directory to the user's home directory. */
1661 if (chdir(pw->pw_dir) < 0) {
1662 /* Suppress missing homedir warning for chroot case */
1663 #ifdef HAVE_LOGIN_CAP
1664 r = login_getcapbool(lc, "requirehome", 0);
1666 if (r || !in_chroot) {
1667 fprintf(stderr, "Could not chdir to home "
1668 "directory %s: %s\n", pw->pw_dir,
1675 closefrom(STDERR_FILENO + 1);
1677 do_rc_files(ssh, s, shell);
1679 /* restore SIGPIPE for child */
1680 signal(SIGPIPE, SIG_DFL);
1682 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1683 printf("This service allows sftp connections only.\n");
1686 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1687 extern int optind, optreset;
1691 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1692 args = xstrdup(command ? command : "sftp-server");
1693 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1694 if (i < ARGV_MAX - 1)
1697 optind = optreset = 1;
1698 __progname = argv[0];
1700 ssh_selinux_change_context("sftpd_t");
1702 exit(sftp_server_main(i, argv, s->pw));
1707 /* Get the last component of the shell name. */
1708 if ((shell0 = strrchr(shell, '/')) != NULL)
1714 * If we have no command, execute the shell. In this case, the shell
1715 * name to be passed in argv[0] is preceded by '-' to indicate that
1716 * this is a login shell.
1721 /* Start the shell. Set initial character to '-'. */
1724 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1725 >= sizeof(argv0) - 1) {
1731 /* Execute the shell. */
1734 execve(shell, argv, env);
1736 /* Executing the shell failed. */
1741 * Execute the command using the user's shell. This uses the -c
1742 * option to execute the command.
1744 argv[0] = (char *) shell0;
1746 argv[2] = (char *) command;
1748 execve(shell, argv, env);
1754 session_unused(int id)
1756 debug3("%s: session id %d unused", __func__, id);
1757 if (id >= options.max_sessions ||
1758 id >= sessions_nalloc) {
1759 fatal("%s: insane session id %d (max %d nalloc %d)",
1760 __func__, id, options.max_sessions, sessions_nalloc);
1762 memset(&sessions[id], 0, sizeof(*sessions));
1763 sessions[id].self = id;
1764 sessions[id].used = 0;
1765 sessions[id].chanid = -1;
1766 sessions[id].ptyfd = -1;
1767 sessions[id].ttyfd = -1;
1768 sessions[id].ptymaster = -1;
1769 sessions[id].x11_chanids = NULL;
1770 sessions[id].next_unused = sessions_first_unused;
1771 sessions_first_unused = id;
1779 if (sessions_first_unused == -1) {
1780 if (sessions_nalloc >= options.max_sessions)
1782 debug2("%s: allocate (allocated %d max %d)",
1783 __func__, sessions_nalloc, options.max_sessions);
1784 tmp = xrecallocarray(sessions, sessions_nalloc,
1785 sessions_nalloc + 1, sizeof(*sessions));
1787 error("%s: cannot allocate %d sessions",
1788 __func__, sessions_nalloc + 1);
1792 session_unused(sessions_nalloc++);
1795 if (sessions_first_unused >= sessions_nalloc ||
1796 sessions_first_unused < 0) {
1797 fatal("%s: insane first_unused %d max %d nalloc %d",
1798 __func__, sessions_first_unused, options.max_sessions,
1802 s = &sessions[sessions_first_unused];
1804 fatal("%s: session %d already used",
1805 __func__, sessions_first_unused);
1807 sessions_first_unused = s->next_unused;
1809 s->next_unused = -1;
1810 debug("session_new: session %d", s->self);
1819 for (i = 0; i < sessions_nalloc; i++) {
1820 Session *s = &sessions[i];
1822 debug("dump: used %d next_unused %d session %d %p "
1823 "channel %d pid %ld",
1834 session_open(Authctxt *authctxt, int chanid)
1836 Session *s = session_new();
1837 debug("session_open: channel %d", chanid);
1839 error("no more sessions");
1842 s->authctxt = authctxt;
1843 s->pw = authctxt->pw;
1844 if (s->pw == NULL || !authctxt->valid)
1845 fatal("no user for session %d", s->self);
1846 debug("session_open: session %d: link with channel %d", s->self, chanid);
1852 session_by_tty(char *tty)
1855 for (i = 0; i < sessions_nalloc; i++) {
1856 Session *s = &sessions[i];
1857 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1858 debug("session_by_tty: session %d tty %s", i, tty);
1862 debug("session_by_tty: unknown tty %.100s", tty);
1868 session_by_channel(int id)
1871 for (i = 0; i < sessions_nalloc; i++) {
1872 Session *s = &sessions[i];
1873 if (s->used && s->chanid == id) {
1874 debug("session_by_channel: session %d channel %d",
1879 debug("session_by_channel: unknown channel %d", id);
1885 session_by_x11_channel(int id)
1889 for (i = 0; i < sessions_nalloc; i++) {
1890 Session *s = &sessions[i];
1892 if (s->x11_chanids == NULL || !s->used)
1894 for (j = 0; s->x11_chanids[j] != -1; j++) {
1895 if (s->x11_chanids[j] == id) {
1896 debug("session_by_x11_channel: session %d "
1897 "channel %d", s->self, id);
1902 debug("session_by_x11_channel: unknown channel %d", id);
1908 session_by_pid(pid_t pid)
1911 debug("session_by_pid: pid %ld", (long)pid);
1912 for (i = 0; i < sessions_nalloc; i++) {
1913 Session *s = &sessions[i];
1914 if (s->used && s->pid == pid)
1917 error("session_by_pid: unknown pid %ld", (long)pid);
1923 session_window_change_req(struct ssh *ssh, Session *s)
1925 s->col = packet_get_int();
1926 s->row = packet_get_int();
1927 s->xpixel = packet_get_int();
1928 s->ypixel = packet_get_int();
1930 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1935 session_pty_req(struct ssh *ssh, Session *s)
1939 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1940 debug("Allocating a pty not permitted for this connection.");
1943 if (s->ttyfd != -1) {
1944 packet_disconnect("Protocol error: you already have a pty.");
1948 s->term = packet_get_string(&len);
1949 s->col = packet_get_int();
1950 s->row = packet_get_int();
1951 s->xpixel = packet_get_int();
1952 s->ypixel = packet_get_int();
1954 if (strcmp(s->term, "") == 0) {
1959 /* Allocate a pty and open it. */
1960 debug("Allocating pty.");
1961 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1967 error("session_pty_req: session %d alloc failed", s->self);
1970 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1972 ssh_tty_parse_modes(ssh, s->ttyfd);
1975 pty_setowner(s->pw, s->tty);
1977 /* Set window size from the packet. */
1978 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1981 session_proctitle(s);
1986 session_subsystem_req(struct ssh *ssh, Session *s)
1994 s->subsys = packet_get_string(&len);
1996 debug2("subsystem request for %.100s by user %s", s->subsys,
1999 for (i = 0; i < options.num_subsystems; i++) {
2000 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
2001 prog = options.subsystem_command[i];
2002 cmd = options.subsystem_args[i];
2003 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2004 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2005 debug("subsystem: %s", prog);
2007 if (stat(prog, &st) < 0)
2008 debug("subsystem: cannot stat %s: %s",
2009 prog, strerror(errno));
2010 s->is_subsystem = SUBSYSTEM_EXT;
2011 debug("subsystem: exec() %s", cmd);
2013 success = do_exec(ssh, s, cmd) == 0;
2019 logit("subsystem request for %.100s by user %s failed, "
2020 "subsystem not found", s->subsys, s->pw->pw_name);
2026 session_x11_req(struct ssh *ssh, Session *s)
2030 if (s->auth_proto != NULL || s->auth_data != NULL) {
2031 error("session_x11_req: session %d: "
2032 "x11 forwarding already active", s->self);
2035 s->single_connection = packet_get_char();
2036 s->auth_proto = packet_get_string(NULL);
2037 s->auth_data = packet_get_string(NULL);
2038 s->screen = packet_get_int();
2041 if (xauth_valid_string(s->auth_proto) &&
2042 xauth_valid_string(s->auth_data))
2043 success = session_setup_x11fwd(ssh, s);
2046 error("Invalid X11 forwarding data");
2049 free(s->auth_proto);
2051 s->auth_proto = NULL;
2052 s->auth_data = NULL;
2058 session_shell_req(struct ssh *ssh, Session *s)
2061 return do_exec(ssh, s, NULL) == 0;
2065 session_exec_req(struct ssh *ssh, Session *s)
2069 char *command = packet_get_string(&len);
2071 success = do_exec(ssh, s, command) == 0;
2077 session_break_req(struct ssh *ssh, Session *s)
2080 packet_get_int(); /* ignored */
2083 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2089 session_env_req(struct ssh *ssh, Session *s)
2092 u_int name_len, val_len, i;
2094 name = packet_get_cstring(&name_len);
2095 val = packet_get_cstring(&val_len);
2098 /* Don't set too many environment variables */
2099 if (s->num_env > 128) {
2100 debug2("Ignoring env request %s: too many env vars", name);
2104 for (i = 0; i < options.num_accept_env; i++) {
2105 if (match_pattern(name, options.accept_env[i])) {
2106 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2107 s->env = xrecallocarray(s->env, s->num_env,
2108 s->num_env + 1, sizeof(*s->env));
2109 s->env[s->num_env].name = name;
2110 s->env[s->num_env].val = val;
2115 debug2("Ignoring env request %s: disallowed name", name);
2124 session_auth_agent_req(struct ssh *ssh, Session *s)
2126 static int called = 0;
2129 if (!auth_opts->permit_agent_forwarding_flag ||
2130 !options.allow_agent_forwarding) {
2131 debug("%s: agent forwarding disabled", __func__);
2138 return auth_input_request_forwarding(ssh, s->pw);
2143 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2148 if ((s = session_by_channel(c->self)) == NULL) {
2149 logit("%s: no session %d req %.100s", __func__, c->self, rtype);
2152 debug("%s: session %d req %s", __func__, s->self, rtype);
2155 * a session is in LARVAL state until a shell, a command
2156 * or a subsystem is executed
2158 if (c->type == SSH_CHANNEL_LARVAL) {
2159 if (strcmp(rtype, "shell") == 0) {
2160 success = session_shell_req(ssh, s);
2161 } else if (strcmp(rtype, "exec") == 0) {
2162 success = session_exec_req(ssh, s);
2163 } else if (strcmp(rtype, "pty-req") == 0) {
2164 success = session_pty_req(ssh, s);
2165 } else if (strcmp(rtype, "x11-req") == 0) {
2166 success = session_x11_req(ssh, s);
2167 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2168 success = session_auth_agent_req(ssh, s);
2169 } else if (strcmp(rtype, "subsystem") == 0) {
2170 success = session_subsystem_req(ssh, s);
2171 } else if (strcmp(rtype, "env") == 0) {
2172 success = session_env_req(ssh, s);
2175 if (strcmp(rtype, "window-change") == 0) {
2176 success = session_window_change_req(ssh, s);
2177 } else if (strcmp(rtype, "break") == 0) {
2178 success = session_break_req(ssh, s);
2185 session_set_fds(struct ssh *ssh, Session *s,
2186 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2189 * now that have a child and a pipe to the child,
2190 * we can activate our channel and register the fd's
2192 if (s->chanid == -1)
2193 fatal("no channel for session %d", s->self);
2194 channel_set_fds(ssh, s->chanid,
2196 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2197 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2201 * Function to perform pty cleanup. Also called if we get aborted abnormally
2202 * (e.g., due to a dropped connection).
2205 session_pty_cleanup2(Session *s)
2208 error("session_pty_cleanup: no session");
2214 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2216 /* Record that the user has logged out. */
2218 record_logout(s->pid, s->tty, s->pw->pw_name);
2220 /* Release the pseudo-tty. */
2222 pty_release(s->tty);
2225 * Close the server side of the socket pairs. We must do this after
2226 * the pty cleanup, so that another process doesn't get this pty
2227 * while we're still cleaning up.
2229 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2230 error("close(s->ptymaster/%d): %s",
2231 s->ptymaster, strerror(errno));
2233 /* unlink pty from session */
2238 session_pty_cleanup(Session *s)
2240 PRIVSEP(session_pty_cleanup2(s));
2246 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2261 return "SIG@openssh.com";
2265 session_close_x11(struct ssh *ssh, int id)
2269 if ((c = channel_by_id(ssh, id)) == NULL) {
2270 debug("%s: x11 channel %d missing", __func__, id);
2272 /* Detach X11 listener */
2273 debug("%s: detach x11 channel %d", __func__, id);
2274 channel_cancel_cleanup(ssh, id);
2275 if (c->ostate != CHAN_OUTPUT_CLOSED)
2276 chan_mark_dead(ssh, c);
2281 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2286 debug3("%s: channel %d", __func__, id);
2287 channel_cancel_cleanup(ssh, id);
2288 if ((s = session_by_x11_channel(id)) == NULL)
2289 fatal("%s: no x11 channel %d", __func__, id);
2290 for (i = 0; s->x11_chanids[i] != -1; i++) {
2291 debug("%s: session %d: closing channel %d",
2292 __func__, s->self, s->x11_chanids[i]);
2294 * The channel "id" is already closing, but make sure we
2295 * close all of its siblings.
2297 if (s->x11_chanids[i] != id)
2298 session_close_x11(ssh, s->x11_chanids[i]);
2300 free(s->x11_chanids);
2301 s->x11_chanids = NULL;
2304 free(s->auth_proto);
2305 s->auth_proto = NULL;
2307 s->auth_data = NULL;
2308 free(s->auth_display);
2309 s->auth_display = NULL;
2313 session_exit_message(struct ssh *ssh, Session *s, int status)
2317 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2318 fatal("%s: session %d: no channel %d",
2319 __func__, s->self, s->chanid);
2320 debug("%s: session %d channel %d pid %ld",
2321 __func__, s->self, s->chanid, (long)s->pid);
2323 if (WIFEXITED(status)) {
2324 channel_request_start(ssh, s->chanid, "exit-status", 0);
2325 packet_put_int(WEXITSTATUS(status));
2327 } else if (WIFSIGNALED(status)) {
2328 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2329 packet_put_cstring(sig2name(WTERMSIG(status)));
2331 packet_put_char(WCOREDUMP(status)? 1 : 0);
2332 #else /* WCOREDUMP */
2334 #endif /* WCOREDUMP */
2335 packet_put_cstring("");
2336 packet_put_cstring("");
2339 /* Some weird exit cause. Just exit. */
2340 packet_disconnect("wait returned status %04x.", status);
2343 /* disconnect channel */
2344 debug("%s: release channel %d", __func__, s->chanid);
2347 * Adjust cleanup callback attachment to send close messages when
2348 * the channel gets EOF. The session will be then be closed
2349 * by session_close_by_channel when the childs close their fds.
2351 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2354 * emulate a write failure with 'chan_write_failed', nobody will be
2355 * interested in data we write.
2356 * Note that we must not call 'chan_read_failed', since there could
2357 * be some more data waiting in the pipe.
2359 if (c->ostate != CHAN_OUTPUT_CLOSED)
2360 chan_write_failed(ssh, c);
2364 session_close(struct ssh *ssh, Session *s)
2368 verbose("Close session: user %s from %.200s port %d id %d",
2370 ssh_remote_ipaddr(ssh),
2371 ssh_remote_port(ssh),
2375 session_pty_cleanup(s);
2378 free(s->x11_chanids);
2379 free(s->auth_display);
2381 free(s->auth_proto);
2383 if (s->env != NULL) {
2384 for (i = 0; i < s->num_env; i++) {
2385 free(s->env[i].name);
2386 free(s->env[i].val);
2390 session_proctitle(s);
2391 session_unused(s->self);
2395 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2397 Session *s = session_by_pid(pid);
2399 debug("%s: no session for pid %ld", __func__, (long)pid);
2402 if (s->chanid != -1)
2403 session_exit_message(ssh, s, status);
2405 session_pty_cleanup(s);
2410 * this is called when a channel dies before
2411 * the session 'child' itself dies
2414 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2416 Session *s = session_by_channel(id);
2420 debug("%s: no session for id %d", __func__, id);
2423 debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
2425 debug("%s: channel %d: has child", __func__, id);
2427 * delay detach of session, but release pty, since
2428 * the fd's to the child are already closed
2431 session_pty_cleanup(s);
2434 /* detach by removing callback */
2435 channel_cancel_cleanup(ssh, s->chanid);
2437 /* Close any X11 listeners associated with this session */
2438 if (s->x11_chanids != NULL) {
2439 for (i = 0; s->x11_chanids[i] != -1; i++) {
2440 session_close_x11(ssh, s->x11_chanids[i]);
2441 s->x11_chanids[i] = -1;
2446 session_close(ssh, s);
2450 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2453 for (i = 0; i < sessions_nalloc; i++) {
2454 Session *s = &sessions[i];
2456 if (closefunc != NULL)
2459 session_close(ssh, s);
2465 session_tty_list(void)
2467 static char buf[1024];
2472 for (i = 0; i < sessions_nalloc; i++) {
2473 Session *s = &sessions[i];
2474 if (s->used && s->ttyfd != -1) {
2476 if (strncmp(s->tty, "/dev/", 5) != 0) {
2477 cp = strrchr(s->tty, '/');
2478 cp = (cp == NULL) ? s->tty : cp + 1;
2483 strlcat(buf, ",", sizeof buf);
2484 strlcat(buf, cp, sizeof buf);
2488 strlcpy(buf, "notty", sizeof buf);
2493 session_proctitle(Session *s)
2496 error("no user for session %d", s->self);
2498 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2502 session_setup_x11fwd(struct ssh *ssh, Session *s)
2505 char display[512], auth_display[512];
2506 char hostname[NI_MAXHOST];
2509 if (!auth_opts->permit_x11_forwarding_flag) {
2510 packet_send_debug("X11 forwarding disabled by key options.");
2513 if (!options.x11_forwarding) {
2514 debug("X11 forwarding disabled in server configuration file.");
2517 if (options.xauth_location == NULL ||
2518 (stat(options.xauth_location, &st) == -1)) {
2519 packet_send_debug("No xauth program; cannot forward X11.");
2522 if (s->display != NULL) {
2523 debug("X11 display already set.");
2526 if (x11_create_display_inet(ssh, options.x11_display_offset,
2527 options.x11_use_localhost, s->single_connection,
2528 &s->display_number, &s->x11_chanids) == -1) {
2529 debug("x11_create_display_inet failed.");
2532 for (i = 0; s->x11_chanids[i] != -1; i++) {
2533 channel_register_cleanup(ssh, s->x11_chanids[i],
2534 session_close_single_x11, 0);
2537 /* Set up a suitable value for the DISPLAY variable. */
2538 if (gethostname(hostname, sizeof(hostname)) < 0)
2539 fatal("gethostname: %.100s", strerror(errno));
2541 * auth_display must be used as the displayname when the
2542 * authorization entry is added with xauth(1). This will be
2543 * different than the DISPLAY string for localhost displays.
2545 if (options.x11_use_localhost) {
2546 snprintf(display, sizeof display, "localhost:%u.%u",
2547 s->display_number, s->screen);
2548 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2549 s->display_number, s->screen);
2550 s->display = xstrdup(display);
2551 s->auth_display = xstrdup(auth_display);
2553 #ifdef IPADDR_IN_DISPLAY
2555 struct in_addr my_addr;
2557 he = gethostbyname(hostname);
2559 error("Can't get IP address for X11 DISPLAY.");
2560 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2563 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2564 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2565 s->display_number, s->screen);
2567 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2568 s->display_number, s->screen);
2570 s->display = xstrdup(display);
2571 s->auth_display = xstrdup(display);
2578 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2580 server_loop2(ssh, authctxt);
2584 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2586 static int called = 0;
2588 debug("do_cleanup");
2590 /* no cleanup if we're in the child for login shell */
2594 /* avoid double cleanup */
2599 if (authctxt == NULL)
2603 if (options.use_pam) {
2605 sshpam_thread_cleanup();
2609 if (!authctxt->authenticated)
2613 if (options.kerberos_ticket_cleanup &&
2615 krb5_cleanup_proc(authctxt);
2619 if (options.gss_cleanup_creds)
2620 ssh_gssapi_cleanup_creds();
2623 /* remove agent socket */
2624 auth_sock_cleanup_proc(authctxt->pw);
2626 /* remove userauth info */
2627 if (auth_info_file != NULL) {
2628 temporarily_use_uid(authctxt->pw);
2629 unlink(auth_info_file);
2631 free(auth_info_file);
2632 auth_info_file = NULL;
2636 * Cleanup ptys/utmp only if privsep is disabled,
2637 * or if running in monitor.
2639 if (!use_privsep || mm_is_monitor())
2640 session_destroy_all(ssh, session_pty_cleanup2);
2643 /* Return a name for the remote host that fits inside utmp_size */
2646 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2648 const char *remote = "";
2651 remote = auth_get_canonical_hostname(ssh, use_dns);
2652 if (utmp_size == 0 || strlen(remote) > utmp_size)
2653 remote = ssh_remote_ipaddr(ssh);