1 /* $OpenBSD: session.c,v 1.274 2014/07/15 15:54:14 millert 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>
64 #include "openbsd-compat/sys-queue.h"
83 #include "auth-options.h"
85 #include "pathnames.h"
90 #include "serverloop.h"
94 #include "monitor_wrap.h"
97 #if defined(KRB5) && defined(USE_AFS)
102 #include <selinux/selinux.h>
105 #define IS_INTERNAL_SFTP(c) \
106 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
107 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
108 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
109 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
113 Session *session_new(void);
114 void session_set_fds(Session *, int, int, int, int, int);
115 void session_pty_cleanup(Session *);
116 void session_proctitle(Session *);
117 int session_setup_x11fwd(Session *);
118 int do_exec_pty(Session *, const char *);
119 int do_exec_no_pty(Session *, const char *);
120 int do_exec(Session *, const char *);
121 void do_login(Session *, const char *);
122 #ifdef LOGIN_NEEDS_UTMPX
123 static void do_pre_login(Session *s);
125 void do_child(Session *, const char *);
127 int check_quietlogin(Session *, const char *);
129 static void do_authenticated1(Authctxt *);
130 static void do_authenticated2(Authctxt *);
132 static int session_pty_req(Session *);
135 extern ServerOptions options;
136 extern char *__progname;
137 extern int log_stderr;
138 extern int debug_flag;
139 extern u_int utmp_len;
140 extern int startup_pipe;
141 extern void destroy_sensitive_data(void);
142 extern Buffer loginmsg;
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;
163 /* Name and directory of socket for authentication agent forwarding. */
164 static char *auth_sock_name = NULL;
165 static char *auth_sock_dir = NULL;
167 /* removes the agent forwarding socket */
170 auth_sock_cleanup_proc(struct passwd *pw)
172 if (auth_sock_name != NULL) {
173 temporarily_use_uid(pw);
174 unlink(auth_sock_name);
175 rmdir(auth_sock_dir);
176 auth_sock_name = NULL;
182 auth_input_request_forwarding(struct passwd * pw)
187 if (auth_sock_name != NULL) {
188 error("authentication forwarding requested twice.");
192 /* Temporarily drop privileged uid for mkdir/bind. */
193 temporarily_use_uid(pw);
195 /* Allocate a buffer for the socket name, and format the name. */
196 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
198 /* Create private directory for socket */
199 if (mkdtemp(auth_sock_dir) == NULL) {
200 packet_send_debug("Agent forwarding disabled: "
201 "mkdtemp() failed: %.100s", strerror(errno));
204 auth_sock_dir = NULL;
208 xasprintf(&auth_sock_name, "%s/agent.%ld",
209 auth_sock_dir, (long) getpid());
211 /* Start a Unix listener on auth_sock_name. */
212 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
214 /* Restore the privileged uid. */
217 /* Check for socket/bind/listen failure. */
221 /* Allocate a channel for the authentication agent socket. */
222 nc = channel_new("auth socket",
223 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
224 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
225 0, "auth socket", 1);
226 nc->path = xstrdup(auth_sock_name);
230 free(auth_sock_name);
231 if (auth_sock_dir != NULL) {
232 rmdir(auth_sock_dir);
237 auth_sock_name = NULL;
238 auth_sock_dir = NULL;
243 display_loginmsg(void)
245 if (buffer_len(&loginmsg) > 0) {
246 buffer_append(&loginmsg, "\0", 1);
247 printf("%s", (char *)buffer_ptr(&loginmsg));
248 buffer_clear(&loginmsg);
253 do_authenticated(Authctxt *authctxt)
255 setproctitle("%s", authctxt->pw->pw_name);
257 /* setup the channel layer */
258 /* XXX - streamlocal? */
259 if (no_port_forwarding_flag ||
260 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
261 channel_disable_adm_local_opens();
263 channel_permit_all_opens();
268 do_authenticated2(authctxt);
270 do_authenticated1(authctxt);
272 do_cleanup(authctxt);
276 * Prepares for an interactive session. This is called after the user has
277 * been successfully authenticated. During this message exchange, pseudo
278 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
279 * are requested, etc.
282 do_authenticated1(Authctxt *authctxt)
286 int success, type, screen_flag;
287 int enable_compression_after_reply = 0;
288 u_int proto_len, data_len, dlen, compression_level = 0;
292 error("no more sessions");
295 s->authctxt = authctxt;
296 s->pw = authctxt->pw;
299 * We stay in this loop until the client requests to execute a shell
305 /* Get a packet from the client. */
306 type = packet_read();
308 /* Process the packet. */
310 case SSH_CMSG_REQUEST_COMPRESSION:
311 compression_level = packet_get_int();
313 if (compression_level < 1 || compression_level > 9) {
314 packet_send_debug("Received invalid compression level %d.",
318 if (options.compression == COMP_NONE) {
319 debug2("compression disabled");
322 /* Enable compression after we have responded with SUCCESS. */
323 enable_compression_after_reply = 1;
327 case SSH_CMSG_REQUEST_PTY:
328 success = session_pty_req(s);
331 case SSH_CMSG_X11_REQUEST_FORWARDING:
332 s->auth_proto = packet_get_string(&proto_len);
333 s->auth_data = packet_get_string(&data_len);
335 screen_flag = packet_get_protocol_flags() &
336 SSH_PROTOFLAG_SCREEN_NUMBER;
337 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
339 if (packet_remaining() == 4) {
341 debug2("Buggy client: "
342 "X11 screen flag missing");
343 s->screen = packet_get_int();
348 success = session_setup_x11fwd(s);
352 s->auth_proto = NULL;
357 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
358 if (!options.allow_agent_forwarding ||
359 no_agent_forwarding_flag || compat13) {
360 debug("Authentication agent forwarding not permitted for this authentication.");
363 debug("Received authentication agent forwarding request.");
364 success = auth_input_request_forwarding(s->pw);
367 case SSH_CMSG_PORT_FORWARD_REQUEST:
368 if (no_port_forwarding_flag) {
369 debug("Port forwarding not permitted for this authentication.");
372 if (!(options.allow_tcp_forwarding & FORWARD_REMOTE)) {
373 debug("Port forwarding not permitted.");
376 debug("Received TCP/IP port forwarding request.");
377 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
378 &options.fwd_opts) < 0) {
379 debug("Port forwarding failed.");
385 case SSH_CMSG_MAX_PACKET_SIZE:
386 if (packet_set_maxsize(packet_get_int()) > 0)
390 case SSH_CMSG_EXEC_SHELL:
391 case SSH_CMSG_EXEC_CMD:
392 if (type == SSH_CMSG_EXEC_CMD) {
393 command = packet_get_string(&dlen);
394 debug("Exec command '%.500s'", command);
395 if (do_exec(s, command) != 0)
397 "command execution failed");
400 if (do_exec(s, NULL) != 0)
402 "shell execution failed");
410 * Any unknown messages in this phase are ignored,
411 * and a failure message is returned.
413 logit("Unknown packet type received after authentication: %d", type);
415 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
419 /* Enable compression now that we have replied if appropriate. */
420 if (enable_compression_after_reply) {
421 enable_compression_after_reply = 0;
422 packet_start_compression(compression_level);
429 * This is called to fork and execute a command when we have no tty. This
430 * will call do_child from the child, and server_loop from the parent after
431 * setting up file descriptors and such.
434 do_exec_no_pty(Session *s, const char *command)
439 int pin[2], pout[2], perr[2];
442 fatal("do_exec_no_pty: no session");
444 /* Allocate pipes for communicating with the program. */
446 error("%s: pipe in: %.100s", __func__, strerror(errno));
449 if (pipe(pout) < 0) {
450 error("%s: pipe out: %.100s", __func__, strerror(errno));
455 if (pipe(perr) < 0) {
456 error("%s: pipe err: %.100s", __func__,
465 int inout[2], err[2];
468 fatal("do_exec_no_pty: no session");
470 /* Uses socket pairs to communicate with the program. */
471 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
472 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
475 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
476 error("%s: socketpair #2: %.100s", __func__,
484 session_proctitle(s);
486 /* Fork the child. */
487 switch ((pid = fork())) {
489 error("%s: fork: %.100s", __func__, strerror(errno));
507 /* Child. Reinitialize the log since the pid has changed. */
508 log_init(__progname, options.log_level,
509 options.log_facility, log_stderr);
512 * Create a new session and process group since the 4.4BSD
513 * setlogin() affects the entire process group.
516 error("setsid failed: %.100s", strerror(errno));
520 * Redirect stdin. We close the parent side of the socket
521 * pair, and make the child side the standard input.
524 if (dup2(pin[0], 0) < 0)
525 perror("dup2 stdin");
528 /* Redirect stdout. */
530 if (dup2(pout[1], 1) < 0)
531 perror("dup2 stdout");
534 /* Redirect stderr. */
536 if (dup2(perr[1], 2) < 0)
537 perror("dup2 stderr");
541 * Redirect stdin, stdout, and stderr. Stdin and stdout will
542 * use the same socket, as some programs (particularly rdist)
543 * seem to depend on it.
547 if (dup2(inout[0], 0) < 0) /* stdin */
548 perror("dup2 stdin");
549 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
550 perror("dup2 stdout");
552 if (dup2(err[0], 2) < 0) /* stderr */
553 perror("dup2 stderr");
559 cray_init_job(s->pw); /* set up cray jid and tmpdir */
562 /* Do processing for the child (exec command etc). */
563 do_child(s, command);
570 signal(WJSIGNAL, cray_job_termination_handler);
573 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
577 /* Set interactive/non-interactive mode. */
578 packet_set_interactive(s->display != NULL,
579 options.ip_qos_interactive, options.ip_qos_bulk);
582 * Clear loginmsg, since it's the child's responsibility to display
583 * it to the user, otherwise multiple sessions may accumulate
584 * multiple copies of the login messages.
586 buffer_clear(&loginmsg);
589 /* We are the parent. Close the child sides of the pipes. */
595 session_set_fds(s, pin[1], pout[0], perr[0],
598 /* Enter the interactive session. */
599 server_loop(pid, pin[1], pout[0], perr[0]);
600 /* server_loop has closed pin[1], pout[0], and perr[0]. */
603 /* We are the parent. Close the child sides of the socket pairs. */
608 * Enter the interactive session. Note: server_loop must be able to
609 * handle the case that fdin and fdout are the same.
612 session_set_fds(s, inout[1], inout[1], err[1],
615 server_loop(pid, inout[1], inout[1], err[1]);
616 /* server_loop has closed inout[1] and err[1]. */
623 * This is called to fork and execute a command when we have a tty. This
624 * will call do_child from the child, and server_loop from the parent after
625 * setting up file descriptors, controlling tty, updating wtmp, utmp,
626 * lastlog, and other such operations.
629 do_exec_pty(Session *s, const char *command)
631 int fdout, ptyfd, ttyfd, ptymaster;
635 fatal("do_exec_pty: no session");
640 * Create another descriptor of the pty master side for use as the
641 * standard input. We could use the original descriptor, but this
642 * simplifies code in server_loop. The descriptor is bidirectional.
643 * Do this before forking (and cleanup in the child) so as to
644 * detect and gracefully fail out-of-fd conditions.
646 if ((fdout = dup(ptyfd)) < 0) {
647 error("%s: dup #1: %s", __func__, strerror(errno));
652 /* we keep a reference to the pty master */
653 if ((ptymaster = dup(ptyfd)) < 0) {
654 error("%s: dup #2: %s", __func__, strerror(errno));
661 /* Fork the child. */
662 switch ((pid = fork())) {
664 error("%s: fork: %.100s", __func__, strerror(errno));
676 /* Child. Reinitialize the log because the pid has changed. */
677 log_init(__progname, options.log_level,
678 options.log_facility, log_stderr);
679 /* Close the master side of the pseudo tty. */
682 /* Make the pseudo tty our controlling tty. */
683 pty_make_controlling_tty(&ttyfd, s->tty);
685 /* Redirect stdin/stdout/stderr from the pseudo tty. */
686 if (dup2(ttyfd, 0) < 0)
687 error("dup2 stdin: %s", strerror(errno));
688 if (dup2(ttyfd, 1) < 0)
689 error("dup2 stdout: %s", strerror(errno));
690 if (dup2(ttyfd, 2) < 0)
691 error("dup2 stderr: %s", strerror(errno));
693 /* Close the extra descriptor for the pseudo tty. */
696 /* record login, etc. similar to login(1) */
698 if (!(options.use_login && command == NULL)) {
700 cray_init_job(s->pw); /* set up cray jid and tmpdir */
702 do_login(s, command);
704 # ifdef LOGIN_NEEDS_UTMPX
710 * Do common processing for the child, such as execing
713 do_child(s, command);
720 signal(WJSIGNAL, cray_job_termination_handler);
723 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
728 /* Parent. Close the slave side of the pseudo tty. */
731 /* Enter interactive session. */
732 s->ptymaster = ptymaster;
733 packet_set_interactive(1,
734 options.ip_qos_interactive, options.ip_qos_bulk);
736 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
738 server_loop(pid, ptyfd, fdout, -1);
739 /* server_loop _has_ closed ptyfd and fdout. */
744 #ifdef LOGIN_NEEDS_UTMPX
746 do_pre_login(Session *s)
749 struct sockaddr_storage from;
750 pid_t pid = getpid();
753 * Get IP address of client. If the connection is not a socket, let
754 * the address be 0.0.0.0.
756 memset(&from, 0, sizeof(from));
757 fromlen = sizeof(from);
758 if (packet_connection_is_on_socket()) {
759 if (getpeername(packet_get_connection_in(),
760 (struct sockaddr *)&from, &fromlen) < 0) {
761 debug("getpeername: %.100s", strerror(errno));
766 record_utmp_only(pid, s->tty, s->pw->pw_name,
767 get_remote_name_or_ip(utmp_len, options.use_dns),
768 (struct sockaddr *)&from, fromlen);
773 * This is called to fork and execute a command. If another command is
774 * to be forced, execute that instead.
777 do_exec(Session *s, const char *command)
780 const char *forced = NULL;
781 char session_type[1024], *tty = NULL;
783 if (options.adm_forced_command) {
784 original_command = command;
785 command = options.adm_forced_command;
787 } else if (forced_command) {
788 original_command = command;
789 command = forced_command;
790 forced = "(key-option)";
792 if (forced != NULL) {
793 if (IS_INTERNAL_SFTP(command)) {
794 s->is_subsystem = s->is_subsystem ?
795 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
796 } else if (s->is_subsystem)
797 s->is_subsystem = SUBSYSTEM_EXT;
798 snprintf(session_type, sizeof(session_type),
799 "forced-command %s '%.900s'", forced, command);
800 } else if (s->is_subsystem) {
801 snprintf(session_type, sizeof(session_type),
802 "subsystem '%.900s'", s->subsys);
803 } else if (command == NULL) {
804 snprintf(session_type, sizeof(session_type), "shell");
806 /* NB. we don't log unforced commands to preserve privacy */
807 snprintf(session_type, sizeof(session_type), "command");
810 if (s->ttyfd != -1) {
812 if (strncmp(tty, "/dev/", 5) == 0)
816 verbose("Starting session: %s%s%s for %s from %.200s port %d",
818 tty == NULL ? "" : " on ",
819 tty == NULL ? "" : tty,
824 #ifdef SSH_AUDIT_EVENTS
826 PRIVSEP(audit_run_command(command));
827 else if (s->ttyfd == -1) {
828 char *shell = s->pw->pw_shell;
830 if (shell[0] == '\0') /* empty shell means /bin/sh */
832 PRIVSEP(audit_run_command(shell));
836 ret = do_exec_pty(s, command);
838 ret = do_exec_no_pty(s, command);
840 original_command = NULL;
843 * Clear loginmsg: it's the child's responsibility to display
844 * it to the user, otherwise multiple sessions may accumulate
845 * multiple copies of the login messages.
847 buffer_clear(&loginmsg);
852 /* administrative, login(1)-like work */
854 do_login(Session *s, const char *command)
857 struct sockaddr_storage from;
858 struct passwd * pw = s->pw;
859 pid_t pid = getpid();
862 * Get IP address of client. If the connection is not a socket, let
863 * the address be 0.0.0.0.
865 memset(&from, 0, sizeof(from));
866 fromlen = sizeof(from);
867 if (packet_connection_is_on_socket()) {
868 if (getpeername(packet_get_connection_in(),
869 (struct sockaddr *)&from, &fromlen) < 0) {
870 debug("getpeername: %.100s", strerror(errno));
875 /* Record that there was a login on that tty from the remote host. */
877 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
878 get_remote_name_or_ip(utmp_len,
880 (struct sockaddr *)&from, fromlen);
884 * If password change is needed, do it now.
885 * This needs to occur before the ~/.hushlogin check.
887 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
890 s->authctxt->force_pwchange = 0;
891 /* XXX - signal [net] parent to enable forwardings */
895 if (check_quietlogin(s, command))
904 * Display the message of the day.
912 if (options.print_motd) {
913 #ifdef HAVE_LOGIN_CAP
914 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
917 f = fopen("/etc/motd", "r");
920 while (fgets(buf, sizeof(buf), f))
929 * Check for quiet login, either .hushlogin or command given.
932 check_quietlogin(Session *s, const char *command)
935 struct passwd *pw = s->pw;
938 /* Return 1 if .hushlogin exists or a command given. */
941 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
942 #ifdef HAVE_LOGIN_CAP
943 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
946 if (stat(buf, &st) >= 0)
953 * Sets the value of the given variable in the environment. If the variable
954 * already exists, its value is overridden.
957 child_set_env(char ***envp, u_int *envsizep, const char *name,
964 if (strchr(name, '=') != NULL) {
965 error("Invalid environment variable \"%.100s\"", name);
970 * If we're passed an uninitialized list, allocate a single null
971 * entry before continuing.
973 if (*envp == NULL && *envsizep == 0) {
974 *envp = xmalloc(sizeof(char *));
980 * Find the slot where the value should be stored. If the variable
981 * already exists, we reuse the slot; otherwise we append a new slot
982 * at the end of the array, expanding if necessary.
985 namelen = strlen(name);
986 for (i = 0; env[i]; i++)
987 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
990 /* Reuse the slot. */
993 /* New variable. Expand if necessary. */
995 if (i >= envsize - 1) {
997 fatal("child_set_env: too many env vars");
999 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
1000 *envsizep = envsize;
1002 /* Need to set the NULL pointer at end of array beyond the new slot. */
1006 /* Allocate space and format the variable in the appropriate slot. */
1007 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1008 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1012 * Reads environment variables from the given file and adds/overrides them
1013 * into the environment. If the file does not exist, this does nothing.
1014 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1015 * and assignments of the form name=value. No other forms are allowed.
1018 read_environment_file(char ***env, u_int *envsize,
1019 const char *filename)
1026 f = fopen(filename, "r");
1030 while (fgets(buf, sizeof(buf), f)) {
1031 if (++lineno > 1000)
1032 fatal("Too many lines in environment file %s", filename);
1033 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1035 if (!*cp || *cp == '#' || *cp == '\n')
1038 cp[strcspn(cp, "\n")] = '\0';
1040 value = strchr(cp, '=');
1041 if (value == NULL) {
1042 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1047 * Replace the equals sign by nul, and advance value to
1052 child_set_env(env, envsize, cp, value);
1057 #ifdef HAVE_ETC_DEFAULT_LOGIN
1059 * Return named variable from specified environment, or NULL if not present.
1062 child_get_env(char **env, const char *name)
1068 for (i=0; env[i] != NULL; i++)
1069 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1070 return(env[i] + len + 1);
1075 * Read /etc/default/login.
1076 * We pick up the PATH (or SUPATH for root) and UMASK.
1079 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1081 char **tmpenv = NULL, *var;
1082 u_int i, tmpenvsize = 0;
1086 * We don't want to copy the whole file to the child's environment,
1087 * so we use a temporary environment and copy the variables we're
1090 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1096 var = child_get_env(tmpenv, "SUPATH");
1098 var = child_get_env(tmpenv, "PATH");
1100 child_set_env(env, envsize, "PATH", var);
1102 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1103 if (sscanf(var, "%5lo", &mask) == 1)
1104 umask((mode_t)mask);
1106 for (i = 0; tmpenv[i] != NULL; i++)
1110 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1113 copy_environment(char **source, char ***env, u_int *envsize)
1115 char *var_name, *var_val;
1121 for(i = 0; source[i] != NULL; i++) {
1122 var_name = xstrdup(source[i]);
1123 if ((var_val = strstr(var_name, "=")) == NULL) {
1129 debug3("Copy environment: %s=%s", var_name, var_val);
1130 child_set_env(env, envsize, var_name, var_val);
1137 do_setup_env(Session *s, const char *shell)
1142 struct passwd *pw = s->pw;
1143 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1147 /* Initialize the environment. */
1149 env = xcalloc(envsize, sizeof(char *));
1154 * The Windows environment contains some setting which are
1155 * important for a running system. They must not be dropped.
1160 p = fetch_windows_environment();
1161 copy_environment(p, &env, &envsize);
1162 free_windows_environment(p);
1167 /* Allow any GSSAPI methods that we've used to alter
1168 * the childs environment as they see fit
1170 ssh_gssapi_do_child(&env, &envsize);
1173 if (!options.use_login) {
1174 /* Set basic environment. */
1175 for (i = 0; i < s->num_env; i++)
1176 child_set_env(&env, &envsize, s->env[i].name,
1179 child_set_env(&env, &envsize, "USER", pw->pw_name);
1180 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1182 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1184 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1185 #ifdef HAVE_LOGIN_CAP
1186 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1187 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1189 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1190 #else /* HAVE_LOGIN_CAP */
1191 # ifndef HAVE_CYGWIN
1193 * There's no standard path on Windows. The path contains
1194 * important components pointing to the system directories,
1195 * needed for loading shared libraries. So the path better
1196 * remains intact here.
1198 # ifdef HAVE_ETC_DEFAULT_LOGIN
1199 read_etc_default_login(&env, &envsize, pw->pw_uid);
1200 path = child_get_env(env, "PATH");
1201 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1202 if (path == NULL || *path == '\0') {
1203 child_set_env(&env, &envsize, "PATH",
1204 s->pw->pw_uid == 0 ?
1205 SUPERUSER_PATH : _PATH_STDPATH);
1207 # endif /* HAVE_CYGWIN */
1208 #endif /* HAVE_LOGIN_CAP */
1210 snprintf(buf, sizeof buf, "%.200s/%.50s",
1211 _PATH_MAILDIR, pw->pw_name);
1212 child_set_env(&env, &envsize, "MAIL", buf);
1214 /* Normal systems set SHELL by default. */
1215 child_set_env(&env, &envsize, "SHELL", shell);
1218 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1220 /* Set custom environment options from RSA authentication. */
1221 if (!options.use_login) {
1222 while (custom_environment) {
1223 struct envstring *ce = custom_environment;
1226 for (i = 0; str[i] != '=' && str[i]; i++)
1228 if (str[i] == '=') {
1230 child_set_env(&env, &envsize, str, str + i + 1);
1232 custom_environment = ce->next;
1238 /* SSH_CLIENT deprecated */
1239 snprintf(buf, sizeof buf, "%.50s %d %d",
1240 get_remote_ipaddr(), get_remote_port(), get_local_port());
1241 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1243 laddr = get_local_ipaddr(packet_get_connection_in());
1244 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1245 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1247 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1250 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1252 child_set_env(&env, &envsize, "TERM", s->term);
1254 child_set_env(&env, &envsize, "DISPLAY", s->display);
1255 if (original_command)
1256 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1260 if (cray_tmpdir[0] != '\0')
1261 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1262 #endif /* _UNICOS */
1265 * Since we clear KRB5CCNAME at startup, if it's set now then it
1266 * must have been set by a native authentication method (eg AIX or
1267 * SIA), so copy it to the child.
1272 if ((cp = getenv("KRB5CCNAME")) != NULL)
1273 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1280 if ((cp = getenv("AUTHSTATE")) != NULL)
1281 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1282 read_environment_file(&env, &envsize, "/etc/environment");
1286 if (s->authctxt->krb5_ccname)
1287 child_set_env(&env, &envsize, "KRB5CCNAME",
1288 s->authctxt->krb5_ccname);
1292 * Pull in any environment variables that may have
1295 if (options.use_pam) {
1298 p = fetch_pam_child_environment();
1299 copy_environment(p, &env, &envsize);
1300 free_pam_environment(p);
1302 p = fetch_pam_environment();
1303 copy_environment(p, &env, &envsize);
1304 free_pam_environment(p);
1306 #endif /* USE_PAM */
1308 if (auth_sock_name != NULL)
1309 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1312 /* read $HOME/.ssh/environment. */
1313 if (options.permit_user_env && !options.use_login) {
1314 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1315 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1316 read_environment_file(&env, &envsize, buf);
1319 /* dump the environment */
1320 fprintf(stderr, "Environment:\n");
1321 for (i = 0; env[i]; i++)
1322 fprintf(stderr, " %.200s\n", env[i]);
1328 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1329 * first in this order).
1332 do_rc_files(Session *s, const char *shell)
1340 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1342 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1343 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1344 !no_user_rc && options.permit_user_rc &&
1345 stat(_PATH_SSH_USER_RC, &st) >= 0) {
1346 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1347 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1349 fprintf(stderr, "Running %s\n", cmd);
1350 f = popen(cmd, "w");
1353 fprintf(f, "%s %s\n", s->auth_proto,
1357 fprintf(stderr, "Could not run %s\n",
1359 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1361 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1362 _PATH_SSH_SYSTEM_RC);
1363 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1366 fprintf(f, "%s %s\n", s->auth_proto,
1370 fprintf(stderr, "Could not run %s\n",
1371 _PATH_SSH_SYSTEM_RC);
1372 } else if (do_xauth && options.xauth_location != NULL) {
1373 /* Add authority data to .Xauthority if appropriate. */
1376 "Running %.500s remove %.100s\n",
1377 options.xauth_location, s->auth_display);
1379 "%.500s add %.100s %.100s %.100s\n",
1380 options.xauth_location, s->auth_display,
1381 s->auth_proto, s->auth_data);
1383 snprintf(cmd, sizeof cmd, "%s -q -",
1384 options.xauth_location);
1385 f = popen(cmd, "w");
1387 fprintf(f, "remove %s\n",
1389 fprintf(f, "add %s %s %s\n",
1390 s->auth_display, s->auth_proto,
1394 fprintf(stderr, "Could not run %s\n",
1401 do_nologin(struct passwd *pw)
1404 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1407 #ifdef HAVE_LOGIN_CAP
1408 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1410 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1412 if (pw->pw_uid == 0)
1416 if (stat(nl, &sb) == -1) {
1422 /* /etc/nologin exists. Print its contents if we can and exit. */
1423 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1424 if ((f = fopen(nl, "r")) != NULL) {
1425 while (fgets(buf, sizeof(buf), f))
1433 * Chroot into a directory after checking it for safety: all path components
1434 * must be root-owned directories with strict permissions.
1437 safely_chroot(const char *path, uid_t uid)
1440 char component[MAXPATHLEN];
1444 fatal("chroot path does not begin at root");
1445 if (strlen(path) >= sizeof(component))
1446 fatal("chroot path too long");
1449 * Descend the path, checking that each component is a
1450 * root-owned directory with strict permissions.
1452 for (cp = path; cp != NULL;) {
1453 if ((cp = strchr(cp, '/')) == NULL)
1454 strlcpy(component, path, sizeof(component));
1457 memcpy(component, path, cp - path);
1458 component[cp - path] = '\0';
1461 debug3("%s: checking '%s'", __func__, component);
1463 if (stat(component, &st) != 0)
1464 fatal("%s: stat(\"%s\"): %s", __func__,
1465 component, strerror(errno));
1466 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1467 fatal("bad ownership or modes for chroot "
1468 "directory %s\"%s\"",
1469 cp == NULL ? "" : "component ", component);
1470 if (!S_ISDIR(st.st_mode))
1471 fatal("chroot path %s\"%s\" is not a directory",
1472 cp == NULL ? "" : "component ", component);
1476 if (chdir(path) == -1)
1477 fatal("Unable to chdir to chroot path \"%s\": "
1478 "%s", path, strerror(errno));
1479 if (chroot(path) == -1)
1480 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1481 if (chdir("/") == -1)
1482 fatal("%s: chdir(/) after chroot: %s",
1483 __func__, strerror(errno));
1484 verbose("Changed root directory to \"%s\"", path);
1487 /* Set login name, uid, gid, and groups. */
1489 do_setusercontext(struct passwd *pw)
1491 char *chroot_path, *tmp;
1493 int doing_chroot = 0;
1496 platform_setusercontext(pw);
1498 if (platform_privileged_uidswap()) {
1499 #ifdef HAVE_LOGIN_CAP
1500 if (setusercontext(lc, pw, pw->pw_uid,
1501 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1502 perror("unable to set user context");
1506 if (setlogin(pw->pw_name) < 0)
1507 error("setlogin failed: %s", strerror(errno));
1508 if (setgid(pw->pw_gid) < 0) {
1512 /* Initialize the group list. */
1513 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1514 perror("initgroups");
1520 platform_setusercontext_post_groups(pw);
1522 if (options.chroot_directory != NULL &&
1523 strcasecmp(options.chroot_directory, "none") != 0) {
1524 tmp = tilde_expand_filename(options.chroot_directory,
1526 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1527 "u", pw->pw_name, (char *)NULL);
1528 safely_chroot(chroot_path, pw->pw_uid);
1531 /* Make sure we don't attempt to chroot again */
1532 free(options.chroot_directory);
1533 options.chroot_directory = NULL;
1539 #ifdef HAVE_LOGIN_CAP
1540 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1541 perror("unable to set user context (setuser)");
1545 * FreeBSD's setusercontext() will not apply the user's
1546 * own umask setting unless running with the user's UID.
1548 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1551 /* In a chroot environment, the set_id() will always fail; typically
1552 * because of the lack of necessary authentication services and runtime
1553 * such as ./usr/lib/libiaf.so, ./usr/lib/libpam.so.1, and ./etc/passwd
1554 * We skip it in the internal sftp chroot case.
1555 * We'll lose auditing and ACLs but permanently_set_uid will
1556 * take care of the rest.
1558 if ((doing_chroot == 0) && set_id(pw->pw_name) != 0) {
1559 fatal("set_id(%s) Failed", pw->pw_name);
1561 # endif /* USE_LIBIAF */
1562 /* Permanently switch to the desired uid. */
1563 permanently_set_uid(pw);
1565 } else if (options.chroot_directory != NULL &&
1566 strcasecmp(options.chroot_directory, "none") != 0) {
1567 fatal("server lacks privileges to chroot to ChrootDirectory");
1570 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1571 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1575 do_pwchange(Session *s)
1578 fprintf(stderr, "WARNING: Your password has expired.\n");
1579 if (s->ttyfd != -1) {
1581 "You must change your password now and login again!\n");
1585 #ifdef PASSWD_NEEDS_USERNAME
1586 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1589 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1594 "Password change required but no TTY available.\n");
1600 launch_login(struct passwd *pw, const char *hostname)
1602 /* Launch login(1). */
1604 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1605 #ifdef xxxLOGIN_NEEDS_TERM
1606 (s->term ? s->term : "unknown"),
1607 #endif /* LOGIN_NEEDS_TERM */
1608 #ifdef LOGIN_NO_ENDOPT
1609 "-p", "-f", pw->pw_name, (char *)NULL);
1611 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1614 /* Login couldn't be executed, die. */
1621 child_close_fds(void)
1623 extern AuthenticationConnection *auth_conn;
1626 ssh_close_authentication_connection(auth_conn);
1630 if (packet_get_connection_in() == packet_get_connection_out())
1631 close(packet_get_connection_in());
1633 close(packet_get_connection_in());
1634 close(packet_get_connection_out());
1637 * Close all descriptors related to channels. They will still remain
1638 * open in the parent.
1640 /* XXX better use close-on-exec? -markus */
1641 channel_close_all();
1644 * Close any extra file descriptors. Note that there may still be
1645 * descriptors left by system functions. They will be closed later.
1650 * Close any extra open file descriptors so that we don't have them
1651 * hanging around in clients. Note that we want to do this after
1652 * initgroups, because at least on Solaris 2.3 it leaves file
1655 closefrom(STDERR_FILENO + 1);
1659 * Performs common processing for the child, such as setting up the
1660 * environment, closing extra file descriptors, setting the user and group
1661 * ids, and executing the command or shell.
1665 do_child(Session *s, const char *command)
1667 extern char **environ;
1669 char *argv[ARGV_MAX];
1670 const char *shell, *shell0, *hostname = NULL;
1671 struct passwd *pw = s->pw;
1674 /* remove hostkey from the child's memory */
1675 destroy_sensitive_data();
1677 /* Force a password change */
1678 if (s->authctxt->force_pwchange) {
1679 do_setusercontext(pw);
1685 /* login(1) is only called if we execute the login shell */
1686 if (options.use_login && command != NULL)
1687 options.use_login = 0;
1690 cray_setup(pw->pw_uid, pw->pw_name, command);
1691 #endif /* _UNICOS */
1694 * Login(1) does this as well, and it needs uid 0 for the "-h"
1695 * switch, so we let login(1) to this for us.
1697 if (!options.use_login) {
1699 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1700 if (!check_quietlogin(s, command))
1702 #else /* HAVE_OSF_SIA */
1703 /* When PAM is enabled we rely on it to do the nologin check */
1704 if (!options.use_pam)
1706 do_setusercontext(pw);
1708 * PAM session modules in do_setusercontext may have
1709 * generated messages, so if this in an interactive
1710 * login then display them too.
1712 if (!check_quietlogin(s, command))
1714 #endif /* HAVE_OSF_SIA */
1718 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1719 debug3("PAM session not opened, exiting");
1726 * Get the shell from the password data. An empty shell field is
1727 * legal, and means /bin/sh.
1729 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1732 * Make sure $SHELL points to the shell from the password file,
1733 * even if shell is overridden from login.conf
1735 env = do_setup_env(s, shell);
1737 #ifdef HAVE_LOGIN_CAP
1738 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1741 /* we have to stash the hostname before we close our socket. */
1742 if (options.use_login)
1743 hostname = get_remote_name_or_ip(utmp_len,
1746 * Close the connection descriptors; note that this is the child, and
1747 * the server will still have the socket open, and it is important
1748 * that we do not shutdown it. Note that the descriptors cannot be
1749 * closed before building the environment, as we call
1750 * get_remote_ipaddr there.
1755 * Must take new environment into use so that .ssh/rc,
1756 * /etc/ssh/sshrc and xauth are run in the proper environment.
1760 #if defined(KRB5) && defined(USE_AFS)
1762 * At this point, we check to see if AFS is active and if we have
1763 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1764 * if we can (and need to) extend the ticket into an AFS token. If
1765 * we don't do this, we run into potential problems if the user's
1766 * home directory is in AFS and it's not world-readable.
1769 if (options.kerberos_get_afs_token && k_hasafs() &&
1770 (s->authctxt->krb5_ctx != NULL)) {
1773 debug("Getting AFS token");
1777 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1778 krb5_afslog(s->authctxt->krb5_ctx,
1779 s->authctxt->krb5_fwd_ccache, cell, NULL);
1781 krb5_afslog_home(s->authctxt->krb5_ctx,
1782 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1786 /* Change current directory to the user's home directory. */
1787 if (chdir(pw->pw_dir) < 0) {
1788 /* Suppress missing homedir warning for chroot case */
1789 #ifdef HAVE_LOGIN_CAP
1790 r = login_getcapbool(lc, "requirehome", 0);
1792 if (r || options.chroot_directory == NULL ||
1793 strcasecmp(options.chroot_directory, "none") == 0)
1794 fprintf(stderr, "Could not chdir to home "
1795 "directory %s: %s\n", pw->pw_dir,
1801 closefrom(STDERR_FILENO + 1);
1803 if (!options.use_login)
1804 do_rc_files(s, shell);
1806 /* restore SIGPIPE for child */
1807 signal(SIGPIPE, SIG_DFL);
1809 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1810 printf("This service allows sftp connections only.\n");
1813 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1814 extern int optind, optreset;
1818 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1819 args = xstrdup(command ? command : "sftp-server");
1820 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1821 if (i < ARGV_MAX - 1)
1824 optind = optreset = 1;
1825 __progname = argv[0];
1827 ssh_selinux_change_context("sftpd_t");
1829 exit(sftp_server_main(i, argv, s->pw));
1834 if (options.use_login) {
1835 launch_login(pw, hostname);
1839 /* Get the last component of the shell name. */
1840 if ((shell0 = strrchr(shell, '/')) != NULL)
1846 * If we have no command, execute the shell. In this case, the shell
1847 * name to be passed in argv[0] is preceded by '-' to indicate that
1848 * this is a login shell.
1853 /* Start the shell. Set initial character to '-'. */
1856 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1857 >= sizeof(argv0) - 1) {
1863 /* Execute the shell. */
1866 execve(shell, argv, env);
1868 /* Executing the shell failed. */
1873 * Execute the command using the user's shell. This uses the -c
1874 * option to execute the command.
1876 argv[0] = (char *) shell0;
1878 argv[2] = (char *) command;
1880 execve(shell, argv, env);
1886 session_unused(int id)
1888 debug3("%s: session id %d unused", __func__, id);
1889 if (id >= options.max_sessions ||
1890 id >= sessions_nalloc) {
1891 fatal("%s: insane session id %d (max %d nalloc %d)",
1892 __func__, id, options.max_sessions, sessions_nalloc);
1894 memset(&sessions[id], 0, sizeof(*sessions));
1895 sessions[id].self = id;
1896 sessions[id].used = 0;
1897 sessions[id].chanid = -1;
1898 sessions[id].ptyfd = -1;
1899 sessions[id].ttyfd = -1;
1900 sessions[id].ptymaster = -1;
1901 sessions[id].x11_chanids = NULL;
1902 sessions[id].next_unused = sessions_first_unused;
1903 sessions_first_unused = id;
1911 if (sessions_first_unused == -1) {
1912 if (sessions_nalloc >= options.max_sessions)
1914 debug2("%s: allocate (allocated %d max %d)",
1915 __func__, sessions_nalloc, options.max_sessions);
1916 tmp = xrealloc(sessions, sessions_nalloc + 1,
1919 error("%s: cannot allocate %d sessions",
1920 __func__, sessions_nalloc + 1);
1924 session_unused(sessions_nalloc++);
1927 if (sessions_first_unused >= sessions_nalloc ||
1928 sessions_first_unused < 0) {
1929 fatal("%s: insane first_unused %d max %d nalloc %d",
1930 __func__, sessions_first_unused, options.max_sessions,
1934 s = &sessions[sessions_first_unused];
1936 fatal("%s: session %d already used",
1937 __func__, sessions_first_unused);
1939 sessions_first_unused = s->next_unused;
1941 s->next_unused = -1;
1942 debug("session_new: session %d", s->self);
1951 for (i = 0; i < sessions_nalloc; i++) {
1952 Session *s = &sessions[i];
1954 debug("dump: used %d next_unused %d session %d %p "
1955 "channel %d pid %ld",
1966 session_open(Authctxt *authctxt, int chanid)
1968 Session *s = session_new();
1969 debug("session_open: channel %d", chanid);
1971 error("no more sessions");
1974 s->authctxt = authctxt;
1975 s->pw = authctxt->pw;
1976 if (s->pw == NULL || !authctxt->valid)
1977 fatal("no user for session %d", s->self);
1978 debug("session_open: session %d: link with channel %d", s->self, chanid);
1984 session_by_tty(char *tty)
1987 for (i = 0; i < sessions_nalloc; i++) {
1988 Session *s = &sessions[i];
1989 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1990 debug("session_by_tty: session %d tty %s", i, tty);
1994 debug("session_by_tty: unknown tty %.100s", tty);
2000 session_by_channel(int id)
2003 for (i = 0; i < sessions_nalloc; i++) {
2004 Session *s = &sessions[i];
2005 if (s->used && s->chanid == id) {
2006 debug("session_by_channel: session %d channel %d",
2011 debug("session_by_channel: unknown channel %d", id);
2017 session_by_x11_channel(int id)
2021 for (i = 0; i < sessions_nalloc; i++) {
2022 Session *s = &sessions[i];
2024 if (s->x11_chanids == NULL || !s->used)
2026 for (j = 0; s->x11_chanids[j] != -1; j++) {
2027 if (s->x11_chanids[j] == id) {
2028 debug("session_by_x11_channel: session %d "
2029 "channel %d", s->self, id);
2034 debug("session_by_x11_channel: unknown channel %d", id);
2040 session_by_pid(pid_t pid)
2043 debug("session_by_pid: pid %ld", (long)pid);
2044 for (i = 0; i < sessions_nalloc; i++) {
2045 Session *s = &sessions[i];
2046 if (s->used && s->pid == pid)
2049 error("session_by_pid: unknown pid %ld", (long)pid);
2055 session_window_change_req(Session *s)
2057 s->col = packet_get_int();
2058 s->row = packet_get_int();
2059 s->xpixel = packet_get_int();
2060 s->ypixel = packet_get_int();
2062 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2067 session_pty_req(Session *s)
2072 if (no_pty_flag || !options.permit_tty) {
2073 debug("Allocating a pty not permitted for this authentication.");
2076 if (s->ttyfd != -1) {
2077 packet_disconnect("Protocol error: you already have a pty.");
2081 s->term = packet_get_string(&len);
2084 s->col = packet_get_int();
2085 s->row = packet_get_int();
2087 s->row = packet_get_int();
2088 s->col = packet_get_int();
2090 s->xpixel = packet_get_int();
2091 s->ypixel = packet_get_int();
2093 if (strcmp(s->term, "") == 0) {
2098 /* Allocate a pty and open it. */
2099 debug("Allocating pty.");
2100 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
2106 error("session_pty_req: session %d alloc failed", s->self);
2109 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2111 /* for SSH1 the tty modes length is not given */
2113 n_bytes = packet_remaining();
2114 tty_parse_modes(s->ttyfd, &n_bytes);
2117 pty_setowner(s->pw, s->tty);
2119 /* Set window size from the packet. */
2120 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2123 session_proctitle(s);
2128 session_subsystem_req(Session *s)
2136 s->subsys = packet_get_string(&len);
2138 debug2("subsystem request for %.100s by user %s", s->subsys,
2141 for (i = 0; i < options.num_subsystems; i++) {
2142 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
2143 prog = options.subsystem_command[i];
2144 cmd = options.subsystem_args[i];
2145 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2146 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2147 debug("subsystem: %s", prog);
2149 if (stat(prog, &st) < 0)
2150 debug("subsystem: cannot stat %s: %s",
2151 prog, strerror(errno));
2152 s->is_subsystem = SUBSYSTEM_EXT;
2153 debug("subsystem: exec() %s", cmd);
2155 success = do_exec(s, cmd) == 0;
2161 logit("subsystem request for %.100s by user %s failed, "
2162 "subsystem not found", s->subsys, s->pw->pw_name);
2168 session_x11_req(Session *s)
2172 if (s->auth_proto != NULL || s->auth_data != NULL) {
2173 error("session_x11_req: session %d: "
2174 "x11 forwarding already active", s->self);
2177 s->single_connection = packet_get_char();
2178 s->auth_proto = packet_get_string(NULL);
2179 s->auth_data = packet_get_string(NULL);
2180 s->screen = packet_get_int();
2183 success = session_setup_x11fwd(s);
2185 free(s->auth_proto);
2187 s->auth_proto = NULL;
2188 s->auth_data = NULL;
2194 session_shell_req(Session *s)
2197 return do_exec(s, NULL) == 0;
2201 session_exec_req(Session *s)
2205 char *command = packet_get_string(&len);
2207 success = do_exec(s, command) == 0;
2213 session_break_req(Session *s)
2216 packet_get_int(); /* ignored */
2219 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2225 session_env_req(Session *s)
2228 u_int name_len, val_len, i;
2230 name = packet_get_cstring(&name_len);
2231 val = packet_get_cstring(&val_len);
2234 /* Don't set too many environment variables */
2235 if (s->num_env > 128) {
2236 debug2("Ignoring env request %s: too many env vars", name);
2240 for (i = 0; i < options.num_accept_env; i++) {
2241 if (match_pattern(name, options.accept_env[i])) {
2242 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2243 s->env = xrealloc(s->env, s->num_env + 1,
2245 s->env[s->num_env].name = name;
2246 s->env[s->num_env].val = val;
2251 debug2("Ignoring env request %s: disallowed name", name);
2260 session_auth_agent_req(Session *s)
2262 static int called = 0;
2264 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2265 debug("session_auth_agent_req: no_agent_forwarding_flag");
2272 return auth_input_request_forwarding(s->pw);
2277 session_input_channel_req(Channel *c, const char *rtype)
2282 if ((s = session_by_channel(c->self)) == NULL) {
2283 logit("session_input_channel_req: no session %d req %.100s",
2287 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2290 * a session is in LARVAL state until a shell, a command
2291 * or a subsystem is executed
2293 if (c->type == SSH_CHANNEL_LARVAL) {
2294 if (strcmp(rtype, "shell") == 0) {
2295 success = session_shell_req(s);
2296 } else if (strcmp(rtype, "exec") == 0) {
2297 success = session_exec_req(s);
2298 } else if (strcmp(rtype, "pty-req") == 0) {
2299 success = session_pty_req(s);
2300 } else if (strcmp(rtype, "x11-req") == 0) {
2301 success = session_x11_req(s);
2302 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2303 success = session_auth_agent_req(s);
2304 } else if (strcmp(rtype, "subsystem") == 0) {
2305 success = session_subsystem_req(s);
2306 } else if (strcmp(rtype, "env") == 0) {
2307 success = session_env_req(s);
2310 if (strcmp(rtype, "window-change") == 0) {
2311 success = session_window_change_req(s);
2312 } else if (strcmp(rtype, "break") == 0) {
2313 success = session_break_req(s);
2320 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2324 fatal("session_set_fds: called for proto != 2.0");
2326 * now that have a child and a pipe to the child,
2327 * we can activate our channel and register the fd's
2329 if (s->chanid == -1)
2330 fatal("no channel for session %d", s->self);
2331 channel_set_fds(s->chanid,
2333 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2334 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2338 * Function to perform pty cleanup. Also called if we get aborted abnormally
2339 * (e.g., due to a dropped connection).
2342 session_pty_cleanup2(Session *s)
2345 error("session_pty_cleanup: no session");
2351 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2353 /* Record that the user has logged out. */
2355 record_logout(s->pid, s->tty, s->pw->pw_name);
2357 /* Release the pseudo-tty. */
2359 pty_release(s->tty);
2362 * Close the server side of the socket pairs. We must do this after
2363 * the pty cleanup, so that another process doesn't get this pty
2364 * while we're still cleaning up.
2366 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2367 error("close(s->ptymaster/%d): %s",
2368 s->ptymaster, strerror(errno));
2370 /* unlink pty from session */
2375 session_pty_cleanup(Session *s)
2377 PRIVSEP(session_pty_cleanup2(s));
2383 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2398 return "SIG@openssh.com";
2402 session_close_x11(int id)
2406 if ((c = channel_by_id(id)) == NULL) {
2407 debug("session_close_x11: x11 channel %d missing", id);
2409 /* Detach X11 listener */
2410 debug("session_close_x11: detach x11 channel %d", id);
2411 channel_cancel_cleanup(id);
2412 if (c->ostate != CHAN_OUTPUT_CLOSED)
2418 session_close_single_x11(int id, void *arg)
2423 debug3("session_close_single_x11: channel %d", id);
2424 channel_cancel_cleanup(id);
2425 if ((s = session_by_x11_channel(id)) == NULL)
2426 fatal("session_close_single_x11: no x11 channel %d", id);
2427 for (i = 0; s->x11_chanids[i] != -1; i++) {
2428 debug("session_close_single_x11: session %d: "
2429 "closing channel %d", s->self, s->x11_chanids[i]);
2431 * The channel "id" is already closing, but make sure we
2432 * close all of its siblings.
2434 if (s->x11_chanids[i] != id)
2435 session_close_x11(s->x11_chanids[i]);
2437 free(s->x11_chanids);
2438 s->x11_chanids = NULL;
2441 free(s->auth_proto);
2442 s->auth_proto = NULL;
2444 s->auth_data = NULL;
2445 free(s->auth_display);
2446 s->auth_display = NULL;
2450 session_exit_message(Session *s, int status)
2454 if ((c = channel_lookup(s->chanid)) == NULL)
2455 fatal("session_exit_message: session %d: no channel %d",
2456 s->self, s->chanid);
2457 debug("session_exit_message: session %d channel %d pid %ld",
2458 s->self, s->chanid, (long)s->pid);
2460 if (WIFEXITED(status)) {
2461 channel_request_start(s->chanid, "exit-status", 0);
2462 packet_put_int(WEXITSTATUS(status));
2464 } else if (WIFSIGNALED(status)) {
2465 channel_request_start(s->chanid, "exit-signal", 0);
2466 packet_put_cstring(sig2name(WTERMSIG(status)));
2468 packet_put_char(WCOREDUMP(status)? 1 : 0);
2469 #else /* WCOREDUMP */
2471 #endif /* WCOREDUMP */
2472 packet_put_cstring("");
2473 packet_put_cstring("");
2476 /* Some weird exit cause. Just exit. */
2477 packet_disconnect("wait returned status %04x.", status);
2480 /* disconnect channel */
2481 debug("session_exit_message: release channel %d", s->chanid);
2484 * Adjust cleanup callback attachment to send close messages when
2485 * the channel gets EOF. The session will be then be closed
2486 * by session_close_by_channel when the childs close their fds.
2488 channel_register_cleanup(c->self, session_close_by_channel, 1);
2491 * emulate a write failure with 'chan_write_failed', nobody will be
2492 * interested in data we write.
2493 * Note that we must not call 'chan_read_failed', since there could
2494 * be some more data waiting in the pipe.
2496 if (c->ostate != CHAN_OUTPUT_CLOSED)
2497 chan_write_failed(c);
2501 session_close(Session *s)
2505 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2507 session_pty_cleanup(s);
2510 free(s->x11_chanids);
2511 free(s->auth_display);
2513 free(s->auth_proto);
2515 if (s->env != NULL) {
2516 for (i = 0; i < s->num_env; i++) {
2517 free(s->env[i].name);
2518 free(s->env[i].val);
2522 session_proctitle(s);
2523 session_unused(s->self);
2527 session_close_by_pid(pid_t pid, int status)
2529 Session *s = session_by_pid(pid);
2531 debug("session_close_by_pid: no session for pid %ld",
2535 if (s->chanid != -1)
2536 session_exit_message(s, status);
2538 session_pty_cleanup(s);
2543 * this is called when a channel dies before
2544 * the session 'child' itself dies
2547 session_close_by_channel(int id, void *arg)
2549 Session *s = session_by_channel(id);
2553 debug("session_close_by_channel: no session for id %d", id);
2556 debug("session_close_by_channel: channel %d child %ld",
2559 debug("session_close_by_channel: channel %d: has child", id);
2561 * delay detach of session, but release pty, since
2562 * the fd's to the child are already closed
2565 session_pty_cleanup(s);
2568 /* detach by removing callback */
2569 channel_cancel_cleanup(s->chanid);
2571 /* Close any X11 listeners associated with this session */
2572 if (s->x11_chanids != NULL) {
2573 for (i = 0; s->x11_chanids[i] != -1; i++) {
2574 session_close_x11(s->x11_chanids[i]);
2575 s->x11_chanids[i] = -1;
2584 session_destroy_all(void (*closefunc)(Session *))
2587 for (i = 0; i < sessions_nalloc; i++) {
2588 Session *s = &sessions[i];
2590 if (closefunc != NULL)
2599 session_tty_list(void)
2601 static char buf[1024];
2606 for (i = 0; i < sessions_nalloc; i++) {
2607 Session *s = &sessions[i];
2608 if (s->used && s->ttyfd != -1) {
2610 if (strncmp(s->tty, "/dev/", 5) != 0) {
2611 cp = strrchr(s->tty, '/');
2612 cp = (cp == NULL) ? s->tty : cp + 1;
2617 strlcat(buf, ",", sizeof buf);
2618 strlcat(buf, cp, sizeof buf);
2622 strlcpy(buf, "notty", sizeof buf);
2627 session_proctitle(Session *s)
2630 error("no user for session %d", s->self);
2632 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2636 session_setup_x11fwd(Session *s)
2639 char display[512], auth_display[512];
2640 char hostname[NI_MAXHOST];
2643 if (no_x11_forwarding_flag) {
2644 packet_send_debug("X11 forwarding disabled in user configuration file.");
2647 if (!options.x11_forwarding) {
2648 debug("X11 forwarding disabled in server configuration file.");
2651 if (!options.xauth_location ||
2652 (stat(options.xauth_location, &st) == -1)) {
2653 packet_send_debug("No xauth program; cannot forward with spoofing.");
2656 if (options.use_login) {
2657 packet_send_debug("X11 forwarding disabled; "
2658 "not compatible with UseLogin=yes.");
2661 if (s->display != NULL) {
2662 debug("X11 display already set.");
2665 if (x11_create_display_inet(options.x11_display_offset,
2666 options.x11_use_localhost, s->single_connection,
2667 &s->display_number, &s->x11_chanids) == -1) {
2668 debug("x11_create_display_inet failed.");
2671 for (i = 0; s->x11_chanids[i] != -1; i++) {
2672 channel_register_cleanup(s->x11_chanids[i],
2673 session_close_single_x11, 0);
2676 /* Set up a suitable value for the DISPLAY variable. */
2677 if (gethostname(hostname, sizeof(hostname)) < 0)
2678 fatal("gethostname: %.100s", strerror(errno));
2680 * auth_display must be used as the displayname when the
2681 * authorization entry is added with xauth(1). This will be
2682 * different than the DISPLAY string for localhost displays.
2684 if (options.x11_use_localhost) {
2685 snprintf(display, sizeof display, "localhost:%u.%u",
2686 s->display_number, s->screen);
2687 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2688 s->display_number, s->screen);
2689 s->display = xstrdup(display);
2690 s->auth_display = xstrdup(auth_display);
2692 #ifdef IPADDR_IN_DISPLAY
2694 struct in_addr my_addr;
2696 he = gethostbyname(hostname);
2698 error("Can't get IP address for X11 DISPLAY.");
2699 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2702 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2703 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2704 s->display_number, s->screen);
2706 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2707 s->display_number, s->screen);
2709 s->display = xstrdup(display);
2710 s->auth_display = xstrdup(display);
2717 do_authenticated2(Authctxt *authctxt)
2719 server_loop2(authctxt);
2723 do_cleanup(Authctxt *authctxt)
2725 static int called = 0;
2727 debug("do_cleanup");
2729 /* no cleanup if we're in the child for login shell */
2733 /* avoid double cleanup */
2738 if (authctxt == NULL)
2742 if (options.use_pam) {
2744 sshpam_thread_cleanup();
2748 if (!authctxt->authenticated)
2752 if (options.kerberos_ticket_cleanup &&
2754 krb5_cleanup_proc(authctxt);
2758 if (compat20 && options.gss_cleanup_creds)
2759 ssh_gssapi_cleanup_creds();
2762 /* remove agent socket */
2763 auth_sock_cleanup_proc(authctxt->pw);
2766 * Cleanup ptys/utmp only if privsep is disabled,
2767 * or if running in monitor.
2769 if (!use_privsep || mm_is_monitor())
2770 session_destroy_all(session_pty_cleanup2);