1 /* $OpenBSD: session.c,v 1.315 2019/02/22 03:37: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.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
43 #include <sys/socket.h>
47 #include <arpa/inet.h>
66 #include "openbsd-compat/sys-queue.h"
85 #include "auth-options.h"
87 #include "pathnames.h"
92 #include "serverloop.h"
96 #include "monitor_wrap.h"
100 #if defined(KRB5) && defined(USE_AFS)
105 #include <selinux/selinux.h>
108 #define IS_INTERNAL_SFTP(c) \
109 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
110 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
111 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
112 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
116 Session *session_new(void);
117 void session_set_fds(struct ssh *, Session *, int, int, int, int, int);
118 void session_pty_cleanup(Session *);
119 void session_proctitle(Session *);
120 int session_setup_x11fwd(struct ssh *, Session *);
121 int do_exec_pty(struct ssh *, Session *, const char *);
122 int do_exec_no_pty(struct ssh *, Session *, const char *);
123 int do_exec(struct ssh *, Session *, const char *);
124 void do_login(struct ssh *, Session *, const char *);
125 void do_child(struct ssh *, Session *, const char *);
127 int check_quietlogin(Session *, const char *);
129 static void do_authenticated2(struct ssh *, Authctxt *);
131 static int session_pty_req(struct ssh *, Session *);
134 extern ServerOptions options;
135 extern char *__progname;
136 extern int debug_flag;
137 extern u_int utmp_len;
138 extern int startup_pipe;
139 extern void destroy_sensitive_data(void);
140 extern struct sshbuf *loginmsg;
141 extern struct sshauthopt *auth_opts;
142 extern char *tun_fwd_ifnames; /* serverloop.c */
144 /* original command from peer. */
145 const char *original_command = NULL;
148 static int sessions_first_unused = -1;
149 static int sessions_nalloc = 0;
150 static Session *sessions = NULL;
152 #define SUBSYSTEM_NONE 0
153 #define SUBSYSTEM_EXT 1
154 #define SUBSYSTEM_INT_SFTP 2
155 #define SUBSYSTEM_INT_SFTP_ERROR 3
157 #ifdef HAVE_LOGIN_CAP
161 static int is_child = 0;
162 static int in_chroot = 0;
164 /* File containing userauth info, if ExposeAuthInfo set */
165 static char *auth_info_file = NULL;
167 /* Name and directory of socket for authentication agent forwarding. */
168 static char *auth_sock_name = NULL;
169 static char *auth_sock_dir = NULL;
171 /* removes the agent forwarding socket */
174 auth_sock_cleanup_proc(struct passwd *pw)
176 if (auth_sock_name != NULL) {
177 temporarily_use_uid(pw);
178 unlink(auth_sock_name);
179 rmdir(auth_sock_dir);
180 auth_sock_name = NULL;
186 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
191 if (auth_sock_name != NULL) {
192 error("authentication forwarding requested twice.");
196 /* Temporarily drop privileged uid for mkdir/bind. */
197 temporarily_use_uid(pw);
199 /* Allocate a buffer for the socket name, and format the name. */
200 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
202 /* Create private directory for socket */
203 if (mkdtemp(auth_sock_dir) == NULL) {
204 ssh_packet_send_debug(ssh, "Agent forwarding disabled: "
205 "mkdtemp() failed: %.100s", strerror(errno));
208 auth_sock_dir = NULL;
212 xasprintf(&auth_sock_name, "%s/agent.%ld",
213 auth_sock_dir, (long) getpid());
215 /* Start a Unix listener on auth_sock_name. */
216 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
218 /* Restore the privileged uid. */
221 /* Check for socket/bind/listen failure. */
225 /* Allocate a channel for the authentication agent socket. */
226 nc = channel_new(ssh, "auth socket",
227 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
228 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
229 0, "auth socket", 1);
230 nc->path = xstrdup(auth_sock_name);
234 free(auth_sock_name);
235 if (auth_sock_dir != NULL) {
236 temporarily_use_uid(pw);
237 rmdir(auth_sock_dir);
243 auth_sock_name = NULL;
244 auth_sock_dir = NULL;
249 display_loginmsg(void)
253 if (sshbuf_len(loginmsg) == 0)
255 if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
256 fatal("%s: buffer error: %s", __func__, ssh_err(r));
257 printf("%s", (char *)sshbuf_ptr(loginmsg));
258 sshbuf_reset(loginmsg);
262 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
264 int fd = -1, success = 0;
266 if (!options.expose_userauth_info || info == NULL)
269 temporarily_use_uid(pw);
270 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
271 if ((fd = mkstemp(auth_info_file)) == -1) {
272 error("%s: mkstemp: %s", __func__, strerror(errno));
275 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
276 sshbuf_len(info)) != sshbuf_len(info)) {
277 error("%s: write: %s", __func__, strerror(errno));
280 if (close(fd) != 0) {
281 error("%s: close: %s", __func__, strerror(errno));
289 free(auth_info_file);
290 auth_info_file = NULL;
296 set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
298 char *tmp, *cp, *host;
302 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
303 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
304 for (i = 0; i < auth_opts->npermitopen; i++) {
305 tmp = cp = xstrdup(auth_opts->permitopen[i]);
306 /* This shouldn't fail as it has already been checked */
307 if ((host = hpdelim(&cp)) == NULL)
308 fatal("%s: internal error: hpdelim", __func__);
309 host = cleanhostname(host);
310 if (cp == NULL || (port = permitopen_port(cp)) < 0)
311 fatal("%s: internal error: permitopen port",
313 channel_add_permission(ssh,
314 FORWARD_USER, FORWARD_LOCAL, host, port);
318 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
319 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
320 for (i = 0; i < auth_opts->npermitlisten; i++) {
321 tmp = cp = xstrdup(auth_opts->permitlisten[i]);
322 /* This shouldn't fail as it has already been checked */
323 if ((host = hpdelim(&cp)) == NULL)
324 fatal("%s: internal error: hpdelim", __func__);
325 host = cleanhostname(host);
326 if (cp == NULL || (port = permitopen_port(cp)) < 0)
327 fatal("%s: internal error: permitlisten port",
329 channel_add_permission(ssh,
330 FORWARD_USER, FORWARD_REMOTE, host, port);
337 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
339 setproctitle("%s", authctxt->pw->pw_name);
341 auth_log_authopts("active", auth_opts, 0);
343 /* setup the channel layer */
344 /* XXX - streamlocal? */
345 set_fwdpermit_from_authopts(ssh, auth_opts);
347 if (!auth_opts->permit_port_forwarding_flag ||
348 options.disable_forwarding) {
349 channel_disable_admin(ssh, FORWARD_LOCAL);
350 channel_disable_admin(ssh, FORWARD_REMOTE);
352 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
353 channel_disable_admin(ssh, FORWARD_LOCAL);
355 channel_permit_all(ssh, FORWARD_LOCAL);
356 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
357 channel_disable_admin(ssh, FORWARD_REMOTE);
359 channel_permit_all(ssh, FORWARD_REMOTE);
361 auth_debug_send(ssh);
363 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
365 do_authenticated2(ssh, authctxt);
367 do_cleanup(ssh, authctxt);
370 /* Check untrusted xauth strings for metacharacters */
372 xauth_valid_string(const char *s)
376 for (i = 0; s[i] != '\0'; i++) {
377 if (!isalnum((u_char)s[i]) &&
378 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
379 s[i] != '-' && s[i] != '_')
387 * This is called to fork and execute a command when we have no tty. This
388 * will call do_child from the child, and server_loop from the parent after
389 * setting up file descriptors and such.
392 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
396 int pin[2], pout[2], perr[2];
399 fatal("do_exec_no_pty: no session");
401 /* Allocate pipes for communicating with the program. */
403 error("%s: pipe in: %.100s", __func__, strerror(errno));
406 if (pipe(pout) < 0) {
407 error("%s: pipe out: %.100s", __func__, strerror(errno));
412 if (pipe(perr) < 0) {
413 error("%s: pipe err: %.100s", __func__,
422 int inout[2], err[2];
425 fatal("do_exec_no_pty: no session");
427 /* Uses socket pairs to communicate with the program. */
428 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
429 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
432 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
433 error("%s: socketpair #2: %.100s", __func__,
441 session_proctitle(s);
443 /* Fork the child. */
444 switch ((pid = fork())) {
446 error("%s: fork: %.100s", __func__, strerror(errno));
465 * Create a new session and process group since the 4.4BSD
466 * setlogin() affects the entire process group.
469 error("setsid failed: %.100s", strerror(errno));
473 * Redirect stdin. We close the parent side of the socket
474 * pair, and make the child side the standard input.
477 if (dup2(pin[0], 0) < 0)
478 perror("dup2 stdin");
481 /* Redirect stdout. */
483 if (dup2(pout[1], 1) < 0)
484 perror("dup2 stdout");
487 /* Redirect stderr. */
489 if (dup2(perr[1], 2) < 0)
490 perror("dup2 stderr");
494 * Redirect stdin, stdout, and stderr. Stdin and stdout will
495 * use the same socket, as some programs (particularly rdist)
496 * seem to depend on it.
500 if (dup2(inout[0], 0) < 0) /* stdin */
501 perror("dup2 stdin");
502 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
503 perror("dup2 stdout");
505 if (dup2(err[0], 2) < 0) /* stderr */
506 perror("dup2 stderr");
510 /* Do processing for the child (exec command etc). */
511 do_child(ssh, s, command);
518 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
522 /* Set interactive/non-interactive mode. */
523 ssh_packet_set_interactive(ssh, s->display != NULL,
524 options.ip_qos_interactive, options.ip_qos_bulk);
527 * Clear loginmsg, since it's the child's responsibility to display
528 * it to the user, otherwise multiple sessions may accumulate
529 * multiple copies of the login messages.
531 sshbuf_reset(loginmsg);
534 /* We are the parent. Close the child sides of the pipes. */
539 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
542 /* We are the parent. Close the child sides of the socket pairs. */
547 * Enter the interactive session. Note: server_loop must be able to
548 * handle the case that fdin and fdout are the same.
550 session_set_fds(ssh, s, inout[1], inout[1], err[1],
557 * This is called to fork and execute a command when we have a tty. This
558 * will call do_child from the child, and server_loop from the parent after
559 * setting up file descriptors, controlling tty, updating wtmp, utmp,
560 * lastlog, and other such operations.
563 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
565 int fdout, ptyfd, ttyfd, ptymaster;
569 fatal("do_exec_pty: no session");
574 * Create another descriptor of the pty master side for use as the
575 * standard input. We could use the original descriptor, but this
576 * simplifies code in server_loop. The descriptor is bidirectional.
577 * Do this before forking (and cleanup in the child) so as to
578 * detect and gracefully fail out-of-fd conditions.
580 if ((fdout = dup(ptyfd)) < 0) {
581 error("%s: dup #1: %s", __func__, strerror(errno));
586 /* we keep a reference to the pty master */
587 if ((ptymaster = dup(ptyfd)) < 0) {
588 error("%s: dup #2: %s", __func__, strerror(errno));
595 /* Fork the child. */
596 switch ((pid = fork())) {
598 error("%s: fork: %.100s", __func__, strerror(errno));
610 /* Close the master side of the pseudo tty. */
613 /* Make the pseudo tty our controlling tty. */
614 pty_make_controlling_tty(&ttyfd, s->tty);
616 /* Redirect stdin/stdout/stderr from the pseudo tty. */
617 if (dup2(ttyfd, 0) < 0)
618 error("dup2 stdin: %s", strerror(errno));
619 if (dup2(ttyfd, 1) < 0)
620 error("dup2 stdout: %s", strerror(errno));
621 if (dup2(ttyfd, 2) < 0)
622 error("dup2 stderr: %s", strerror(errno));
624 /* Close the extra descriptor for the pseudo tty. */
627 /* record login, etc. similar to login(1) */
629 do_login(ssh, s, command);
632 * Do common processing for the child, such as execing
635 do_child(ssh, s, command);
642 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
647 /* Parent. Close the slave side of the pseudo tty. */
650 /* Enter interactive session. */
651 s->ptymaster = ptymaster;
652 ssh_packet_set_interactive(ssh, 1,
653 options.ip_qos_interactive, options.ip_qos_bulk);
654 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
659 * This is called to fork and execute a command. If another command is
660 * to be forced, execute that instead.
663 do_exec(struct ssh *ssh, Session *s, const char *command)
666 const char *forced = NULL, *tty = NULL;
667 char session_type[1024];
669 if (options.adm_forced_command) {
670 original_command = command;
671 command = options.adm_forced_command;
673 } else if (auth_opts->force_command != NULL) {
674 original_command = command;
675 command = auth_opts->force_command;
676 forced = "(key-option)";
679 if (forced != NULL) {
681 if (IS_INTERNAL_SFTP(command)) {
682 s->is_subsystem = s->is_subsystem ?
683 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
684 } else if (s->is_subsystem)
685 s->is_subsystem = SUBSYSTEM_EXT;
686 snprintf(session_type, sizeof(session_type),
687 "forced-command %s '%.900s'", forced, command);
688 } else if (s->is_subsystem) {
689 snprintf(session_type, sizeof(session_type),
690 "subsystem '%.900s'", s->subsys);
691 } else if (command == NULL) {
692 snprintf(session_type, sizeof(session_type), "shell");
694 /* NB. we don't log unforced commands to preserve privacy */
695 snprintf(session_type, sizeof(session_type), "command");
698 if (s->ttyfd != -1) {
700 if (strncmp(tty, "/dev/", 5) == 0)
704 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
706 tty == NULL ? "" : " on ",
707 tty == NULL ? "" : tty,
709 ssh_remote_ipaddr(ssh),
710 ssh_remote_port(ssh),
713 #ifdef SSH_AUDIT_EVENTS
715 PRIVSEP(audit_run_command(command));
716 else if (s->ttyfd == -1) {
717 char *shell = s->pw->pw_shell;
719 if (shell[0] == '\0') /* empty shell means /bin/sh */
721 PRIVSEP(audit_run_command(shell));
725 ret = do_exec_pty(ssh, s, command);
727 ret = do_exec_no_pty(ssh, s, command);
729 original_command = NULL;
732 * Clear loginmsg: it's the child's responsibility to display
733 * it to the user, otherwise multiple sessions may accumulate
734 * multiple copies of the login messages.
736 sshbuf_reset(loginmsg);
741 /* administrative, login(1)-like work */
743 do_login(struct ssh *ssh, Session *s, const char *command)
746 struct sockaddr_storage from;
747 struct passwd * pw = s->pw;
748 pid_t pid = getpid();
751 * Get IP address of client. If the connection is not a socket, let
752 * the address be 0.0.0.0.
754 memset(&from, 0, sizeof(from));
755 fromlen = sizeof(from);
756 if (ssh_packet_connection_is_on_socket(ssh)) {
757 if (getpeername(ssh_packet_get_connection_in(ssh),
758 (struct sockaddr *)&from, &fromlen) < 0) {
759 debug("getpeername: %.100s", strerror(errno));
764 /* Record that there was a login on that tty from the remote host. */
766 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
767 session_get_remote_name_or_ip(ssh, utmp_len,
769 (struct sockaddr *)&from, fromlen);
773 * If password change is needed, do it now.
774 * This needs to occur before the ~/.hushlogin check.
776 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
779 s->authctxt->force_pwchange = 0;
780 /* XXX - signal [net] parent to enable forwardings */
784 if (check_quietlogin(s, command))
793 * Display the message of the day.
801 if (options.print_motd) {
802 #ifdef HAVE_LOGIN_CAP
803 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
806 f = fopen("/etc/motd", "r");
809 while (fgets(buf, sizeof(buf), f))
818 * Check for quiet login, either .hushlogin or command given.
821 check_quietlogin(Session *s, const char *command)
824 struct passwd *pw = s->pw;
827 /* Return 1 if .hushlogin exists or a command given. */
830 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
831 #ifdef HAVE_LOGIN_CAP
832 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
835 if (stat(buf, &st) >= 0)
842 * Reads environment variables from the given file and adds/overrides them
843 * into the environment. If the file does not exist, this does nothing.
844 * Otherwise, it must consist of empty lines, comments (line starts with '#')
845 * and assignments of the form name=value. No other forms are allowed.
846 * If whitelist is not NULL, then it is interpreted as a pattern list and
847 * only variable names that match it will be accepted.
850 read_environment_file(char ***env, u_int *envsize,
851 const char *filename, const char *whitelist)
854 char *line = NULL, *cp, *value;
858 f = fopen(filename, "r");
862 while (getline(&line, &linesize, f) != -1) {
864 fatal("Too many lines in environment file %s", filename);
865 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
867 if (!*cp || *cp == '#' || *cp == '\n')
870 cp[strcspn(cp, "\n")] = '\0';
872 value = strchr(cp, '=');
874 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
879 * Replace the equals sign by nul, and advance value to
884 if (whitelist != NULL &&
885 match_pattern_list(cp, whitelist, 0) != 1)
887 child_set_env(env, envsize, cp, value);
893 #ifdef HAVE_ETC_DEFAULT_LOGIN
895 * Return named variable from specified environment, or NULL if not present.
898 child_get_env(char **env, const char *name)
904 for (i=0; env[i] != NULL; i++)
905 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
906 return(env[i] + len + 1);
911 * Read /etc/default/login.
912 * We pick up the PATH (or SUPATH for root) and UMASK.
915 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
917 char **tmpenv = NULL, *var;
918 u_int i, tmpenvsize = 0;
922 * We don't want to copy the whole file to the child's environment,
923 * so we use a temporary environment and copy the variables we're
926 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
927 options.permit_user_env_whitelist);
933 var = child_get_env(tmpenv, "SUPATH");
935 var = child_get_env(tmpenv, "PATH");
937 child_set_env(env, envsize, "PATH", var);
939 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
940 if (sscanf(var, "%5lo", &mask) == 1)
943 for (i = 0; tmpenv[i] != NULL; i++)
947 #endif /* HAVE_ETC_DEFAULT_LOGIN */
950 copy_environment_blacklist(char **source, char ***env, u_int *envsize,
951 const char *blacklist)
953 char *var_name, *var_val;
959 for(i = 0; source[i] != NULL; i++) {
960 var_name = xstrdup(source[i]);
961 if ((var_val = strstr(var_name, "=")) == NULL) {
967 if (blacklist == NULL ||
968 match_pattern_list(var_name, blacklist, 0) != 1) {
969 debug3("Copy environment: %s=%s", var_name, var_val);
970 child_set_env(env, envsize, var_name, var_val);
980 copy_environment(char **source, char ***env, u_int *envsize)
982 copy_environment_blacklist(source, env, envsize, NULL);
988 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
993 char *ocp, *cp, *value, **env, *laddr;
994 struct passwd *pw = s->pw;
995 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
999 /* Initialize the environment. */
1001 env = xcalloc(envsize, sizeof(char *));
1006 * The Windows environment contains some setting which are
1007 * important for a running system. They must not be dropped.
1012 p = fetch_windows_environment();
1013 copy_environment(p, &env, &envsize);
1014 free_windows_environment(p);
1019 /* Allow any GSSAPI methods that we've used to alter
1020 * the childs environment as they see fit
1022 ssh_gssapi_do_child(&env, &envsize);
1025 /* Set basic environment. */
1026 for (i = 0; i < s->num_env; i++)
1027 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
1029 child_set_env(&env, &envsize, "USER", pw->pw_name);
1030 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1032 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1034 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1035 #ifdef HAVE_LOGIN_CAP
1036 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1037 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1039 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1040 #else /* HAVE_LOGIN_CAP */
1041 # ifndef HAVE_CYGWIN
1043 * There's no standard path on Windows. The path contains
1044 * important components pointing to the system directories,
1045 * needed for loading shared libraries. So the path better
1046 * remains intact here.
1048 # ifdef HAVE_ETC_DEFAULT_LOGIN
1049 read_etc_default_login(&env, &envsize, pw->pw_uid);
1050 path = child_get_env(env, "PATH");
1051 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1052 if (path == NULL || *path == '\0') {
1053 child_set_env(&env, &envsize, "PATH",
1054 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1056 # endif /* HAVE_CYGWIN */
1057 #endif /* HAVE_LOGIN_CAP */
1059 if (!options.use_pam) {
1060 snprintf(buf, sizeof buf, "%.200s/%.50s",
1061 _PATH_MAILDIR, pw->pw_name);
1062 child_set_env(&env, &envsize, "MAIL", buf);
1065 /* Normal systems set SHELL by default. */
1066 child_set_env(&env, &envsize, "SHELL", shell);
1069 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1071 child_set_env(&env, &envsize, "TERM", s->term);
1073 child_set_env(&env, &envsize, "DISPLAY", s->display);
1076 * Since we clear KRB5CCNAME at startup, if it's set now then it
1077 * must have been set by a native authentication method (eg AIX or
1078 * SIA), so copy it to the child.
1083 if ((cp = getenv("KRB5CCNAME")) != NULL)
1084 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1091 if ((cp = getenv("AUTHSTATE")) != NULL)
1092 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1093 read_environment_file(&env, &envsize, "/etc/environment",
1094 options.permit_user_env_whitelist);
1098 if (s->authctxt->krb5_ccname)
1099 child_set_env(&env, &envsize, "KRB5CCNAME",
1100 s->authctxt->krb5_ccname);
1102 if (auth_sock_name != NULL)
1103 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1107 /* Set custom environment options from pubkey authentication. */
1108 if (options.permit_user_env) {
1109 for (n = 0 ; n < auth_opts->nenv; n++) {
1110 ocp = xstrdup(auth_opts->env[n]);
1111 cp = strchr(ocp, '=');
1114 /* Apply PermitUserEnvironment whitelist */
1115 if (options.permit_user_env_whitelist == NULL ||
1116 match_pattern_list(ocp,
1117 options.permit_user_env_whitelist, 0) == 1)
1118 child_set_env(&env, &envsize,
1125 /* read $HOME/.ssh/environment. */
1126 if (options.permit_user_env) {
1127 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1129 read_environment_file(&env, &envsize, buf,
1130 options.permit_user_env_whitelist);
1135 * Pull in any environment variables that may have
1138 if (options.use_pam) {
1142 * Don't allow PAM-internal env vars to leak
1143 * back into the session environment.
1145 #define PAM_ENV_BLACKLIST "SSH_AUTH_INFO*,SSH_CONNECTION*"
1146 p = fetch_pam_child_environment();
1147 copy_environment_blacklist(p, &env, &envsize,
1149 free_pam_environment(p);
1151 p = fetch_pam_environment();
1152 copy_environment_blacklist(p, &env, &envsize,
1154 free_pam_environment(p);
1156 #endif /* USE_PAM */
1158 /* Environment specified by admin */
1159 for (i = 0; i < options.num_setenv; i++) {
1160 cp = xstrdup(options.setenv[i]);
1161 if ((value = strchr(cp, '=')) == NULL) {
1162 /* shouldn't happen; vars are checked in servconf.c */
1163 fatal("Invalid config SetEnv: %s", options.setenv[i]);
1166 child_set_env(&env, &envsize, cp, value);
1169 /* SSH_CLIENT deprecated */
1170 snprintf(buf, sizeof buf, "%.50s %d %d",
1171 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1172 ssh_local_port(ssh));
1173 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1175 laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh));
1176 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1177 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1178 laddr, ssh_local_port(ssh));
1180 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1182 if (tun_fwd_ifnames != NULL)
1183 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
1184 if (auth_info_file != NULL)
1185 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
1187 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1188 if (original_command)
1189 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1193 /* dump the environment */
1194 fprintf(stderr, "Environment:\n");
1195 for (i = 0; env[i]; i++)
1196 fprintf(stderr, " %.200s\n", env[i]);
1202 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1203 * first in this order).
1206 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1214 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1216 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1217 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1218 auth_opts->permit_user_rc && options.permit_user_rc &&
1219 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1220 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1221 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1223 fprintf(stderr, "Running %s\n", cmd);
1224 f = popen(cmd, "w");
1227 fprintf(f, "%s %s\n", s->auth_proto,
1231 fprintf(stderr, "Could not run %s\n",
1233 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1235 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1236 _PATH_SSH_SYSTEM_RC);
1237 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1240 fprintf(f, "%s %s\n", s->auth_proto,
1244 fprintf(stderr, "Could not run %s\n",
1245 _PATH_SSH_SYSTEM_RC);
1246 } else if (do_xauth && options.xauth_location != NULL) {
1247 /* Add authority data to .Xauthority if appropriate. */
1250 "Running %.500s remove %.100s\n",
1251 options.xauth_location, s->auth_display);
1253 "%.500s add %.100s %.100s %.100s\n",
1254 options.xauth_location, s->auth_display,
1255 s->auth_proto, s->auth_data);
1257 snprintf(cmd, sizeof cmd, "%s -q -",
1258 options.xauth_location);
1259 f = popen(cmd, "w");
1261 fprintf(f, "remove %s\n",
1263 fprintf(f, "add %s %s %s\n",
1264 s->auth_display, s->auth_proto,
1268 fprintf(stderr, "Could not run %s\n",
1275 do_nologin(struct passwd *pw)
1278 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1281 #ifdef HAVE_LOGIN_CAP
1282 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1284 nl = strdup(login_getcapstr(lc, "nologin", def_nl, def_nl));
1286 if (pw->pw_uid == 0)
1290 if (stat(nl, &sb) == -1) {
1296 /* /etc/nologin exists. Print its contents if we can and exit. */
1297 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1298 if ((f = fopen(nl, "r")) != NULL) {
1299 while (fgets(buf, sizeof(buf), f))
1307 * Chroot into a directory after checking it for safety: all path components
1308 * must be root-owned directories with strict permissions.
1311 safely_chroot(const char *path, uid_t uid)
1314 char component[PATH_MAX];
1317 if (!path_absolute(path))
1318 fatal("chroot path does not begin at root");
1319 if (strlen(path) >= sizeof(component))
1320 fatal("chroot path too long");
1323 * Descend the path, checking that each component is a
1324 * root-owned directory with strict permissions.
1326 for (cp = path; cp != NULL;) {
1327 if ((cp = strchr(cp, '/')) == NULL)
1328 strlcpy(component, path, sizeof(component));
1331 memcpy(component, path, cp - path);
1332 component[cp - path] = '\0';
1335 debug3("%s: checking '%s'", __func__, component);
1337 if (stat(component, &st) != 0)
1338 fatal("%s: stat(\"%s\"): %s", __func__,
1339 component, strerror(errno));
1340 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1341 fatal("bad ownership or modes for chroot "
1342 "directory %s\"%s\"",
1343 cp == NULL ? "" : "component ", component);
1344 if (!S_ISDIR(st.st_mode))
1345 fatal("chroot path %s\"%s\" is not a directory",
1346 cp == NULL ? "" : "component ", component);
1350 if (chdir(path) == -1)
1351 fatal("Unable to chdir to chroot path \"%s\": "
1352 "%s", path, strerror(errno));
1353 if (chroot(path) == -1)
1354 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1355 if (chdir("/") == -1)
1356 fatal("%s: chdir(/) after chroot: %s",
1357 __func__, strerror(errno));
1358 verbose("Changed root directory to \"%s\"", path);
1361 /* Set login name, uid, gid, and groups. */
1363 do_setusercontext(struct passwd *pw)
1365 char uidstr[32], *chroot_path, *tmp;
1367 platform_setusercontext(pw);
1369 if (platform_privileged_uidswap()) {
1370 #ifdef HAVE_LOGIN_CAP
1371 if (setusercontext(lc, pw, pw->pw_uid,
1372 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1373 perror("unable to set user context");
1377 if (setlogin(pw->pw_name) < 0)
1378 error("setlogin failed: %s", strerror(errno));
1379 if (setgid(pw->pw_gid) < 0) {
1383 /* Initialize the group list. */
1384 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1385 perror("initgroups");
1391 platform_setusercontext_post_groups(pw);
1393 if (!in_chroot && options.chroot_directory != NULL &&
1394 strcasecmp(options.chroot_directory, "none") != 0) {
1395 tmp = tilde_expand_filename(options.chroot_directory,
1397 snprintf(uidstr, sizeof(uidstr), "%llu",
1398 (unsigned long long)pw->pw_uid);
1399 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1400 "u", pw->pw_name, "U", uidstr, (char *)NULL);
1401 safely_chroot(chroot_path, pw->pw_uid);
1404 /* Make sure we don't attempt to chroot again */
1405 free(options.chroot_directory);
1406 options.chroot_directory = NULL;
1410 #ifdef HAVE_LOGIN_CAP
1411 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1412 perror("unable to set user context (setuser)");
1416 * FreeBSD's setusercontext() will not apply the user's
1417 * own umask setting unless running with the user's UID.
1419 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1423 * In a chroot environment, the set_id() will always fail;
1424 * typically because of the lack of necessary authentication
1425 * services and runtime such as ./usr/lib/libiaf.so,
1426 * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
1427 * internal sftp chroot case. We'll lose auditing and ACLs but
1428 * permanently_set_uid will take care of the rest.
1430 if (!in_chroot && set_id(pw->pw_name) != 0)
1431 fatal("set_id(%s) Failed", pw->pw_name);
1432 # endif /* USE_LIBIAF */
1433 /* Permanently switch to the desired uid. */
1434 permanently_set_uid(pw);
1436 } else if (options.chroot_directory != NULL &&
1437 strcasecmp(options.chroot_directory, "none") != 0) {
1438 fatal("server lacks privileges to chroot to ChrootDirectory");
1441 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1442 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1446 do_pwchange(Session *s)
1449 fprintf(stderr, "WARNING: Your password has expired.\n");
1450 if (s->ttyfd != -1) {
1452 "You must change your password now and login again!\n");
1456 #ifdef PASSWD_NEEDS_USERNAME
1457 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1460 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1465 "Password change required but no TTY available.\n");
1471 child_close_fds(struct ssh *ssh)
1473 extern int auth_sock;
1475 if (auth_sock != -1) {
1480 if (ssh_packet_get_connection_in(ssh) ==
1481 ssh_packet_get_connection_out(ssh))
1482 close(ssh_packet_get_connection_in(ssh));
1484 close(ssh_packet_get_connection_in(ssh));
1485 close(ssh_packet_get_connection_out(ssh));
1488 * Close all descriptors related to channels. They will still remain
1489 * open in the parent.
1491 /* XXX better use close-on-exec? -markus */
1492 channel_close_all(ssh);
1495 * Close any extra file descriptors. Note that there may still be
1496 * descriptors left by system functions. They will be closed later.
1501 * Close any extra open file descriptors so that we don't have them
1502 * hanging around in clients. Note that we want to do this after
1503 * initgroups, because at least on Solaris 2.3 it leaves file
1506 closefrom(STDERR_FILENO + 1);
1510 * Performs common processing for the child, such as setting up the
1511 * environment, closing extra file descriptors, setting the user and group
1512 * ids, and executing the command or shell.
1516 do_child(struct ssh *ssh, Session *s, const char *command)
1518 extern char **environ;
1519 char **env, *argv[ARGV_MAX], remote_id[512];
1520 const char *shell, *shell0;
1521 struct passwd *pw = s->pw;
1524 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1526 /* remove hostkey from the child's memory */
1527 destroy_sensitive_data();
1528 ssh_packet_clear_keys(ssh);
1530 /* Force a password change */
1531 if (s->authctxt->force_pwchange) {
1532 do_setusercontext(pw);
1533 child_close_fds(ssh);
1539 * Login(1) does this as well, and it needs uid 0 for the "-h"
1540 * switch, so we let login(1) to this for us.
1543 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1544 if (!check_quietlogin(s, command))
1546 #else /* HAVE_OSF_SIA */
1547 /* When PAM is enabled we rely on it to do the nologin check */
1548 if (!options.use_pam)
1550 do_setusercontext(pw);
1552 * PAM session modules in do_setusercontext may have
1553 * generated messages, so if this in an interactive
1554 * login then display them too.
1556 if (!check_quietlogin(s, command))
1558 #endif /* HAVE_OSF_SIA */
1561 if (options.use_pam && !is_pam_session_open()) {
1562 debug3("PAM session not opened, exiting");
1569 * Get the shell from the password data. An empty shell field is
1570 * legal, and means /bin/sh.
1572 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1575 * Make sure $SHELL points to the shell from the password file,
1576 * even if shell is overridden from login.conf
1578 env = do_setup_env(ssh, s, shell);
1580 #ifdef HAVE_LOGIN_CAP
1581 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1585 * Close the connection descriptors; note that this is the child, and
1586 * the server will still have the socket open, and it is important
1587 * that we do not shutdown it. Note that the descriptors cannot be
1588 * closed before building the environment, as we call
1589 * ssh_remote_ipaddr there.
1591 child_close_fds(ssh);
1594 * Must take new environment into use so that .ssh/rc,
1595 * /etc/ssh/sshrc and xauth are run in the proper environment.
1599 #if defined(KRB5) && defined(USE_AFS)
1601 * At this point, we check to see if AFS is active and if we have
1602 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1603 * if we can (and need to) extend the ticket into an AFS token. If
1604 * we don't do this, we run into potential problems if the user's
1605 * home directory is in AFS and it's not world-readable.
1608 if (options.kerberos_get_afs_token && k_hasafs() &&
1609 (s->authctxt->krb5_ctx != NULL)) {
1612 debug("Getting AFS token");
1616 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1617 krb5_afslog(s->authctxt->krb5_ctx,
1618 s->authctxt->krb5_fwd_ccache, cell, NULL);
1620 krb5_afslog_home(s->authctxt->krb5_ctx,
1621 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1625 /* Change current directory to the user's home directory. */
1626 if (chdir(pw->pw_dir) < 0) {
1627 /* Suppress missing homedir warning for chroot case */
1628 #ifdef HAVE_LOGIN_CAP
1629 r = login_getcapbool(lc, "requirehome", 0);
1631 if (r || !in_chroot) {
1632 fprintf(stderr, "Could not chdir to home "
1633 "directory %s: %s\n", pw->pw_dir,
1640 closefrom(STDERR_FILENO + 1);
1642 do_rc_files(ssh, s, shell);
1644 /* restore SIGPIPE for child */
1645 signal(SIGPIPE, SIG_DFL);
1647 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1648 error("Connection from %s: refusing non-sftp session",
1650 printf("This service allows sftp connections only.\n");
1653 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1654 extern int optind, optreset;
1658 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1659 args = xstrdup(command ? command : "sftp-server");
1660 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1661 if (i < ARGV_MAX - 1)
1664 optind = optreset = 1;
1665 __progname = argv[0];
1667 ssh_selinux_change_context("sftpd_t");
1669 exit(sftp_server_main(i, argv, s->pw));
1674 /* Get the last component of the shell name. */
1675 if ((shell0 = strrchr(shell, '/')) != NULL)
1681 * If we have no command, execute the shell. In this case, the shell
1682 * name to be passed in argv[0] is preceded by '-' to indicate that
1683 * this is a login shell.
1688 /* Start the shell. Set initial character to '-'. */
1691 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1692 >= sizeof(argv0) - 1) {
1698 /* Execute the shell. */
1701 execve(shell, argv, env);
1703 /* Executing the shell failed. */
1708 * Execute the command using the user's shell. This uses the -c
1709 * option to execute the command.
1711 argv[0] = (char *) shell0;
1713 argv[2] = (char *) command;
1715 execve(shell, argv, env);
1721 session_unused(int id)
1723 debug3("%s: session id %d unused", __func__, id);
1724 if (id >= options.max_sessions ||
1725 id >= sessions_nalloc) {
1726 fatal("%s: insane session id %d (max %d nalloc %d)",
1727 __func__, id, options.max_sessions, sessions_nalloc);
1729 memset(&sessions[id], 0, sizeof(*sessions));
1730 sessions[id].self = id;
1731 sessions[id].used = 0;
1732 sessions[id].chanid = -1;
1733 sessions[id].ptyfd = -1;
1734 sessions[id].ttyfd = -1;
1735 sessions[id].ptymaster = -1;
1736 sessions[id].x11_chanids = NULL;
1737 sessions[id].next_unused = sessions_first_unused;
1738 sessions_first_unused = id;
1746 if (sessions_first_unused == -1) {
1747 if (sessions_nalloc >= options.max_sessions)
1749 debug2("%s: allocate (allocated %d max %d)",
1750 __func__, sessions_nalloc, options.max_sessions);
1751 tmp = xrecallocarray(sessions, sessions_nalloc,
1752 sessions_nalloc + 1, sizeof(*sessions));
1754 error("%s: cannot allocate %d sessions",
1755 __func__, sessions_nalloc + 1);
1759 session_unused(sessions_nalloc++);
1762 if (sessions_first_unused >= sessions_nalloc ||
1763 sessions_first_unused < 0) {
1764 fatal("%s: insane first_unused %d max %d nalloc %d",
1765 __func__, sessions_first_unused, options.max_sessions,
1769 s = &sessions[sessions_first_unused];
1771 fatal("%s: session %d already used",
1772 __func__, sessions_first_unused);
1774 sessions_first_unused = s->next_unused;
1776 s->next_unused = -1;
1777 debug("session_new: session %d", s->self);
1786 for (i = 0; i < sessions_nalloc; i++) {
1787 Session *s = &sessions[i];
1789 debug("dump: used %d next_unused %d session %d %p "
1790 "channel %d pid %ld",
1801 session_open(Authctxt *authctxt, int chanid)
1803 Session *s = session_new();
1804 debug("session_open: channel %d", chanid);
1806 error("no more sessions");
1809 s->authctxt = authctxt;
1810 s->pw = authctxt->pw;
1811 if (s->pw == NULL || !authctxt->valid)
1812 fatal("no user for session %d", s->self);
1813 debug("session_open: session %d: link with channel %d", s->self, chanid);
1819 session_by_tty(char *tty)
1822 for (i = 0; i < sessions_nalloc; i++) {
1823 Session *s = &sessions[i];
1824 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1825 debug("session_by_tty: session %d tty %s", i, tty);
1829 debug("session_by_tty: unknown tty %.100s", tty);
1835 session_by_channel(int id)
1838 for (i = 0; i < sessions_nalloc; i++) {
1839 Session *s = &sessions[i];
1840 if (s->used && s->chanid == id) {
1841 debug("session_by_channel: session %d channel %d",
1846 debug("session_by_channel: unknown channel %d", id);
1852 session_by_x11_channel(int id)
1856 for (i = 0; i < sessions_nalloc; i++) {
1857 Session *s = &sessions[i];
1859 if (s->x11_chanids == NULL || !s->used)
1861 for (j = 0; s->x11_chanids[j] != -1; j++) {
1862 if (s->x11_chanids[j] == id) {
1863 debug("session_by_x11_channel: session %d "
1864 "channel %d", s->self, id);
1869 debug("session_by_x11_channel: unknown channel %d", id);
1875 session_by_pid(pid_t pid)
1878 debug("session_by_pid: pid %ld", (long)pid);
1879 for (i = 0; i < sessions_nalloc; i++) {
1880 Session *s = &sessions[i];
1881 if (s->used && s->pid == pid)
1884 error("session_by_pid: unknown pid %ld", (long)pid);
1890 session_window_change_req(struct ssh *ssh, Session *s)
1894 if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1895 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1896 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1897 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 ||
1898 (r = sshpkt_get_end(ssh)) != 0)
1899 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1900 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1905 session_pty_req(struct ssh *ssh, Session *s)
1909 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1910 debug("Allocating a pty not permitted for this connection.");
1913 if (s->ttyfd != -1) {
1914 ssh_packet_disconnect(ssh, "Protocol error: you already have a pty.");
1918 if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 ||
1919 (r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1920 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1921 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1922 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0)
1923 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1925 if (strcmp(s->term, "") == 0) {
1930 /* Allocate a pty and open it. */
1931 debug("Allocating pty.");
1932 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1938 error("session_pty_req: session %d alloc failed", s->self);
1941 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1943 ssh_tty_parse_modes(ssh, s->ttyfd);
1945 if ((r = sshpkt_get_end(ssh)) != 0)
1946 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1949 pty_setowner(s->pw, s->tty);
1951 /* Set window size from the packet. */
1952 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1954 session_proctitle(s);
1959 session_subsystem_req(struct ssh *ssh, Session *s)
1966 if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 ||
1967 (r = sshpkt_get_end(ssh)) != 0)
1968 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1969 debug2("subsystem request for %.100s by user %s", s->subsys,
1972 for (i = 0; i < options.num_subsystems; i++) {
1973 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1974 prog = options.subsystem_command[i];
1975 cmd = options.subsystem_args[i];
1976 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1977 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1978 debug("subsystem: %s", prog);
1980 if (stat(prog, &st) < 0)
1981 debug("subsystem: cannot stat %s: %s",
1982 prog, strerror(errno));
1983 s->is_subsystem = SUBSYSTEM_EXT;
1984 debug("subsystem: exec() %s", cmd);
1986 success = do_exec(ssh, s, cmd) == 0;
1992 logit("subsystem request for %.100s by user %s failed, "
1993 "subsystem not found", s->subsys, s->pw->pw_name);
1999 session_x11_req(struct ssh *ssh, Session *s)
2002 u_char single_connection = 0;
2004 if (s->auth_proto != NULL || s->auth_data != NULL) {
2005 error("session_x11_req: session %d: "
2006 "x11 forwarding already active", s->self);
2009 if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 ||
2010 (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 ||
2011 (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 ||
2012 (r = sshpkt_get_u32(ssh, &s->screen)) != 0 ||
2013 (r = sshpkt_get_end(ssh)) != 0)
2014 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2016 s->single_connection = single_connection;
2018 if (xauth_valid_string(s->auth_proto) &&
2019 xauth_valid_string(s->auth_data))
2020 success = session_setup_x11fwd(ssh, s);
2023 error("Invalid X11 forwarding data");
2026 free(s->auth_proto);
2028 s->auth_proto = NULL;
2029 s->auth_data = NULL;
2035 session_shell_req(struct ssh *ssh, Session *s)
2039 if ((r = sshpkt_get_end(ssh)) != 0)
2040 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2041 return do_exec(ssh, s, NULL) == 0;
2045 session_exec_req(struct ssh *ssh, Session *s)
2049 char *command = NULL;
2051 if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 ||
2052 (r = sshpkt_get_end(ssh)) != 0)
2053 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2055 success = do_exec(ssh, s, command) == 0;
2061 session_break_req(struct ssh *ssh, Session *s)
2065 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */
2066 (r = sshpkt_get_end(ssh)) != 0)
2067 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2069 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2075 session_env_req(struct ssh *ssh, Session *s)
2081 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
2082 (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 ||
2083 (r = sshpkt_get_end(ssh)) != 0)
2084 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2086 /* Don't set too many environment variables */
2087 if (s->num_env > 128) {
2088 debug2("Ignoring env request %s: too many env vars", name);
2092 for (i = 0; i < options.num_accept_env; i++) {
2093 if (match_pattern(name, options.accept_env[i])) {
2094 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2095 s->env = xrecallocarray(s->env, s->num_env,
2096 s->num_env + 1, sizeof(*s->env));
2097 s->env[s->num_env].name = name;
2098 s->env[s->num_env].val = val;
2103 debug2("Ignoring env request %s: disallowed name", name);
2112 * Conversion of signals from ssh channel request names.
2113 * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
2117 name2sig(char *name)
2119 #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
2129 if (strcmp(name, "INFO@openssh.com") == 0)
2136 session_signal_req(struct ssh *ssh, Session *s)
2138 char *signame = NULL;
2139 int r, sig, success = 0;
2141 if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
2142 (r = sshpkt_get_end(ssh)) != 0) {
2143 error("%s: parse packet: %s", __func__, ssh_err(r));
2146 if ((sig = name2sig(signame)) == -1) {
2147 error("%s: unsupported signal \"%s\"", __func__, signame);
2151 error("%s: no pid for session %d", __func__, s->self);
2154 if (s->forced || s->is_subsystem) {
2155 error("%s: refusing to send signal %s to %s session", __func__,
2156 signame, s->forced ? "forced-command" : "subsystem");
2159 if (!use_privsep || mm_is_monitor()) {
2160 error("%s: session signalling requires privilege separation",
2165 debug("%s: signal %s, killpg(%ld, %d)", __func__, signame,
2167 temporarily_use_uid(s->pw);
2168 r = killpg(s->pid, sig);
2171 error("%s: killpg(%ld, %d): %s", __func__, (long)s->pid,
2172 sig, strerror(errno));
2184 session_auth_agent_req(struct ssh *ssh, Session *s)
2186 static int called = 0;
2189 if ((r = sshpkt_get_end(ssh)) != 0)
2190 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
2191 if (!auth_opts->permit_agent_forwarding_flag ||
2192 !options.allow_agent_forwarding) {
2193 debug("%s: agent forwarding disabled", __func__);
2200 return auth_input_request_forwarding(ssh, s->pw);
2205 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
2210 if ((s = session_by_channel(c->self)) == NULL) {
2211 logit("%s: no session %d req %.100s", __func__, c->self, rtype);
2214 debug("%s: session %d req %s", __func__, s->self, rtype);
2217 * a session is in LARVAL state until a shell, a command
2218 * or a subsystem is executed
2220 if (c->type == SSH_CHANNEL_LARVAL) {
2221 if (strcmp(rtype, "shell") == 0) {
2222 success = session_shell_req(ssh, s);
2223 } else if (strcmp(rtype, "exec") == 0) {
2224 success = session_exec_req(ssh, s);
2225 } else if (strcmp(rtype, "pty-req") == 0) {
2226 success = session_pty_req(ssh, s);
2227 } else if (strcmp(rtype, "x11-req") == 0) {
2228 success = session_x11_req(ssh, s);
2229 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2230 success = session_auth_agent_req(ssh, s);
2231 } else if (strcmp(rtype, "subsystem") == 0) {
2232 success = session_subsystem_req(ssh, s);
2233 } else if (strcmp(rtype, "env") == 0) {
2234 success = session_env_req(ssh, s);
2237 if (strcmp(rtype, "window-change") == 0) {
2238 success = session_window_change_req(ssh, s);
2239 } else if (strcmp(rtype, "break") == 0) {
2240 success = session_break_req(ssh, s);
2241 } else if (strcmp(rtype, "signal") == 0) {
2242 success = session_signal_req(ssh, s);
2249 session_set_fds(struct ssh *ssh, Session *s,
2250 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2253 * now that have a child and a pipe to the child,
2254 * we can activate our channel and register the fd's
2256 if (s->chanid == -1)
2257 fatal("no channel for session %d", s->self);
2258 channel_set_fds(ssh, s->chanid,
2260 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2261 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2265 * Function to perform pty cleanup. Also called if we get aborted abnormally
2266 * (e.g., due to a dropped connection).
2269 session_pty_cleanup2(Session *s)
2272 error("%s: no session", __func__);
2278 debug("%s: session %d release %s", __func__, s->self, s->tty);
2280 /* Record that the user has logged out. */
2282 record_logout(s->pid, s->tty, s->pw->pw_name);
2284 /* Release the pseudo-tty. */
2286 pty_release(s->tty);
2289 * Close the server side of the socket pairs. We must do this after
2290 * the pty cleanup, so that another process doesn't get this pty
2291 * while we're still cleaning up.
2293 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2294 error("close(s->ptymaster/%d): %s",
2295 s->ptymaster, strerror(errno));
2297 /* unlink pty from session */
2302 session_pty_cleanup(Session *s)
2304 PRIVSEP(session_pty_cleanup2(s));
2310 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2325 return "SIG@openssh.com";
2329 session_close_x11(struct ssh *ssh, int id)
2333 if ((c = channel_by_id(ssh, id)) == NULL) {
2334 debug("%s: x11 channel %d missing", __func__, id);
2336 /* Detach X11 listener */
2337 debug("%s: detach x11 channel %d", __func__, id);
2338 channel_cancel_cleanup(ssh, id);
2339 if (c->ostate != CHAN_OUTPUT_CLOSED)
2340 chan_mark_dead(ssh, c);
2345 session_close_single_x11(struct ssh *ssh, int id, void *arg)
2350 debug3("%s: channel %d", __func__, id);
2351 channel_cancel_cleanup(ssh, id);
2352 if ((s = session_by_x11_channel(id)) == NULL)
2353 fatal("%s: no x11 channel %d", __func__, id);
2354 for (i = 0; s->x11_chanids[i] != -1; i++) {
2355 debug("%s: session %d: closing channel %d",
2356 __func__, s->self, s->x11_chanids[i]);
2358 * The channel "id" is already closing, but make sure we
2359 * close all of its siblings.
2361 if (s->x11_chanids[i] != id)
2362 session_close_x11(ssh, s->x11_chanids[i]);
2364 free(s->x11_chanids);
2365 s->x11_chanids = NULL;
2368 free(s->auth_proto);
2369 s->auth_proto = NULL;
2371 s->auth_data = NULL;
2372 free(s->auth_display);
2373 s->auth_display = NULL;
2377 session_exit_message(struct ssh *ssh, Session *s, int status)
2382 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2383 fatal("%s: session %d: no channel %d",
2384 __func__, s->self, s->chanid);
2385 debug("%s: session %d channel %d pid %ld",
2386 __func__, s->self, s->chanid, (long)s->pid);
2388 if (WIFEXITED(status)) {
2389 channel_request_start(ssh, s->chanid, "exit-status", 0);
2390 if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 ||
2391 (r = sshpkt_send(ssh)) != 0)
2392 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2393 } else if (WIFSIGNALED(status)) {
2394 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2396 # define WCOREDUMP(x) (0)
2398 if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 ||
2399 (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 ||
2400 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2401 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2402 (r = sshpkt_send(ssh)) != 0)
2403 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2405 /* Some weird exit cause. Just exit. */
2406 ssh_packet_disconnect(ssh, "wait returned status %04x.", status);
2409 /* disconnect channel */
2410 debug("%s: release channel %d", __func__, s->chanid);
2413 * Adjust cleanup callback attachment to send close messages when
2414 * the channel gets EOF. The session will be then be closed
2415 * by session_close_by_channel when the childs close their fds.
2417 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2420 * emulate a write failure with 'chan_write_failed', nobody will be
2421 * interested in data we write.
2422 * Note that we must not call 'chan_read_failed', since there could
2423 * be some more data waiting in the pipe.
2425 if (c->ostate != CHAN_OUTPUT_CLOSED)
2426 chan_write_failed(ssh, c);
2430 session_close(struct ssh *ssh, Session *s)
2434 verbose("Close session: user %s from %.200s port %d id %d",
2436 ssh_remote_ipaddr(ssh),
2437 ssh_remote_port(ssh),
2441 session_pty_cleanup(s);
2444 free(s->x11_chanids);
2445 free(s->auth_display);
2447 free(s->auth_proto);
2449 if (s->env != NULL) {
2450 for (i = 0; i < s->num_env; i++) {
2451 free(s->env[i].name);
2452 free(s->env[i].val);
2456 session_proctitle(s);
2457 session_unused(s->self);
2461 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2463 Session *s = session_by_pid(pid);
2465 debug("%s: no session for pid %ld", __func__, (long)pid);
2468 if (s->chanid != -1)
2469 session_exit_message(ssh, s, status);
2471 session_pty_cleanup(s);
2476 * this is called when a channel dies before
2477 * the session 'child' itself dies
2480 session_close_by_channel(struct ssh *ssh, int id, void *arg)
2482 Session *s = session_by_channel(id);
2486 debug("%s: no session for id %d", __func__, id);
2489 debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
2491 debug("%s: channel %d: has child, ttyfd %d",
2492 __func__, id, s->ttyfd);
2494 * delay detach of session, but release pty, since
2495 * the fd's to the child are already closed
2498 session_pty_cleanup(s);
2501 /* detach by removing callback */
2502 channel_cancel_cleanup(ssh, s->chanid);
2504 /* Close any X11 listeners associated with this session */
2505 if (s->x11_chanids != NULL) {
2506 for (i = 0; s->x11_chanids[i] != -1; i++) {
2507 session_close_x11(ssh, s->x11_chanids[i]);
2508 s->x11_chanids[i] = -1;
2513 session_close(ssh, s);
2517 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2520 for (i = 0; i < sessions_nalloc; i++) {
2521 Session *s = &sessions[i];
2523 if (closefunc != NULL)
2526 session_close(ssh, s);
2532 session_tty_list(void)
2534 static char buf[1024];
2539 for (i = 0; i < sessions_nalloc; i++) {
2540 Session *s = &sessions[i];
2541 if (s->used && s->ttyfd != -1) {
2543 if (strncmp(s->tty, "/dev/", 5) != 0) {
2544 cp = strrchr(s->tty, '/');
2545 cp = (cp == NULL) ? s->tty : cp + 1;
2550 strlcat(buf, ",", sizeof buf);
2551 strlcat(buf, cp, sizeof buf);
2555 strlcpy(buf, "notty", sizeof buf);
2560 session_proctitle(Session *s)
2563 error("no user for session %d", s->self);
2565 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2569 session_setup_x11fwd(struct ssh *ssh, Session *s)
2572 char display[512], auth_display[512];
2573 char hostname[NI_MAXHOST];
2576 if (!auth_opts->permit_x11_forwarding_flag) {
2577 ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options.");
2580 if (!options.x11_forwarding) {
2581 debug("X11 forwarding disabled in server configuration file.");
2584 if (options.xauth_location == NULL ||
2585 (stat(options.xauth_location, &st) == -1)) {
2586 ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11.");
2589 if (s->display != NULL) {
2590 debug("X11 display already set.");
2593 if (x11_create_display_inet(ssh, options.x11_display_offset,
2594 options.x11_use_localhost, s->single_connection,
2595 &s->display_number, &s->x11_chanids) == -1) {
2596 debug("x11_create_display_inet failed.");
2599 for (i = 0; s->x11_chanids[i] != -1; i++) {
2600 channel_register_cleanup(ssh, s->x11_chanids[i],
2601 session_close_single_x11, 0);
2604 /* Set up a suitable value for the DISPLAY variable. */
2605 if (gethostname(hostname, sizeof(hostname)) < 0)
2606 fatal("gethostname: %.100s", strerror(errno));
2608 * auth_display must be used as the displayname when the
2609 * authorization entry is added with xauth(1). This will be
2610 * different than the DISPLAY string for localhost displays.
2612 if (options.x11_use_localhost) {
2613 snprintf(display, sizeof display, "localhost:%u.%u",
2614 s->display_number, s->screen);
2615 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2616 s->display_number, s->screen);
2617 s->display = xstrdup(display);
2618 s->auth_display = xstrdup(auth_display);
2620 #ifdef IPADDR_IN_DISPLAY
2622 struct in_addr my_addr;
2624 he = gethostbyname(hostname);
2626 error("Can't get IP address for X11 DISPLAY.");
2627 ssh_packet_send_debug(ssh, "Can't get IP address for X11 DISPLAY.");
2630 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2631 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2632 s->display_number, s->screen);
2634 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2635 s->display_number, s->screen);
2637 s->display = xstrdup(display);
2638 s->auth_display = xstrdup(display);
2645 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2647 server_loop2(ssh, authctxt);
2651 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2653 static int called = 0;
2655 debug("do_cleanup");
2657 /* no cleanup if we're in the child for login shell */
2661 /* avoid double cleanup */
2666 if (authctxt == NULL)
2670 if (options.use_pam) {
2672 sshpam_thread_cleanup();
2676 if (!authctxt->authenticated)
2680 if (options.kerberos_ticket_cleanup &&
2682 krb5_cleanup_proc(authctxt);
2686 if (options.gss_cleanup_creds)
2687 ssh_gssapi_cleanup_creds();
2690 /* remove agent socket */
2691 auth_sock_cleanup_proc(authctxt->pw);
2693 /* remove userauth info */
2694 if (auth_info_file != NULL) {
2695 temporarily_use_uid(authctxt->pw);
2696 unlink(auth_info_file);
2698 free(auth_info_file);
2699 auth_info_file = NULL;
2703 * Cleanup ptys/utmp only if privsep is disabled,
2704 * or if running in monitor.
2706 if (!use_privsep || mm_is_monitor())
2707 session_destroy_all(ssh, session_pty_cleanup2);
2710 /* Return a name for the remote host that fits inside utmp_size */
2713 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2715 const char *remote = "";
2718 remote = auth_get_canonical_hostname(ssh, use_dns);
2719 if (utmp_size == 0 || strlen(remote) > utmp_size)
2720 remote = ssh_remote_ipaddr(ssh);