1 /* $OpenBSD: session.c,v 1.278 2015/04/24 01:36:00 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>
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"
99 #if defined(KRB5) && defined(USE_AFS)
104 #include <selinux/selinux.h>
107 #define IS_INTERNAL_SFTP(c) \
108 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
109 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
110 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
111 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
115 Session *session_new(void);
116 void session_set_fds(Session *, int, int, int, int, int);
117 void session_pty_cleanup(Session *);
118 void session_proctitle(Session *);
119 int session_setup_x11fwd(Session *);
120 int do_exec_pty(Session *, const char *);
121 int do_exec_no_pty(Session *, const char *);
122 int do_exec(Session *, const char *);
123 void do_login(Session *, const char *);
124 #ifdef LOGIN_NEEDS_UTMPX
125 static void do_pre_login(Session *s);
127 void do_child(Session *, const char *);
129 int check_quietlogin(Session *, const char *);
131 static void do_authenticated1(Authctxt *);
132 static void do_authenticated2(Authctxt *);
134 static int session_pty_req(Session *);
137 extern ServerOptions options;
138 extern char *__progname;
139 extern int log_stderr;
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 Buffer loginmsg;
146 /* original command from peer. */
147 const char *original_command = NULL;
150 static int sessions_first_unused = -1;
151 static int sessions_nalloc = 0;
152 static Session *sessions = NULL;
154 #define SUBSYSTEM_NONE 0
155 #define SUBSYSTEM_EXT 1
156 #define SUBSYSTEM_INT_SFTP 2
157 #define SUBSYSTEM_INT_SFTP_ERROR 3
159 #ifdef HAVE_LOGIN_CAP
163 static int is_child = 0;
165 /* Name and directory of socket for authentication agent forwarding. */
166 static char *auth_sock_name = NULL;
167 static char *auth_sock_dir = NULL;
169 /* removes the agent forwarding socket */
172 auth_sock_cleanup_proc(struct passwd *pw)
174 if (auth_sock_name != NULL) {
175 temporarily_use_uid(pw);
176 unlink(auth_sock_name);
177 rmdir(auth_sock_dir);
178 auth_sock_name = NULL;
184 auth_input_request_forwarding(struct passwd * pw)
189 if (auth_sock_name != NULL) {
190 error("authentication forwarding requested twice.");
194 /* Temporarily drop privileged uid for mkdir/bind. */
195 temporarily_use_uid(pw);
197 /* Allocate a buffer for the socket name, and format the name. */
198 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
200 /* Create private directory for socket */
201 if (mkdtemp(auth_sock_dir) == NULL) {
202 packet_send_debug("Agent forwarding disabled: "
203 "mkdtemp() failed: %.100s", strerror(errno));
206 auth_sock_dir = NULL;
210 xasprintf(&auth_sock_name, "%s/agent.%ld",
211 auth_sock_dir, (long) getpid());
213 /* Start a Unix listener on auth_sock_name. */
214 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
216 /* Restore the privileged uid. */
219 /* Check for socket/bind/listen failure. */
223 /* Allocate a channel for the authentication agent socket. */
224 nc = channel_new("auth socket",
225 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
226 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
227 0, "auth socket", 1);
228 nc->path = xstrdup(auth_sock_name);
232 free(auth_sock_name);
233 if (auth_sock_dir != NULL) {
234 rmdir(auth_sock_dir);
239 auth_sock_name = NULL;
240 auth_sock_dir = NULL;
245 display_loginmsg(void)
247 if (buffer_len(&loginmsg) > 0) {
248 buffer_append(&loginmsg, "\0", 1);
249 printf("%s", (char *)buffer_ptr(&loginmsg));
250 buffer_clear(&loginmsg);
255 do_authenticated(Authctxt *authctxt)
257 setproctitle("%s", authctxt->pw->pw_name);
259 /* setup the channel layer */
260 /* XXX - streamlocal? */
261 if (no_port_forwarding_flag ||
262 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
263 channel_disable_adm_local_opens();
265 channel_permit_all_opens();
270 do_authenticated2(authctxt);
272 do_authenticated1(authctxt);
274 do_cleanup(authctxt);
278 * Prepares for an interactive session. This is called after the user has
279 * been successfully authenticated. During this message exchange, pseudo
280 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
281 * are requested, etc.
284 do_authenticated1(Authctxt *authctxt)
288 int success, type, screen_flag;
289 int enable_compression_after_reply = 0;
290 u_int proto_len, data_len, dlen, compression_level = 0;
294 error("no more sessions");
297 s->authctxt = authctxt;
298 s->pw = authctxt->pw;
301 * We stay in this loop until the client requests to execute a shell
307 /* Get a packet from the client. */
308 type = packet_read();
310 /* Process the packet. */
312 case SSH_CMSG_REQUEST_COMPRESSION:
313 compression_level = packet_get_int();
315 if (compression_level < 1 || compression_level > 9) {
316 packet_send_debug("Received invalid compression level %d.",
320 if (options.compression == COMP_NONE) {
321 debug2("compression disabled");
324 /* Enable compression after we have responded with SUCCESS. */
325 enable_compression_after_reply = 1;
329 case SSH_CMSG_REQUEST_PTY:
330 success = session_pty_req(s);
333 case SSH_CMSG_X11_REQUEST_FORWARDING:
334 s->auth_proto = packet_get_string(&proto_len);
335 s->auth_data = packet_get_string(&data_len);
337 screen_flag = packet_get_protocol_flags() &
338 SSH_PROTOFLAG_SCREEN_NUMBER;
339 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
341 if (packet_remaining() == 4) {
343 debug2("Buggy client: "
344 "X11 screen flag missing");
345 s->screen = packet_get_int();
350 success = session_setup_x11fwd(s);
354 s->auth_proto = NULL;
359 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
360 if (!options.allow_agent_forwarding ||
361 no_agent_forwarding_flag || compat13) {
362 debug("Authentication agent forwarding not permitted for this authentication.");
365 debug("Received authentication agent forwarding request.");
366 success = auth_input_request_forwarding(s->pw);
369 case SSH_CMSG_PORT_FORWARD_REQUEST:
370 if (no_port_forwarding_flag) {
371 debug("Port forwarding not permitted for this authentication.");
374 if (!(options.allow_tcp_forwarding & FORWARD_REMOTE)) {
375 debug("Port forwarding not permitted.");
378 debug("Received TCP/IP port forwarding request.");
379 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
380 &options.fwd_opts) < 0) {
381 debug("Port forwarding failed.");
387 case SSH_CMSG_MAX_PACKET_SIZE:
388 if (packet_set_maxsize(packet_get_int()) > 0)
392 case SSH_CMSG_EXEC_SHELL:
393 case SSH_CMSG_EXEC_CMD:
394 if (type == SSH_CMSG_EXEC_CMD) {
395 command = packet_get_string(&dlen);
396 debug("Exec command '%.500s'", command);
397 if (do_exec(s, command) != 0)
399 "command execution failed");
402 if (do_exec(s, NULL) != 0)
404 "shell execution failed");
412 * Any unknown messages in this phase are ignored,
413 * and a failure message is returned.
415 logit("Unknown packet type received after authentication: %d", type);
417 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
421 /* Enable compression now that we have replied if appropriate. */
422 if (enable_compression_after_reply) {
423 enable_compression_after_reply = 0;
424 packet_start_compression(compression_level);
431 * This is called to fork and execute a command when we have no tty. This
432 * will call do_child from the child, and server_loop from the parent after
433 * setting up file descriptors and such.
436 do_exec_no_pty(Session *s, const char *command)
441 int pin[2], pout[2], perr[2];
444 fatal("do_exec_no_pty: no session");
446 /* Allocate pipes for communicating with the program. */
448 error("%s: pipe in: %.100s", __func__, strerror(errno));
451 if (pipe(pout) < 0) {
452 error("%s: pipe out: %.100s", __func__, strerror(errno));
457 if (pipe(perr) < 0) {
458 error("%s: pipe err: %.100s", __func__,
467 int inout[2], err[2];
470 fatal("do_exec_no_pty: no session");
472 /* Uses socket pairs to communicate with the program. */
473 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
474 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
477 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
478 error("%s: socketpair #2: %.100s", __func__,
486 session_proctitle(s);
488 /* Fork the child. */
489 switch ((pid = fork())) {
491 error("%s: fork: %.100s", __func__, strerror(errno));
509 /* Child. Reinitialize the log since the pid has changed. */
510 log_init(__progname, options.log_level,
511 options.log_facility, log_stderr);
514 * Create a new session and process group since the 4.4BSD
515 * setlogin() affects the entire process group.
518 error("setsid failed: %.100s", strerror(errno));
522 * Redirect stdin. We close the parent side of the socket
523 * pair, and make the child side the standard input.
526 if (dup2(pin[0], 0) < 0)
527 perror("dup2 stdin");
530 /* Redirect stdout. */
532 if (dup2(pout[1], 1) < 0)
533 perror("dup2 stdout");
536 /* Redirect stderr. */
538 if (dup2(perr[1], 2) < 0)
539 perror("dup2 stderr");
543 * Redirect stdin, stdout, and stderr. Stdin and stdout will
544 * use the same socket, as some programs (particularly rdist)
545 * seem to depend on it.
549 if (dup2(inout[0], 0) < 0) /* stdin */
550 perror("dup2 stdin");
551 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
552 perror("dup2 stdout");
554 if (dup2(err[0], 2) < 0) /* stderr */
555 perror("dup2 stderr");
561 cray_init_job(s->pw); /* set up cray jid and tmpdir */
564 /* Do processing for the child (exec command etc). */
565 do_child(s, command);
572 signal(WJSIGNAL, cray_job_termination_handler);
575 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
579 /* Set interactive/non-interactive mode. */
580 packet_set_interactive(s->display != NULL,
581 options.ip_qos_interactive, options.ip_qos_bulk);
584 * Clear loginmsg, since it's the child's responsibility to display
585 * it to the user, otherwise multiple sessions may accumulate
586 * multiple copies of the login messages.
588 buffer_clear(&loginmsg);
591 /* We are the parent. Close the child sides of the pipes. */
597 session_set_fds(s, pin[1], pout[0], perr[0],
600 /* Enter the interactive session. */
601 server_loop(pid, pin[1], pout[0], perr[0]);
602 /* server_loop has closed pin[1], pout[0], and perr[0]. */
605 /* We are the parent. Close the child sides of the socket pairs. */
610 * Enter the interactive session. Note: server_loop must be able to
611 * handle the case that fdin and fdout are the same.
614 session_set_fds(s, inout[1], inout[1], err[1],
617 server_loop(pid, inout[1], inout[1], err[1]);
618 /* server_loop has closed inout[1] and err[1]. */
625 * This is called to fork and execute a command when we have a tty. This
626 * will call do_child from the child, and server_loop from the parent after
627 * setting up file descriptors, controlling tty, updating wtmp, utmp,
628 * lastlog, and other such operations.
631 do_exec_pty(Session *s, const char *command)
633 int fdout, ptyfd, ttyfd, ptymaster;
637 fatal("do_exec_pty: no session");
642 * Create another descriptor of the pty master side for use as the
643 * standard input. We could use the original descriptor, but this
644 * simplifies code in server_loop. The descriptor is bidirectional.
645 * Do this before forking (and cleanup in the child) so as to
646 * detect and gracefully fail out-of-fd conditions.
648 if ((fdout = dup(ptyfd)) < 0) {
649 error("%s: dup #1: %s", __func__, strerror(errno));
654 /* we keep a reference to the pty master */
655 if ((ptymaster = dup(ptyfd)) < 0) {
656 error("%s: dup #2: %s", __func__, strerror(errno));
663 /* Fork the child. */
664 switch ((pid = fork())) {
666 error("%s: fork: %.100s", __func__, strerror(errno));
678 /* Child. Reinitialize the log because the pid has changed. */
679 log_init(__progname, options.log_level,
680 options.log_facility, log_stderr);
681 /* Close the master side of the pseudo tty. */
684 /* Make the pseudo tty our controlling tty. */
685 pty_make_controlling_tty(&ttyfd, s->tty);
687 /* Redirect stdin/stdout/stderr from the pseudo tty. */
688 if (dup2(ttyfd, 0) < 0)
689 error("dup2 stdin: %s", strerror(errno));
690 if (dup2(ttyfd, 1) < 0)
691 error("dup2 stdout: %s", strerror(errno));
692 if (dup2(ttyfd, 2) < 0)
693 error("dup2 stderr: %s", strerror(errno));
695 /* Close the extra descriptor for the pseudo tty. */
698 /* record login, etc. similar to login(1) */
700 if (!(options.use_login && command == NULL)) {
702 cray_init_job(s->pw); /* set up cray jid and tmpdir */
704 do_login(s, command);
706 # ifdef LOGIN_NEEDS_UTMPX
712 * Do common processing for the child, such as execing
715 do_child(s, command);
722 signal(WJSIGNAL, cray_job_termination_handler);
725 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
730 /* Parent. Close the slave side of the pseudo tty. */
733 /* Enter interactive session. */
734 s->ptymaster = ptymaster;
735 packet_set_interactive(1,
736 options.ip_qos_interactive, options.ip_qos_bulk);
738 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
740 server_loop(pid, ptyfd, fdout, -1);
741 /* server_loop _has_ closed ptyfd and fdout. */
746 #ifdef LOGIN_NEEDS_UTMPX
748 do_pre_login(Session *s)
751 struct sockaddr_storage from;
752 pid_t pid = getpid();
755 * Get IP address of client. If the connection is not a socket, let
756 * the address be 0.0.0.0.
758 memset(&from, 0, sizeof(from));
759 fromlen = sizeof(from);
760 if (packet_connection_is_on_socket()) {
761 if (getpeername(packet_get_connection_in(),
762 (struct sockaddr *)&from, &fromlen) < 0) {
763 debug("getpeername: %.100s", strerror(errno));
768 record_utmp_only(pid, s->tty, s->pw->pw_name,
769 get_remote_name_or_ip(utmp_len, options.use_dns),
770 (struct sockaddr *)&from, fromlen);
775 * This is called to fork and execute a command. If another command is
776 * to be forced, execute that instead.
779 do_exec(Session *s, const char *command)
782 const char *forced = NULL;
783 char session_type[1024], *tty = NULL;
785 if (options.adm_forced_command) {
786 original_command = command;
787 command = options.adm_forced_command;
789 } else if (forced_command) {
790 original_command = command;
791 command = forced_command;
792 forced = "(key-option)";
794 if (forced != NULL) {
795 if (IS_INTERNAL_SFTP(command)) {
796 s->is_subsystem = s->is_subsystem ?
797 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
798 } else if (s->is_subsystem)
799 s->is_subsystem = SUBSYSTEM_EXT;
800 snprintf(session_type, sizeof(session_type),
801 "forced-command %s '%.900s'", forced, command);
802 } else if (s->is_subsystem) {
803 snprintf(session_type, sizeof(session_type),
804 "subsystem '%.900s'", s->subsys);
805 } else if (command == NULL) {
806 snprintf(session_type, sizeof(session_type), "shell");
808 /* NB. we don't log unforced commands to preserve privacy */
809 snprintf(session_type, sizeof(session_type), "command");
812 if (s->ttyfd != -1) {
814 if (strncmp(tty, "/dev/", 5) == 0)
818 verbose("Starting session: %s%s%s for %s from %.200s port %d",
820 tty == NULL ? "" : " on ",
821 tty == NULL ? "" : tty,
826 #ifdef SSH_AUDIT_EVENTS
828 PRIVSEP(audit_run_command(command));
829 else if (s->ttyfd == -1) {
830 char *shell = s->pw->pw_shell;
832 if (shell[0] == '\0') /* empty shell means /bin/sh */
834 PRIVSEP(audit_run_command(shell));
838 ret = do_exec_pty(s, command);
840 ret = do_exec_no_pty(s, command);
842 original_command = NULL;
845 * Clear loginmsg: it's the child's responsibility to display
846 * it to the user, otherwise multiple sessions may accumulate
847 * multiple copies of the login messages.
849 buffer_clear(&loginmsg);
854 /* administrative, login(1)-like work */
856 do_login(Session *s, const char *command)
859 struct sockaddr_storage from;
860 struct passwd * pw = s->pw;
861 pid_t pid = getpid();
864 * Get IP address of client. If the connection is not a socket, let
865 * the address be 0.0.0.0.
867 memset(&from, 0, sizeof(from));
868 fromlen = sizeof(from);
869 if (packet_connection_is_on_socket()) {
870 if (getpeername(packet_get_connection_in(),
871 (struct sockaddr *)&from, &fromlen) < 0) {
872 debug("getpeername: %.100s", strerror(errno));
877 /* Record that there was a login on that tty from the remote host. */
879 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
880 get_remote_name_or_ip(utmp_len,
882 (struct sockaddr *)&from, fromlen);
886 * If password change is needed, do it now.
887 * This needs to occur before the ~/.hushlogin check.
889 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
892 s->authctxt->force_pwchange = 0;
893 /* XXX - signal [net] parent to enable forwardings */
897 if (check_quietlogin(s, command))
906 * Display the message of the day.
914 if (options.print_motd) {
915 #ifdef HAVE_LOGIN_CAP
916 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
919 f = fopen("/etc/motd", "r");
922 while (fgets(buf, sizeof(buf), f))
931 * Check for quiet login, either .hushlogin or command given.
934 check_quietlogin(Session *s, const char *command)
937 struct passwd *pw = s->pw;
940 /* Return 1 if .hushlogin exists or a command given. */
943 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
944 #ifdef HAVE_LOGIN_CAP
945 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
948 if (stat(buf, &st) >= 0)
955 * Sets the value of the given variable in the environment. If the variable
956 * already exists, its value is overridden.
959 child_set_env(char ***envp, u_int *envsizep, const char *name,
966 if (strchr(name, '=') != NULL) {
967 error("Invalid environment variable \"%.100s\"", name);
972 * If we're passed an uninitialized list, allocate a single null
973 * entry before continuing.
975 if (*envp == NULL && *envsizep == 0) {
976 *envp = xmalloc(sizeof(char *));
982 * Find the slot where the value should be stored. If the variable
983 * already exists, we reuse the slot; otherwise we append a new slot
984 * at the end of the array, expanding if necessary.
987 namelen = strlen(name);
988 for (i = 0; env[i]; i++)
989 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
992 /* Reuse the slot. */
995 /* New variable. Expand if necessary. */
997 if (i >= envsize - 1) {
999 fatal("child_set_env: too many env vars");
1001 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1002 *envsizep = envsize;
1004 /* Need to set the NULL pointer at end of array beyond the new slot. */
1008 /* Allocate space and format the variable in the appropriate slot. */
1009 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1010 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1014 * Reads environment variables from the given file and adds/overrides them
1015 * into the environment. If the file does not exist, this does nothing.
1016 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1017 * and assignments of the form name=value. No other forms are allowed.
1020 read_environment_file(char ***env, u_int *envsize,
1021 const char *filename)
1028 f = fopen(filename, "r");
1032 while (fgets(buf, sizeof(buf), f)) {
1033 if (++lineno > 1000)
1034 fatal("Too many lines in environment file %s", filename);
1035 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1037 if (!*cp || *cp == '#' || *cp == '\n')
1040 cp[strcspn(cp, "\n")] = '\0';
1042 value = strchr(cp, '=');
1043 if (value == NULL) {
1044 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1049 * Replace the equals sign by nul, and advance value to
1054 child_set_env(env, envsize, cp, value);
1059 #ifdef HAVE_ETC_DEFAULT_LOGIN
1061 * Return named variable from specified environment, or NULL if not present.
1064 child_get_env(char **env, const char *name)
1070 for (i=0; env[i] != NULL; i++)
1071 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1072 return(env[i] + len + 1);
1077 * Read /etc/default/login.
1078 * We pick up the PATH (or SUPATH for root) and UMASK.
1081 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1083 char **tmpenv = NULL, *var;
1084 u_int i, tmpenvsize = 0;
1088 * We don't want to copy the whole file to the child's environment,
1089 * so we use a temporary environment and copy the variables we're
1092 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1098 var = child_get_env(tmpenv, "SUPATH");
1100 var = child_get_env(tmpenv, "PATH");
1102 child_set_env(env, envsize, "PATH", var);
1104 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1105 if (sscanf(var, "%5lo", &mask) == 1)
1106 umask((mode_t)mask);
1108 for (i = 0; tmpenv[i] != NULL; i++)
1112 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1115 copy_environment(char **source, char ***env, u_int *envsize)
1117 char *var_name, *var_val;
1123 for(i = 0; source[i] != NULL; i++) {
1124 var_name = xstrdup(source[i]);
1125 if ((var_val = strstr(var_name, "=")) == NULL) {
1131 debug3("Copy environment: %s=%s", var_name, var_val);
1132 child_set_env(env, envsize, var_name, var_val);
1139 do_setup_env(Session *s, const char *shell)
1144 struct passwd *pw = s->pw;
1145 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1148 extern char **environ;
1152 /* Initialize the environment. */
1154 env = xcalloc(envsize, sizeof(char *));
1159 * The Windows environment contains some setting which are
1160 * important for a running system. They must not be dropped.
1165 p = fetch_windows_environment();
1166 copy_environment(p, &env, &envsize);
1167 free_windows_environment(p);
1172 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1175 /* Allow any GSSAPI methods that we've used to alter
1176 * the childs environment as they see fit
1178 ssh_gssapi_do_child(&env, &envsize);
1181 if (!options.use_login) {
1182 /* Set basic environment. */
1183 for (i = 0; i < s->num_env; i++)
1184 child_set_env(&env, &envsize, s->env[i].name,
1187 child_set_env(&env, &envsize, "USER", pw->pw_name);
1188 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1190 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1192 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1193 snprintf(buf, sizeof buf, "%.200s/%.50s",
1194 _PATH_MAILDIR, pw->pw_name);
1195 child_set_env(&env, &envsize, "MAIL", buf);
1196 #ifdef HAVE_LOGIN_CAP
1197 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1198 child_set_env(&env, &envsize, "TERM", "su");
1200 environ = xmalloc(sizeof(char *));
1202 (void) setusercontext(lc, pw, pw->pw_uid,
1203 LOGIN_SETENV|LOGIN_SETPATH);
1204 copy_environment(environ, &env, &envsize);
1205 for (var = environ; *var != NULL; ++var)
1209 #else /* HAVE_LOGIN_CAP */
1210 # ifndef HAVE_CYGWIN
1212 * There's no standard path on Windows. The path contains
1213 * important components pointing to the system directories,
1214 * needed for loading shared libraries. So the path better
1215 * remains intact here.
1217 # ifdef HAVE_ETC_DEFAULT_LOGIN
1218 read_etc_default_login(&env, &envsize, pw->pw_uid);
1219 path = child_get_env(env, "PATH");
1220 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1221 if (path == NULL || *path == '\0') {
1222 child_set_env(&env, &envsize, "PATH",
1223 s->pw->pw_uid == 0 ?
1224 SUPERUSER_PATH : _PATH_STDPATH);
1226 # endif /* HAVE_CYGWIN */
1227 #endif /* HAVE_LOGIN_CAP */
1229 /* Normal systems set SHELL by default. */
1230 child_set_env(&env, &envsize, "SHELL", shell);
1233 /* Set custom environment options from RSA authentication. */
1234 if (!options.use_login) {
1235 while (custom_environment) {
1236 struct envstring *ce = custom_environment;
1239 for (i = 0; str[i] != '=' && str[i]; i++)
1241 if (str[i] == '=') {
1243 child_set_env(&env, &envsize, str, str + i + 1);
1245 custom_environment = ce->next;
1251 /* SSH_CLIENT deprecated */
1252 snprintf(buf, sizeof buf, "%.50s %d %d",
1253 get_remote_ipaddr(), get_remote_port(), get_local_port());
1254 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1256 laddr = get_local_ipaddr(packet_get_connection_in());
1257 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1258 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1260 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1263 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1265 child_set_env(&env, &envsize, "TERM", s->term);
1267 child_set_env(&env, &envsize, "DISPLAY", s->display);
1268 if (original_command)
1269 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1273 if (cray_tmpdir[0] != '\0')
1274 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1275 #endif /* _UNICOS */
1278 * Since we clear KRB5CCNAME at startup, if it's set now then it
1279 * must have been set by a native authentication method (eg AIX or
1280 * SIA), so copy it to the child.
1285 if ((cp = getenv("KRB5CCNAME")) != NULL)
1286 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1293 if ((cp = getenv("AUTHSTATE")) != NULL)
1294 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1295 read_environment_file(&env, &envsize, "/etc/environment");
1299 if (s->authctxt->krb5_ccname)
1300 child_set_env(&env, &envsize, "KRB5CCNAME",
1301 s->authctxt->krb5_ccname);
1305 * Pull in any environment variables that may have
1308 if (options.use_pam) {
1311 p = fetch_pam_child_environment();
1312 copy_environment(p, &env, &envsize);
1313 free_pam_environment(p);
1315 p = fetch_pam_environment();
1316 copy_environment(p, &env, &envsize);
1317 free_pam_environment(p);
1319 #endif /* USE_PAM */
1321 if (auth_sock_name != NULL)
1322 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1325 /* read $HOME/.ssh/environment. */
1326 if (options.permit_user_env && !options.use_login) {
1327 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1328 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1329 read_environment_file(&env, &envsize, buf);
1332 /* dump the environment */
1333 fprintf(stderr, "Environment:\n");
1334 for (i = 0; env[i]; i++)
1335 fprintf(stderr, " %.200s\n", env[i]);
1341 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1342 * first in this order).
1345 do_rc_files(Session *s, const char *shell)
1353 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1355 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1356 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1357 !no_user_rc && options.permit_user_rc &&
1358 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1359 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1360 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1362 fprintf(stderr, "Running %s\n", cmd);
1363 f = popen(cmd, "w");
1366 fprintf(f, "%s %s\n", s->auth_proto,
1370 fprintf(stderr, "Could not run %s\n",
1372 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1374 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1375 _PATH_SSH_SYSTEM_RC);
1376 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1379 fprintf(f, "%s %s\n", s->auth_proto,
1383 fprintf(stderr, "Could not run %s\n",
1384 _PATH_SSH_SYSTEM_RC);
1385 } else if (do_xauth && options.xauth_location != NULL) {
1386 /* Add authority data to .Xauthority if appropriate. */
1389 "Running %.500s remove %.100s\n",
1390 options.xauth_location, s->auth_display);
1392 "%.500s add %.100s %.100s %.100s\n",
1393 options.xauth_location, s->auth_display,
1394 s->auth_proto, s->auth_data);
1396 snprintf(cmd, sizeof cmd, "%s -q -",
1397 options.xauth_location);
1398 f = popen(cmd, "w");
1400 fprintf(f, "remove %s\n",
1402 fprintf(f, "add %s %s %s\n",
1403 s->auth_display, s->auth_proto,
1407 fprintf(stderr, "Could not run %s\n",
1414 do_nologin(struct passwd *pw)
1417 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1420 #ifdef HAVE_LOGIN_CAP
1421 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1423 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1425 if (pw->pw_uid == 0)
1429 if (stat(nl, &sb) == -1) {
1435 /* /etc/nologin exists. Print its contents if we can and exit. */
1436 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1437 if ((f = fopen(nl, "r")) != NULL) {
1438 while (fgets(buf, sizeof(buf), f))
1446 * Chroot into a directory after checking it for safety: all path components
1447 * must be root-owned directories with strict permissions.
1450 safely_chroot(const char *path, uid_t uid)
1453 char component[PATH_MAX];
1457 fatal("chroot path does not begin at root");
1458 if (strlen(path) >= sizeof(component))
1459 fatal("chroot path too long");
1462 * Descend the path, checking that each component is a
1463 * root-owned directory with strict permissions.
1465 for (cp = path; cp != NULL;) {
1466 if ((cp = strchr(cp, '/')) == NULL)
1467 strlcpy(component, path, sizeof(component));
1470 memcpy(component, path, cp - path);
1471 component[cp - path] = '\0';
1474 debug3("%s: checking '%s'", __func__, component);
1476 if (stat(component, &st) != 0)
1477 fatal("%s: stat(\"%s\"): %s", __func__,
1478 component, strerror(errno));
1479 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1480 fatal("bad ownership or modes for chroot "
1481 "directory %s\"%s\"",
1482 cp == NULL ? "" : "component ", component);
1483 if (!S_ISDIR(st.st_mode))
1484 fatal("chroot path %s\"%s\" is not a directory",
1485 cp == NULL ? "" : "component ", component);
1489 if (chdir(path) == -1)
1490 fatal("Unable to chdir to chroot path \"%s\": "
1491 "%s", path, strerror(errno));
1492 if (chroot(path) == -1)
1493 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1494 if (chdir("/") == -1)
1495 fatal("%s: chdir(/) after chroot: %s",
1496 __func__, strerror(errno));
1497 verbose("Changed root directory to \"%s\"", path);
1500 /* Set login name, uid, gid, and groups. */
1502 do_setusercontext(struct passwd *pw)
1504 char *chroot_path, *tmp;
1506 int doing_chroot = 0;
1509 platform_setusercontext(pw);
1511 if (platform_privileged_uidswap()) {
1512 #ifdef HAVE_LOGIN_CAP
1513 if (setusercontext(lc, pw, pw->pw_uid,
1514 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1515 perror("unable to set user context");
1519 if (setlogin(pw->pw_name) < 0)
1520 error("setlogin failed: %s", strerror(errno));
1521 if (setgid(pw->pw_gid) < 0) {
1525 /* Initialize the group list. */
1526 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1527 perror("initgroups");
1533 platform_setusercontext_post_groups(pw);
1535 if (options.chroot_directory != NULL &&
1536 strcasecmp(options.chroot_directory, "none") != 0) {
1537 tmp = tilde_expand_filename(options.chroot_directory,
1539 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1540 "u", pw->pw_name, (char *)NULL);
1541 safely_chroot(chroot_path, pw->pw_uid);
1544 /* Make sure we don't attempt to chroot again */
1545 free(options.chroot_directory);
1546 options.chroot_directory = NULL;
1552 #ifdef HAVE_LOGIN_CAP
1553 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1554 perror("unable to set user context (setuser)");
1558 * FreeBSD's setusercontext() will not apply the user's
1559 * own umask setting unless running with the user's UID.
1561 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1564 /* In a chroot environment, the set_id() will always fail; typically
1565 * because of the lack of necessary authentication services and runtime
1566 * such as ./usr/lib/libiaf.so, ./usr/lib/libpam.so.1, and ./etc/passwd
1567 * We skip it in the internal sftp chroot case.
1568 * We'll lose auditing and ACLs but permanently_set_uid will
1569 * take care of the rest.
1571 if ((doing_chroot == 0) && set_id(pw->pw_name) != 0) {
1572 fatal("set_id(%s) Failed", pw->pw_name);
1574 # endif /* USE_LIBIAF */
1575 /* Permanently switch to the desired uid. */
1576 permanently_set_uid(pw);
1578 } else if (options.chroot_directory != NULL &&
1579 strcasecmp(options.chroot_directory, "none") != 0) {
1580 fatal("server lacks privileges to chroot to ChrootDirectory");
1583 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1584 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1588 do_pwchange(Session *s)
1591 fprintf(stderr, "WARNING: Your password has expired.\n");
1592 if (s->ttyfd != -1) {
1594 "You must change your password now and login again!\n");
1598 #ifdef PASSWD_NEEDS_USERNAME
1599 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1602 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1607 "Password change required but no TTY available.\n");
1613 launch_login(struct passwd *pw, const char *hostname)
1615 /* Launch login(1). */
1617 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1618 #ifdef xxxLOGIN_NEEDS_TERM
1619 (s->term ? s->term : "unknown"),
1620 #endif /* LOGIN_NEEDS_TERM */
1621 #ifdef LOGIN_NO_ENDOPT
1622 "-p", "-f", pw->pw_name, (char *)NULL);
1624 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1627 /* Login couldn't be executed, die. */
1634 child_close_fds(void)
1636 extern int auth_sock;
1638 if (auth_sock != -1) {
1643 if (packet_get_connection_in() == packet_get_connection_out())
1644 close(packet_get_connection_in());
1646 close(packet_get_connection_in());
1647 close(packet_get_connection_out());
1650 * Close all descriptors related to channels. They will still remain
1651 * open in the parent.
1653 /* XXX better use close-on-exec? -markus */
1654 channel_close_all();
1657 * Close any extra file descriptors. Note that there may still be
1658 * descriptors left by system functions. They will be closed later.
1663 * Close any extra open file descriptors so that we don't have them
1664 * hanging around in clients. Note that we want to do this after
1665 * initgroups, because at least on Solaris 2.3 it leaves file
1668 closefrom(STDERR_FILENO + 1);
1672 * Performs common processing for the child, such as setting up the
1673 * environment, closing extra file descriptors, setting the user and group
1674 * ids, and executing the command or shell.
1678 do_child(Session *s, const char *command)
1680 extern char **environ;
1682 char *argv[ARGV_MAX];
1683 const char *shell, *shell0, *hostname = NULL;
1684 struct passwd *pw = s->pw;
1687 /* remove hostkey from the child's memory */
1688 destroy_sensitive_data();
1690 /* Force a password change */
1691 if (s->authctxt->force_pwchange) {
1692 do_setusercontext(pw);
1698 /* login(1) is only called if we execute the login shell */
1699 if (options.use_login && command != NULL)
1700 options.use_login = 0;
1703 cray_setup(pw->pw_uid, pw->pw_name, command);
1704 #endif /* _UNICOS */
1707 * Login(1) does this as well, and it needs uid 0 for the "-h"
1708 * switch, so we let login(1) to this for us.
1710 if (!options.use_login) {
1712 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1713 if (!check_quietlogin(s, command))
1715 #else /* HAVE_OSF_SIA */
1716 /* When PAM is enabled we rely on it to do the nologin check */
1717 if (!options.use_pam)
1719 do_setusercontext(pw);
1721 * PAM session modules in do_setusercontext may have
1722 * generated messages, so if this in an interactive
1723 * login then display them too.
1725 if (!check_quietlogin(s, command))
1727 #endif /* HAVE_OSF_SIA */
1731 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1732 debug3("PAM session not opened, exiting");
1739 * Get the shell from the password data. An empty shell field is
1740 * legal, and means /bin/sh.
1742 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1745 * Make sure $SHELL points to the shell from the password file,
1746 * even if shell is overridden from login.conf
1748 env = do_setup_env(s, shell);
1750 #ifdef HAVE_LOGIN_CAP
1751 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1754 /* we have to stash the hostname before we close our socket. */
1755 if (options.use_login)
1756 hostname = get_remote_name_or_ip(utmp_len,
1759 * Close the connection descriptors; note that this is the child, and
1760 * the server will still have the socket open, and it is important
1761 * that we do not shutdown it. Note that the descriptors cannot be
1762 * closed before building the environment, as we call
1763 * get_remote_ipaddr there.
1768 * Must take new environment into use so that .ssh/rc,
1769 * /etc/ssh/sshrc and xauth are run in the proper environment.
1773 #if defined(KRB5) && defined(USE_AFS)
1775 * At this point, we check to see if AFS is active and if we have
1776 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1777 * if we can (and need to) extend the ticket into an AFS token. If
1778 * we don't do this, we run into potential problems if the user's
1779 * home directory is in AFS and it's not world-readable.
1782 if (options.kerberos_get_afs_token && k_hasafs() &&
1783 (s->authctxt->krb5_ctx != NULL)) {
1786 debug("Getting AFS token");
1790 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1791 krb5_afslog(s->authctxt->krb5_ctx,
1792 s->authctxt->krb5_fwd_ccache, cell, NULL);
1794 krb5_afslog_home(s->authctxt->krb5_ctx,
1795 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1799 /* Change current directory to the user's home directory. */
1800 if (chdir(pw->pw_dir) < 0) {
1801 /* Suppress missing homedir warning for chroot case */
1802 #ifdef HAVE_LOGIN_CAP
1803 r = login_getcapbool(lc, "requirehome", 0);
1805 if (r || options.chroot_directory == NULL ||
1806 strcasecmp(options.chroot_directory, "none") == 0)
1807 fprintf(stderr, "Could not chdir to home "
1808 "directory %s: %s\n", pw->pw_dir,
1814 closefrom(STDERR_FILENO + 1);
1816 if (!options.use_login)
1817 do_rc_files(s, shell);
1819 /* restore SIGPIPE for child */
1820 signal(SIGPIPE, SIG_DFL);
1822 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1823 printf("This service allows sftp connections only.\n");
1826 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1827 extern int optind, optreset;
1831 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1832 args = xstrdup(command ? command : "sftp-server");
1833 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1834 if (i < ARGV_MAX - 1)
1837 optind = optreset = 1;
1838 __progname = argv[0];
1840 ssh_selinux_change_context("sftpd_t");
1842 exit(sftp_server_main(i, argv, s->pw));
1847 if (options.use_login) {
1848 launch_login(pw, hostname);
1852 /* Get the last component of the shell name. */
1853 if ((shell0 = strrchr(shell, '/')) != NULL)
1859 * If we have no command, execute the shell. In this case, the shell
1860 * name to be passed in argv[0] is preceded by '-' to indicate that
1861 * this is a login shell.
1866 /* Start the shell. Set initial character to '-'. */
1869 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1870 >= sizeof(argv0) - 1) {
1876 /* Execute the shell. */
1879 execve(shell, argv, env);
1881 /* Executing the shell failed. */
1886 * Execute the command using the user's shell. This uses the -c
1887 * option to execute the command.
1889 argv[0] = (char *) shell0;
1891 argv[2] = (char *) command;
1893 execve(shell, argv, env);
1899 session_unused(int id)
1901 debug3("%s: session id %d unused", __func__, id);
1902 if (id >= options.max_sessions ||
1903 id >= sessions_nalloc) {
1904 fatal("%s: insane session id %d (max %d nalloc %d)",
1905 __func__, id, options.max_sessions, sessions_nalloc);
1907 memset(&sessions[id], 0, sizeof(*sessions));
1908 sessions[id].self = id;
1909 sessions[id].used = 0;
1910 sessions[id].chanid = -1;
1911 sessions[id].ptyfd = -1;
1912 sessions[id].ttyfd = -1;
1913 sessions[id].ptymaster = -1;
1914 sessions[id].x11_chanids = NULL;
1915 sessions[id].next_unused = sessions_first_unused;
1916 sessions_first_unused = id;
1924 if (sessions_first_unused == -1) {
1925 if (sessions_nalloc >= options.max_sessions)
1927 debug2("%s: allocate (allocated %d max %d)",
1928 __func__, sessions_nalloc, options.max_sessions);
1929 tmp = xreallocarray(sessions, sessions_nalloc + 1,
1932 error("%s: cannot allocate %d sessions",
1933 __func__, sessions_nalloc + 1);
1937 session_unused(sessions_nalloc++);
1940 if (sessions_first_unused >= sessions_nalloc ||
1941 sessions_first_unused < 0) {
1942 fatal("%s: insane first_unused %d max %d nalloc %d",
1943 __func__, sessions_first_unused, options.max_sessions,
1947 s = &sessions[sessions_first_unused];
1949 fatal("%s: session %d already used",
1950 __func__, sessions_first_unused);
1952 sessions_first_unused = s->next_unused;
1954 s->next_unused = -1;
1955 debug("session_new: session %d", s->self);
1964 for (i = 0; i < sessions_nalloc; i++) {
1965 Session *s = &sessions[i];
1967 debug("dump: used %d next_unused %d session %d %p "
1968 "channel %d pid %ld",
1979 session_open(Authctxt *authctxt, int chanid)
1981 Session *s = session_new();
1982 debug("session_open: channel %d", chanid);
1984 error("no more sessions");
1987 s->authctxt = authctxt;
1988 s->pw = authctxt->pw;
1989 if (s->pw == NULL || !authctxt->valid)
1990 fatal("no user for session %d", s->self);
1991 debug("session_open: session %d: link with channel %d", s->self, chanid);
1997 session_by_tty(char *tty)
2000 for (i = 0; i < sessions_nalloc; i++) {
2001 Session *s = &sessions[i];
2002 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
2003 debug("session_by_tty: session %d tty %s", i, tty);
2007 debug("session_by_tty: unknown tty %.100s", tty);
2013 session_by_channel(int id)
2016 for (i = 0; i < sessions_nalloc; i++) {
2017 Session *s = &sessions[i];
2018 if (s->used && s->chanid == id) {
2019 debug("session_by_channel: session %d channel %d",
2024 debug("session_by_channel: unknown channel %d", id);
2030 session_by_x11_channel(int id)
2034 for (i = 0; i < sessions_nalloc; i++) {
2035 Session *s = &sessions[i];
2037 if (s->x11_chanids == NULL || !s->used)
2039 for (j = 0; s->x11_chanids[j] != -1; j++) {
2040 if (s->x11_chanids[j] == id) {
2041 debug("session_by_x11_channel: session %d "
2042 "channel %d", s->self, id);
2047 debug("session_by_x11_channel: unknown channel %d", id);
2053 session_by_pid(pid_t pid)
2056 debug("session_by_pid: pid %ld", (long)pid);
2057 for (i = 0; i < sessions_nalloc; i++) {
2058 Session *s = &sessions[i];
2059 if (s->used && s->pid == pid)
2062 error("session_by_pid: unknown pid %ld", (long)pid);
2068 session_window_change_req(Session *s)
2070 s->col = packet_get_int();
2071 s->row = packet_get_int();
2072 s->xpixel = packet_get_int();
2073 s->ypixel = packet_get_int();
2075 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2080 session_pty_req(Session *s)
2085 if (no_pty_flag || !options.permit_tty) {
2086 debug("Allocating a pty not permitted for this authentication.");
2089 if (s->ttyfd != -1) {
2090 packet_disconnect("Protocol error: you already have a pty.");
2094 s->term = packet_get_string(&len);
2097 s->col = packet_get_int();
2098 s->row = packet_get_int();
2100 s->row = packet_get_int();
2101 s->col = packet_get_int();
2103 s->xpixel = packet_get_int();
2104 s->ypixel = packet_get_int();
2106 if (strcmp(s->term, "") == 0) {
2111 /* Allocate a pty and open it. */
2112 debug("Allocating pty.");
2113 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
2119 error("session_pty_req: session %d alloc failed", s->self);
2122 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2124 /* for SSH1 the tty modes length is not given */
2126 n_bytes = packet_remaining();
2127 tty_parse_modes(s->ttyfd, &n_bytes);
2130 pty_setowner(s->pw, s->tty);
2132 /* Set window size from the packet. */
2133 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2136 session_proctitle(s);
2141 session_subsystem_req(Session *s)
2149 s->subsys = packet_get_string(&len);
2151 debug2("subsystem request for %.100s by user %s", s->subsys,
2154 for (i = 0; i < options.num_subsystems; i++) {
2155 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
2156 prog = options.subsystem_command[i];
2157 cmd = options.subsystem_args[i];
2158 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2159 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2160 debug("subsystem: %s", prog);
2162 if (stat(prog, &st) < 0)
2163 debug("subsystem: cannot stat %s: %s",
2164 prog, strerror(errno));
2165 s->is_subsystem = SUBSYSTEM_EXT;
2166 debug("subsystem: exec() %s", cmd);
2168 success = do_exec(s, cmd) == 0;
2174 logit("subsystem request for %.100s by user %s failed, "
2175 "subsystem not found", s->subsys, s->pw->pw_name);
2181 session_x11_req(Session *s)
2185 if (s->auth_proto != NULL || s->auth_data != NULL) {
2186 error("session_x11_req: session %d: "
2187 "x11 forwarding already active", s->self);
2190 s->single_connection = packet_get_char();
2191 s->auth_proto = packet_get_string(NULL);
2192 s->auth_data = packet_get_string(NULL);
2193 s->screen = packet_get_int();
2196 success = session_setup_x11fwd(s);
2198 free(s->auth_proto);
2200 s->auth_proto = NULL;
2201 s->auth_data = NULL;
2207 session_shell_req(Session *s)
2210 return do_exec(s, NULL) == 0;
2214 session_exec_req(Session *s)
2218 char *command = packet_get_string(&len);
2220 success = do_exec(s, command) == 0;
2226 session_break_req(Session *s)
2229 packet_get_int(); /* ignored */
2232 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2238 session_env_req(Session *s)
2241 u_int name_len, val_len, i;
2243 name = packet_get_cstring(&name_len);
2244 val = packet_get_cstring(&val_len);
2247 /* Don't set too many environment variables */
2248 if (s->num_env > 128) {
2249 debug2("Ignoring env request %s: too many env vars", name);
2253 for (i = 0; i < options.num_accept_env; i++) {
2254 if (match_pattern(name, options.accept_env[i])) {
2255 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2256 s->env = xreallocarray(s->env, s->num_env + 1,
2258 s->env[s->num_env].name = name;
2259 s->env[s->num_env].val = val;
2264 debug2("Ignoring env request %s: disallowed name", name);
2273 session_auth_agent_req(Session *s)
2275 static int called = 0;
2277 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2278 debug("session_auth_agent_req: no_agent_forwarding_flag");
2285 return auth_input_request_forwarding(s->pw);
2290 session_input_channel_req(Channel *c, const char *rtype)
2295 if ((s = session_by_channel(c->self)) == NULL) {
2296 logit("session_input_channel_req: no session %d req %.100s",
2300 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2303 * a session is in LARVAL state until a shell, a command
2304 * or a subsystem is executed
2306 if (c->type == SSH_CHANNEL_LARVAL) {
2307 if (strcmp(rtype, "shell") == 0) {
2308 success = session_shell_req(s);
2309 } else if (strcmp(rtype, "exec") == 0) {
2310 success = session_exec_req(s);
2311 } else if (strcmp(rtype, "pty-req") == 0) {
2312 success = session_pty_req(s);
2313 } else if (strcmp(rtype, "x11-req") == 0) {
2314 success = session_x11_req(s);
2315 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2316 success = session_auth_agent_req(s);
2317 } else if (strcmp(rtype, "subsystem") == 0) {
2318 success = session_subsystem_req(s);
2319 } else if (strcmp(rtype, "env") == 0) {
2320 success = session_env_req(s);
2323 if (strcmp(rtype, "window-change") == 0) {
2324 success = session_window_change_req(s);
2325 } else if (strcmp(rtype, "break") == 0) {
2326 success = session_break_req(s);
2333 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2337 fatal("session_set_fds: called for proto != 2.0");
2339 * now that have a child and a pipe to the child,
2340 * we can activate our channel and register the fd's
2342 if (s->chanid == -1)
2343 fatal("no channel for session %d", s->self);
2344 channel_set_fds(s->chanid,
2346 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2347 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2351 * Function to perform pty cleanup. Also called if we get aborted abnormally
2352 * (e.g., due to a dropped connection).
2355 session_pty_cleanup2(Session *s)
2358 error("session_pty_cleanup: no session");
2364 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2366 /* Record that the user has logged out. */
2368 record_logout(s->pid, s->tty, s->pw->pw_name);
2370 /* Release the pseudo-tty. */
2372 pty_release(s->tty);
2375 * Close the server side of the socket pairs. We must do this after
2376 * the pty cleanup, so that another process doesn't get this pty
2377 * while we're still cleaning up.
2379 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2380 error("close(s->ptymaster/%d): %s",
2381 s->ptymaster, strerror(errno));
2383 /* unlink pty from session */
2388 session_pty_cleanup(Session *s)
2390 PRIVSEP(session_pty_cleanup2(s));
2396 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2411 return "SIG@openssh.com";
2415 session_close_x11(int id)
2419 if ((c = channel_by_id(id)) == NULL) {
2420 debug("session_close_x11: x11 channel %d missing", id);
2422 /* Detach X11 listener */
2423 debug("session_close_x11: detach x11 channel %d", id);
2424 channel_cancel_cleanup(id);
2425 if (c->ostate != CHAN_OUTPUT_CLOSED)
2431 session_close_single_x11(int id, void *arg)
2436 debug3("session_close_single_x11: channel %d", id);
2437 channel_cancel_cleanup(id);
2438 if ((s = session_by_x11_channel(id)) == NULL)
2439 fatal("session_close_single_x11: no x11 channel %d", id);
2440 for (i = 0; s->x11_chanids[i] != -1; i++) {
2441 debug("session_close_single_x11: session %d: "
2442 "closing channel %d", s->self, s->x11_chanids[i]);
2444 * The channel "id" is already closing, but make sure we
2445 * close all of its siblings.
2447 if (s->x11_chanids[i] != id)
2448 session_close_x11(s->x11_chanids[i]);
2450 free(s->x11_chanids);
2451 s->x11_chanids = NULL;
2454 free(s->auth_proto);
2455 s->auth_proto = NULL;
2457 s->auth_data = NULL;
2458 free(s->auth_display);
2459 s->auth_display = NULL;
2463 session_exit_message(Session *s, int status)
2467 if ((c = channel_lookup(s->chanid)) == NULL)
2468 fatal("session_exit_message: session %d: no channel %d",
2469 s->self, s->chanid);
2470 debug("session_exit_message: session %d channel %d pid %ld",
2471 s->self, s->chanid, (long)s->pid);
2473 if (WIFEXITED(status)) {
2474 channel_request_start(s->chanid, "exit-status", 0);
2475 packet_put_int(WEXITSTATUS(status));
2477 } else if (WIFSIGNALED(status)) {
2478 channel_request_start(s->chanid, "exit-signal", 0);
2479 packet_put_cstring(sig2name(WTERMSIG(status)));
2481 packet_put_char(WCOREDUMP(status)? 1 : 0);
2482 #else /* WCOREDUMP */
2484 #endif /* WCOREDUMP */
2485 packet_put_cstring("");
2486 packet_put_cstring("");
2489 /* Some weird exit cause. Just exit. */
2490 packet_disconnect("wait returned status %04x.", status);
2493 /* disconnect channel */
2494 debug("session_exit_message: release channel %d", s->chanid);
2497 * Adjust cleanup callback attachment to send close messages when
2498 * the channel gets EOF. The session will be then be closed
2499 * by session_close_by_channel when the childs close their fds.
2501 channel_register_cleanup(c->self, session_close_by_channel, 1);
2504 * emulate a write failure with 'chan_write_failed', nobody will be
2505 * interested in data we write.
2506 * Note that we must not call 'chan_read_failed', since there could
2507 * be some more data waiting in the pipe.
2509 if (c->ostate != CHAN_OUTPUT_CLOSED)
2510 chan_write_failed(c);
2514 session_close(Session *s)
2518 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2520 session_pty_cleanup(s);
2523 free(s->x11_chanids);
2524 free(s->auth_display);
2526 free(s->auth_proto);
2528 if (s->env != NULL) {
2529 for (i = 0; i < s->num_env; i++) {
2530 free(s->env[i].name);
2531 free(s->env[i].val);
2535 session_proctitle(s);
2536 session_unused(s->self);
2540 session_close_by_pid(pid_t pid, int status)
2542 Session *s = session_by_pid(pid);
2544 debug("session_close_by_pid: no session for pid %ld",
2548 if (s->chanid != -1)
2549 session_exit_message(s, status);
2551 session_pty_cleanup(s);
2556 * this is called when a channel dies before
2557 * the session 'child' itself dies
2560 session_close_by_channel(int id, void *arg)
2562 Session *s = session_by_channel(id);
2566 debug("session_close_by_channel: no session for id %d", id);
2569 debug("session_close_by_channel: channel %d child %ld",
2572 debug("session_close_by_channel: channel %d: has child", id);
2574 * delay detach of session, but release pty, since
2575 * the fd's to the child are already closed
2578 session_pty_cleanup(s);
2581 /* detach by removing callback */
2582 channel_cancel_cleanup(s->chanid);
2584 /* Close any X11 listeners associated with this session */
2585 if (s->x11_chanids != NULL) {
2586 for (i = 0; s->x11_chanids[i] != -1; i++) {
2587 session_close_x11(s->x11_chanids[i]);
2588 s->x11_chanids[i] = -1;
2597 session_destroy_all(void (*closefunc)(Session *))
2600 for (i = 0; i < sessions_nalloc; i++) {
2601 Session *s = &sessions[i];
2603 if (closefunc != NULL)
2612 session_tty_list(void)
2614 static char buf[1024];
2619 for (i = 0; i < sessions_nalloc; i++) {
2620 Session *s = &sessions[i];
2621 if (s->used && s->ttyfd != -1) {
2623 if (strncmp(s->tty, "/dev/", 5) != 0) {
2624 cp = strrchr(s->tty, '/');
2625 cp = (cp == NULL) ? s->tty : cp + 1;
2630 strlcat(buf, ",", sizeof buf);
2631 strlcat(buf, cp, sizeof buf);
2635 strlcpy(buf, "notty", sizeof buf);
2640 session_proctitle(Session *s)
2643 error("no user for session %d", s->self);
2645 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2649 session_setup_x11fwd(Session *s)
2652 char display[512], auth_display[512];
2653 char hostname[NI_MAXHOST];
2656 if (no_x11_forwarding_flag) {
2657 packet_send_debug("X11 forwarding disabled in user configuration file.");
2660 if (!options.x11_forwarding) {
2661 debug("X11 forwarding disabled in server configuration file.");
2664 if (options.xauth_location == NULL ||
2665 (stat(options.xauth_location, &st) == -1)) {
2666 packet_send_debug("No xauth program; cannot forward with spoofing.");
2669 if (options.use_login) {
2670 packet_send_debug("X11 forwarding disabled; "
2671 "not compatible with UseLogin=yes.");
2674 if (s->display != NULL) {
2675 debug("X11 display already set.");
2678 if (x11_create_display_inet(options.x11_display_offset,
2679 options.x11_use_localhost, s->single_connection,
2680 &s->display_number, &s->x11_chanids) == -1) {
2681 debug("x11_create_display_inet failed.");
2684 for (i = 0; s->x11_chanids[i] != -1; i++) {
2685 channel_register_cleanup(s->x11_chanids[i],
2686 session_close_single_x11, 0);
2689 /* Set up a suitable value for the DISPLAY variable. */
2690 if (gethostname(hostname, sizeof(hostname)) < 0)
2691 fatal("gethostname: %.100s", strerror(errno));
2693 * auth_display must be used as the displayname when the
2694 * authorization entry is added with xauth(1). This will be
2695 * different than the DISPLAY string for localhost displays.
2697 if (options.x11_use_localhost) {
2698 snprintf(display, sizeof display, "localhost:%u.%u",
2699 s->display_number, s->screen);
2700 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2701 s->display_number, s->screen);
2702 s->display = xstrdup(display);
2703 s->auth_display = xstrdup(auth_display);
2705 #ifdef IPADDR_IN_DISPLAY
2707 struct in_addr my_addr;
2709 he = gethostbyname(hostname);
2711 error("Can't get IP address for X11 DISPLAY.");
2712 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2715 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2716 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2717 s->display_number, s->screen);
2719 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2720 s->display_number, s->screen);
2722 s->display = xstrdup(display);
2723 s->auth_display = xstrdup(display);
2730 do_authenticated2(Authctxt *authctxt)
2732 server_loop2(authctxt);
2736 do_cleanup(Authctxt *authctxt)
2738 static int called = 0;
2740 debug("do_cleanup");
2742 /* no cleanup if we're in the child for login shell */
2746 /* avoid double cleanup */
2751 if (authctxt == NULL)
2755 if (options.use_pam) {
2757 sshpam_thread_cleanup();
2761 if (!authctxt->authenticated)
2765 if (options.kerberos_ticket_cleanup &&
2767 krb5_cleanup_proc(authctxt);
2771 if (compat20 && options.gss_cleanup_creds)
2772 ssh_gssapi_cleanup_creds();
2775 /* remove agent socket */
2776 auth_sock_cleanup_proc(authctxt->pw);
2779 * Cleanup ptys/utmp only if privsep is disabled,
2780 * or if running in monitor.
2782 if (!use_privsep || mm_is_monitor())
2783 session_destroy_all(session_pty_cleanup2);