1 /* $OpenBSD: session.c,v 1.256 2010/06/25 07:20:04 djm Exp $ */
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
12 * SSH2 support by Markus Friedl.
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
43 #include <sys/socket.h>
47 #include <arpa/inet.h>
63 #include "openbsd-compat/sys-queue.h"
82 #include "auth-options.h"
83 #include "pathnames.h"
87 #include "serverloop.h"
92 #include "monitor_wrap.h"
95 #if defined(KRB5) && defined(USE_AFS)
99 #define IS_INTERNAL_SFTP(c) \
100 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
101 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
102 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
103 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
107 Session *session_new(void);
108 void session_set_fds(Session *, int, int, int, int, int);
109 void session_pty_cleanup(Session *);
110 void session_proctitle(Session *);
111 int session_setup_x11fwd(Session *);
112 int do_exec_pty(Session *, const char *);
113 int do_exec_no_pty(Session *, const char *);
114 int do_exec(Session *, const char *);
115 void do_login(Session *, const char *);
116 #ifdef LOGIN_NEEDS_UTMPX
117 static void do_pre_login(Session *s);
119 void do_child(Session *, const char *);
121 int check_quietlogin(Session *, const char *);
123 static void do_authenticated1(Authctxt *);
124 static void do_authenticated2(Authctxt *);
126 static int session_pty_req(Session *);
129 extern ServerOptions options;
130 extern char *__progname;
131 extern int log_stderr;
132 extern int debug_flag;
133 extern u_int utmp_len;
134 extern int startup_pipe;
135 extern void destroy_sensitive_data(void);
136 extern Buffer loginmsg;
138 /* original command from peer. */
139 const char *original_command = NULL;
142 static int sessions_first_unused = -1;
143 static int sessions_nalloc = 0;
144 static Session *sessions = NULL;
146 #define SUBSYSTEM_NONE 0
147 #define SUBSYSTEM_EXT 1
148 #define SUBSYSTEM_INT_SFTP 2
149 #define SUBSYSTEM_INT_SFTP_ERROR 3
151 #ifdef HAVE_LOGIN_CAP
155 static int is_child = 0;
157 /* Name and directory of socket for authentication agent forwarding. */
158 static char *auth_sock_name = NULL;
159 static char *auth_sock_dir = NULL;
161 /* removes the agent forwarding socket */
164 auth_sock_cleanup_proc(struct passwd *pw)
166 if (auth_sock_name != NULL) {
167 temporarily_use_uid(pw);
168 unlink(auth_sock_name);
169 rmdir(auth_sock_dir);
170 auth_sock_name = NULL;
176 auth_input_request_forwarding(struct passwd * pw)
180 struct sockaddr_un sunaddr;
182 if (auth_sock_name != NULL) {
183 error("authentication forwarding requested twice.");
187 /* Temporarily drop privileged uid for mkdir/bind. */
188 temporarily_use_uid(pw);
190 /* Allocate a buffer for the socket name, and format the name. */
191 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
193 /* Create private directory for socket */
194 if (mkdtemp(auth_sock_dir) == NULL) {
195 packet_send_debug("Agent forwarding disabled: "
196 "mkdtemp() failed: %.100s", strerror(errno));
198 xfree(auth_sock_dir);
199 auth_sock_dir = NULL;
203 xasprintf(&auth_sock_name, "%s/agent.%ld",
204 auth_sock_dir, (long) getpid());
206 /* Create the socket. */
207 sock = socket(AF_UNIX, SOCK_STREAM, 0);
209 error("socket: %.100s", strerror(errno));
214 /* Bind it to the name. */
215 memset(&sunaddr, 0, sizeof(sunaddr));
216 sunaddr.sun_family = AF_UNIX;
217 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
219 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
220 error("bind: %.100s", strerror(errno));
225 /* Restore the privileged uid. */
228 /* Start listening on the socket. */
229 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
230 error("listen: %.100s", strerror(errno));
234 /* Allocate a channel for the authentication agent socket. */
235 /* this shouldn't matter if its hpn or not - cjr */
236 nc = channel_new("auth socket",
237 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
238 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
239 0, "auth socket", 1);
240 nc->path = xstrdup(auth_sock_name);
244 if (auth_sock_name != NULL)
245 xfree(auth_sock_name);
246 if (auth_sock_dir != NULL) {
247 rmdir(auth_sock_dir);
248 xfree(auth_sock_dir);
252 auth_sock_name = NULL;
253 auth_sock_dir = NULL;
258 display_loginmsg(void)
260 if (buffer_len(&loginmsg) > 0) {
261 buffer_append(&loginmsg, "\0", 1);
262 printf("%s", (char *)buffer_ptr(&loginmsg));
263 buffer_clear(&loginmsg);
268 do_authenticated(Authctxt *authctxt)
270 setproctitle("%s", authctxt->pw->pw_name);
272 /* setup the channel layer */
273 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
274 channel_permit_all_opens();
279 do_authenticated2(authctxt);
281 do_authenticated1(authctxt);
283 do_cleanup(authctxt);
287 * Prepares for an interactive session. This is called after the user has
288 * been successfully authenticated. During this message exchange, pseudo
289 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
290 * are requested, etc.
293 do_authenticated1(Authctxt *authctxt)
297 int success, type, screen_flag;
298 int enable_compression_after_reply = 0;
299 u_int proto_len, data_len, dlen, compression_level = 0;
303 error("no more sessions");
306 s->authctxt = authctxt;
307 s->pw = authctxt->pw;
310 * We stay in this loop until the client requests to execute a shell
316 /* Get a packet from the client. */
317 type = packet_read();
319 /* Process the packet. */
321 case SSH_CMSG_REQUEST_COMPRESSION:
322 compression_level = packet_get_int();
324 if (compression_level < 1 || compression_level > 9) {
325 packet_send_debug("Received invalid compression level %d.",
329 if (options.compression == COMP_NONE) {
330 debug2("compression disabled");
333 /* Enable compression after we have responded with SUCCESS. */
334 enable_compression_after_reply = 1;
338 case SSH_CMSG_REQUEST_PTY:
339 success = session_pty_req(s);
342 case SSH_CMSG_X11_REQUEST_FORWARDING:
343 s->auth_proto = packet_get_string(&proto_len);
344 s->auth_data = packet_get_string(&data_len);
346 screen_flag = packet_get_protocol_flags() &
347 SSH_PROTOFLAG_SCREEN_NUMBER;
348 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
350 if (packet_remaining() == 4) {
352 debug2("Buggy client: "
353 "X11 screen flag missing");
354 s->screen = packet_get_int();
359 success = session_setup_x11fwd(s);
361 xfree(s->auth_proto);
363 s->auth_proto = NULL;
368 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
369 if (!options.allow_agent_forwarding ||
370 no_agent_forwarding_flag || compat13) {
371 debug("Authentication agent forwarding not permitted for this authentication.");
374 debug("Received authentication agent forwarding request.");
375 success = auth_input_request_forwarding(s->pw);
378 case SSH_CMSG_PORT_FORWARD_REQUEST:
379 if (no_port_forwarding_flag) {
380 debug("Port forwarding not permitted for this authentication.");
383 if (!options.allow_tcp_forwarding) {
384 debug("Port forwarding not permitted.");
387 debug("Received TCP/IP port forwarding request.");
388 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
389 options.gateway_ports) < 0) {
390 debug("Port forwarding failed.");
396 case SSH_CMSG_MAX_PACKET_SIZE:
397 if (packet_set_maxsize(packet_get_int()) > 0)
401 case SSH_CMSG_EXEC_SHELL:
402 case SSH_CMSG_EXEC_CMD:
403 if (type == SSH_CMSG_EXEC_CMD) {
404 command = packet_get_string(&dlen);
405 debug("Exec command '%.500s'", command);
406 if (do_exec(s, command) != 0)
408 "command execution failed");
411 if (do_exec(s, NULL) != 0)
413 "shell execution failed");
421 * Any unknown messages in this phase are ignored,
422 * and a failure message is returned.
424 logit("Unknown packet type received after authentication: %d", type);
426 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
430 /* Enable compression now that we have replied if appropriate. */
431 if (enable_compression_after_reply) {
432 enable_compression_after_reply = 0;
433 packet_start_compression(compression_level);
440 * This is called to fork and execute a command when we have no tty. This
441 * will call do_child from the child, and server_loop from the parent after
442 * setting up file descriptors and such.
445 do_exec_no_pty(Session *s, const char *command)
450 int pin[2], pout[2], perr[2];
453 fatal("do_exec_no_pty: no session");
455 /* Allocate pipes for communicating with the program. */
457 error("%s: pipe in: %.100s", __func__, strerror(errno));
460 if (pipe(pout) < 0) {
461 error("%s: pipe out: %.100s", __func__, strerror(errno));
466 if (pipe(perr) < 0) {
467 error("%s: pipe err: %.100s", __func__,
476 int inout[2], err[2];
479 fatal("do_exec_no_pty: no session");
481 /* Uses socket pairs to communicate with the program. */
482 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
483 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
486 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
487 error("%s: socketpair #2: %.100s", __func__,
495 session_proctitle(s);
497 /* Fork the child. */
498 switch ((pid = fork())) {
500 error("%s: fork: %.100s", __func__, strerror(errno));
518 /* Child. Reinitialize the log since the pid has changed. */
519 log_init(__progname, options.log_level,
520 options.log_facility, log_stderr);
523 * Create a new session and process group since the 4.4BSD
524 * setlogin() affects the entire process group.
527 error("setsid failed: %.100s", strerror(errno));
531 * Redirect stdin. We close the parent side of the socket
532 * pair, and make the child side the standard input.
535 if (dup2(pin[0], 0) < 0)
536 perror("dup2 stdin");
539 /* Redirect stdout. */
541 if (dup2(pout[1], 1) < 0)
542 perror("dup2 stdout");
545 /* Redirect stderr. */
547 if (dup2(perr[1], 2) < 0)
548 perror("dup2 stderr");
552 * Redirect stdin, stdout, and stderr. Stdin and stdout will
553 * use the same socket, as some programs (particularly rdist)
554 * seem to depend on it.
558 if (dup2(inout[0], 0) < 0) /* stdin */
559 perror("dup2 stdin");
560 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
561 perror("dup2 stdout");
563 if (dup2(err[0], 2) < 0) /* stderr */
564 perror("dup2 stderr");
570 cray_init_job(s->pw); /* set up cray jid and tmpdir */
573 /* Do processing for the child (exec command etc). */
574 do_child(s, command);
581 signal(WJSIGNAL, cray_job_termination_handler);
584 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
588 /* Set interactive/non-interactive mode. */
589 packet_set_interactive(s->display != NULL);
592 * Clear loginmsg, since it's the child's responsibility to display
593 * it to the user, otherwise multiple sessions may accumulate
594 * multiple copies of the login messages.
596 buffer_clear(&loginmsg);
599 /* We are the parent. Close the child sides of the pipes. */
605 session_set_fds(s, pin[1], pout[0], perr[0],
608 /* Enter the interactive session. */
609 server_loop(pid, pin[1], pout[0], perr[0]);
610 /* server_loop has closed pin[1], pout[0], and perr[0]. */
613 /* We are the parent. Close the child sides of the socket pairs. */
618 * Enter the interactive session. Note: server_loop must be able to
619 * handle the case that fdin and fdout are the same.
622 session_set_fds(s, inout[1], inout[1], err[1],
625 server_loop(pid, inout[1], inout[1], err[1]);
626 /* server_loop has closed inout[1] and err[1]. */
633 * This is called to fork and execute a command when we have a tty. This
634 * will call do_child from the child, and server_loop from the parent after
635 * setting up file descriptors, controlling tty, updating wtmp, utmp,
636 * lastlog, and other such operations.
639 do_exec_pty(Session *s, const char *command)
641 int fdout, ptyfd, ttyfd, ptymaster;
645 fatal("do_exec_pty: no session");
650 * Create another descriptor of the pty master side for use as the
651 * standard input. We could use the original descriptor, but this
652 * simplifies code in server_loop. The descriptor is bidirectional.
653 * Do this before forking (and cleanup in the child) so as to
654 * detect and gracefully fail out-of-fd conditions.
656 if ((fdout = dup(ptyfd)) < 0) {
657 error("%s: dup #1: %s", __func__, strerror(errno));
662 /* we keep a reference to the pty master */
663 if ((ptymaster = dup(ptyfd)) < 0) {
664 error("%s: dup #2: %s", __func__, strerror(errno));
671 /* Fork the child. */
672 switch ((pid = fork())) {
674 error("%s: fork: %.100s", __func__, strerror(errno));
686 /* Child. Reinitialize the log because the pid has changed. */
687 log_init(__progname, options.log_level,
688 options.log_facility, log_stderr);
689 /* Close the master side of the pseudo tty. */
692 /* Make the pseudo tty our controlling tty. */
693 pty_make_controlling_tty(&ttyfd, s->tty);
695 /* Redirect stdin/stdout/stderr from the pseudo tty. */
696 if (dup2(ttyfd, 0) < 0)
697 error("dup2 stdin: %s", strerror(errno));
698 if (dup2(ttyfd, 1) < 0)
699 error("dup2 stdout: %s", strerror(errno));
700 if (dup2(ttyfd, 2) < 0)
701 error("dup2 stderr: %s", strerror(errno));
703 /* Close the extra descriptor for the pseudo tty. */
706 /* record login, etc. similar to login(1) */
708 if (!(options.use_login && command == NULL)) {
710 cray_init_job(s->pw); /* set up cray jid and tmpdir */
712 do_login(s, command);
714 # ifdef LOGIN_NEEDS_UTMPX
720 * Do common processing for the child, such as execing
723 do_child(s, command);
730 signal(WJSIGNAL, cray_job_termination_handler);
733 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
738 /* Parent. Close the slave side of the pseudo tty. */
741 /* Enter interactive session. */
742 s->ptymaster = ptymaster;
743 packet_set_interactive(1);
745 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
747 server_loop(pid, ptyfd, fdout, -1);
748 /* server_loop _has_ closed ptyfd and fdout. */
753 #ifdef LOGIN_NEEDS_UTMPX
755 do_pre_login(Session *s)
758 struct sockaddr_storage from;
759 pid_t pid = getpid();
762 * Get IP address of client. If the connection is not a socket, let
763 * the address be 0.0.0.0.
765 memset(&from, 0, sizeof(from));
766 fromlen = sizeof(from);
767 if (packet_connection_is_on_socket()) {
768 if (getpeername(packet_get_connection_in(),
769 (struct sockaddr *)&from, &fromlen) < 0) {
770 debug("getpeername: %.100s", strerror(errno));
775 record_utmp_only(pid, s->tty, s->pw->pw_name,
776 get_remote_name_or_ip(utmp_len, options.use_dns),
777 (struct sockaddr *)&from, fromlen);
782 * This is called to fork and execute a command. If another command is
783 * to be forced, execute that instead.
786 do_exec(Session *s, const char *command)
790 if (options.adm_forced_command) {
791 original_command = command;
792 command = options.adm_forced_command;
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 debug("Forced command (config) '%.900s'", command);
799 } else if (forced_command) {
800 original_command = command;
801 command = forced_command;
802 if (IS_INTERNAL_SFTP(command)) {
803 s->is_subsystem = s->is_subsystem ?
804 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
805 } else if (s->is_subsystem)
806 s->is_subsystem = SUBSYSTEM_EXT;
807 debug("Forced command (key option) '%.900s'", command);
810 #ifdef SSH_AUDIT_EVENTS
812 PRIVSEP(audit_run_command(command));
813 else if (s->ttyfd == -1) {
814 char *shell = s->pw->pw_shell;
816 if (shell[0] == '\0') /* empty shell means /bin/sh */
818 PRIVSEP(audit_run_command(shell));
822 ret = do_exec_pty(s, command);
824 ret = do_exec_no_pty(s, command);
826 original_command = NULL;
829 * Clear loginmsg: it's the child's responsibility to display
830 * it to the user, otherwise multiple sessions may accumulate
831 * multiple copies of the login messages.
833 buffer_clear(&loginmsg);
838 /* administrative, login(1)-like work */
840 do_login(Session *s, const char *command)
843 struct sockaddr_storage from;
844 struct passwd * pw = s->pw;
845 pid_t pid = getpid();
848 * Get IP address of client. If the connection is not a socket, let
849 * the address be 0.0.0.0.
851 memset(&from, 0, sizeof(from));
852 fromlen = sizeof(from);
853 if (packet_connection_is_on_socket()) {
854 if (getpeername(packet_get_connection_in(),
855 (struct sockaddr *)&from, &fromlen) < 0) {
856 debug("getpeername: %.100s", strerror(errno));
861 /* Record that there was a login on that tty from the remote host. */
863 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
864 get_remote_name_or_ip(utmp_len,
866 (struct sockaddr *)&from, fromlen);
870 * If password change is needed, do it now.
871 * This needs to occur before the ~/.hushlogin check.
873 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
876 s->authctxt->force_pwchange = 0;
877 /* XXX - signal [net] parent to enable forwardings */
881 if (check_quietlogin(s, command))
890 * Display the message of the day.
897 #ifdef HAVE_LOGIN_CAP
901 #ifdef HAVE_LOGIN_CAP
902 fname = login_getcapstr(lc, "copyright", NULL, NULL);
903 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
904 while (fgets(buf, sizeof(buf), f) != NULL)
908 #endif /* HAVE_LOGIN_CAP */
909 (void)printf("%s\n\t%s %s\n",
910 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
911 "The Regents of the University of California. ",
912 "All rights reserved.");
916 if (options.print_motd) {
917 #ifdef HAVE_LOGIN_CAP
918 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
921 f = fopen("/etc/motd", "r");
924 while (fgets(buf, sizeof(buf), f))
933 * Check for quiet login, either .hushlogin or command given.
936 check_quietlogin(Session *s, const char *command)
939 struct passwd *pw = s->pw;
942 /* Return 1 if .hushlogin exists or a command given. */
945 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
946 #ifdef HAVE_LOGIN_CAP
947 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
950 if (stat(buf, &st) >= 0)
957 * Sets the value of the given variable in the environment. If the variable
958 * already exists, its value is overridden.
961 child_set_env(char ***envp, u_int *envsizep, const char *name,
969 * If we're passed an uninitialized list, allocate a single null
970 * entry before continuing.
972 if (*envp == NULL && *envsizep == 0) {
973 *envp = xmalloc(sizeof(char *));
979 * Find the slot where the value should be stored. If the variable
980 * already exists, we reuse the slot; otherwise we append a new slot
981 * at the end of the array, expanding if necessary.
984 namelen = strlen(name);
985 for (i = 0; env[i]; i++)
986 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
989 /* Reuse the slot. */
992 /* New variable. Expand if necessary. */
994 if (i >= envsize - 1) {
996 fatal("child_set_env: too many env vars");
998 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
1001 /* Need to set the NULL pointer at end of array beyond the new slot. */
1005 /* Allocate space and format the variable in the appropriate slot. */
1006 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1007 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1011 * Reads environment variables from the given file and adds/overrides them
1012 * into the environment. If the file does not exist, this does nothing.
1013 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1014 * and assignments of the form name=value. No other forms are allowed.
1017 read_environment_file(char ***env, u_int *envsize,
1018 const char *filename)
1025 f = fopen(filename, "r");
1029 while (fgets(buf, sizeof(buf), f)) {
1030 if (++lineno > 1000)
1031 fatal("Too many lines in environment file %s", filename);
1032 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1034 if (!*cp || *cp == '#' || *cp == '\n')
1037 cp[strcspn(cp, "\n")] = '\0';
1039 value = strchr(cp, '=');
1040 if (value == NULL) {
1041 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1046 * Replace the equals sign by nul, and advance value to
1051 child_set_env(env, envsize, cp, value);
1056 #ifdef HAVE_ETC_DEFAULT_LOGIN
1058 * Return named variable from specified environment, or NULL if not present.
1061 child_get_env(char **env, const char *name)
1067 for (i=0; env[i] != NULL; i++)
1068 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1069 return(env[i] + len + 1);
1074 * Read /etc/default/login.
1075 * We pick up the PATH (or SUPATH for root) and UMASK.
1078 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1080 char **tmpenv = NULL, *var;
1081 u_int i, tmpenvsize = 0;
1085 * We don't want to copy the whole file to the child's environment,
1086 * so we use a temporary environment and copy the variables we're
1089 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1095 var = child_get_env(tmpenv, "SUPATH");
1097 var = child_get_env(tmpenv, "PATH");
1099 child_set_env(env, envsize, "PATH", var);
1101 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1102 if (sscanf(var, "%5lo", &mask) == 1)
1103 umask((mode_t)mask);
1105 for (i = 0; tmpenv[i] != NULL; i++)
1109 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1112 copy_environment(char **source, char ***env, u_int *envsize)
1114 char *var_name, *var_val;
1120 for(i = 0; source[i] != NULL; i++) {
1121 var_name = xstrdup(source[i]);
1122 if ((var_val = strstr(var_name, "=")) == NULL) {
1128 debug3("Copy environment: %s=%s", var_name, var_val);
1129 child_set_env(env, envsize, var_name, var_val);
1136 do_setup_env(Session *s, const char *shell)
1141 struct passwd *pw = s->pw;
1142 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1145 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);
1207 * This interferes with libc's management of the environment
1208 * in horrible ways that can cause sshd to crash.
1210 for (var = environ; *var != NULL; ++var)
1215 #else /* HAVE_LOGIN_CAP */
1216 # ifndef HAVE_CYGWIN
1218 * There's no standard path on Windows. The path contains
1219 * important components pointing to the system directories,
1220 * needed for loading shared libraries. So the path better
1221 * remains intact here.
1223 # ifdef HAVE_ETC_DEFAULT_LOGIN
1224 read_etc_default_login(&env, &envsize, pw->pw_uid);
1225 path = child_get_env(env, "PATH");
1226 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1227 if (path == NULL || *path == '\0') {
1228 child_set_env(&env, &envsize, "PATH",
1229 s->pw->pw_uid == 0 ?
1230 SUPERUSER_PATH : _PATH_STDPATH);
1232 # endif /* HAVE_CYGWIN */
1233 #endif /* HAVE_LOGIN_CAP */
1235 /* Normal systems set SHELL by default. */
1236 child_set_env(&env, &envsize, "SHELL", shell);
1239 /* Set custom environment options from RSA authentication. */
1240 if (!options.use_login) {
1241 while (custom_environment) {
1242 struct envstring *ce = custom_environment;
1245 for (i = 0; str[i] != '=' && str[i]; i++)
1247 if (str[i] == '=') {
1249 child_set_env(&env, &envsize, str, str + i + 1);
1251 custom_environment = ce->next;
1257 /* SSH_CLIENT deprecated */
1258 snprintf(buf, sizeof buf, "%.50s %d %d",
1259 get_remote_ipaddr(), get_remote_port(), get_local_port());
1260 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1262 laddr = get_local_ipaddr(packet_get_connection_in());
1263 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1264 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1266 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1269 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1271 child_set_env(&env, &envsize, "TERM", s->term);
1273 child_set_env(&env, &envsize, "DISPLAY", s->display);
1274 if (original_command)
1275 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1279 if (cray_tmpdir[0] != '\0')
1280 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1281 #endif /* _UNICOS */
1284 * Since we clear KRB5CCNAME at startup, if it's set now then it
1285 * must have been set by a native authentication method (eg AIX or
1286 * SIA), so copy it to the child.
1291 if ((cp = getenv("KRB5CCNAME")) != NULL)
1292 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1299 if ((cp = getenv("AUTHSTATE")) != NULL)
1300 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1301 read_environment_file(&env, &envsize, "/etc/environment");
1305 if (s->authctxt->krb5_ccname)
1306 child_set_env(&env, &envsize, "KRB5CCNAME",
1307 s->authctxt->krb5_ccname);
1311 * Pull in any environment variables that may have
1314 if (options.use_pam) {
1317 p = fetch_pam_child_environment();
1318 copy_environment(p, &env, &envsize);
1319 free_pam_environment(p);
1321 p = fetch_pam_environment();
1322 copy_environment(p, &env, &envsize);
1323 free_pam_environment(p);
1325 #endif /* USE_PAM */
1327 if (auth_sock_name != NULL)
1328 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1331 /* read $HOME/.ssh/environment. */
1332 if (options.permit_user_env && !options.use_login) {
1333 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1334 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1335 read_environment_file(&env, &envsize, buf);
1338 /* dump the environment */
1339 fprintf(stderr, "Environment:\n");
1340 for (i = 0; env[i]; i++)
1341 fprintf(stderr, " %.200s\n", env[i]);
1347 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1348 * first in this order).
1351 do_rc_files(Session *s, const char *shell)
1359 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1361 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1362 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1363 !no_user_rc && stat(_PATH_SSH_USER_RC, &st) >= 0) {
1364 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1365 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1367 fprintf(stderr, "Running %s\n", cmd);
1368 f = popen(cmd, "w");
1371 fprintf(f, "%s %s\n", s->auth_proto,
1375 fprintf(stderr, "Could not run %s\n",
1377 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1379 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1380 _PATH_SSH_SYSTEM_RC);
1381 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1384 fprintf(f, "%s %s\n", s->auth_proto,
1388 fprintf(stderr, "Could not run %s\n",
1389 _PATH_SSH_SYSTEM_RC);
1390 } else if (do_xauth && options.xauth_location != NULL) {
1391 /* Add authority data to .Xauthority if appropriate. */
1394 "Running %.500s remove %.100s\n",
1395 options.xauth_location, s->auth_display);
1397 "%.500s add %.100s %.100s %.100s\n",
1398 options.xauth_location, s->auth_display,
1399 s->auth_proto, s->auth_data);
1401 snprintf(cmd, sizeof cmd, "%s -q -",
1402 options.xauth_location);
1403 f = popen(cmd, "w");
1405 fprintf(f, "remove %s\n",
1407 fprintf(f, "add %s %s %s\n",
1408 s->auth_display, s->auth_proto,
1412 fprintf(stderr, "Could not run %s\n",
1419 do_nologin(struct passwd *pw)
1422 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1425 #ifdef HAVE_LOGIN_CAP
1426 if (login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1428 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1430 if (pw->pw_uid == 0)
1434 if (stat(nl, &sb) == -1) {
1440 /* /etc/nologin exists. Print its contents if we can and exit. */
1441 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1442 if ((f = fopen(nl, "r")) != NULL) {
1443 while (fgets(buf, sizeof(buf), f))
1451 * Chroot into a directory after checking it for safety: all path components
1452 * must be root-owned directories with strict permissions.
1455 safely_chroot(const char *path, uid_t uid)
1458 char component[MAXPATHLEN];
1462 fatal("chroot path does not begin at root");
1463 if (strlen(path) >= sizeof(component))
1464 fatal("chroot path too long");
1467 * Descend the path, checking that each component is a
1468 * root-owned directory with strict permissions.
1470 for (cp = path; cp != NULL;) {
1471 if ((cp = strchr(cp, '/')) == NULL)
1472 strlcpy(component, path, sizeof(component));
1475 memcpy(component, path, cp - path);
1476 component[cp - path] = '\0';
1479 debug3("%s: checking '%s'", __func__, component);
1481 if (stat(component, &st) != 0)
1482 fatal("%s: stat(\"%s\"): %s", __func__,
1483 component, strerror(errno));
1484 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1485 fatal("bad ownership or modes for chroot "
1486 "directory %s\"%s\"",
1487 cp == NULL ? "" : "component ", component);
1488 if (!S_ISDIR(st.st_mode))
1489 fatal("chroot path %s\"%s\" is not a directory",
1490 cp == NULL ? "" : "component ", component);
1494 if (chdir(path) == -1)
1495 fatal("Unable to chdir to chroot path \"%s\": "
1496 "%s", path, strerror(errno));
1497 if (chroot(path) == -1)
1498 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1499 if (chdir("/") == -1)
1500 fatal("%s: chdir(/) after chroot: %s",
1501 __func__, strerror(errno));
1502 verbose("Changed root directory to \"%s\"", path);
1505 /* Set login name, uid, gid, and groups. */
1507 do_setusercontext(struct passwd *pw)
1509 char *chroot_path, *tmp;
1512 /* Cache selinux status for later use */
1513 (void)ssh_selinux_enabled();
1517 if (getuid() == 0 || geteuid() == 0)
1518 #endif /* HAVE_CYGWIN */
1520 #ifdef HAVE_LOGIN_CAP
1525 if (options.use_pam) {
1526 do_pam_setcred(use_privsep);
1528 # endif /* USE_PAM */
1529 if (setusercontext(lc, pw, pw->pw_uid,
1530 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1531 perror("unable to set user context");
1535 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1536 /* Sets login uid for accounting */
1537 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1538 error("setluid: %s", strerror(errno));
1539 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1541 if (setlogin(pw->pw_name) < 0)
1542 error("setlogin failed: %s", strerror(errno));
1543 if (setgid(pw->pw_gid) < 0) {
1547 /* Initialize the group list. */
1548 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1549 perror("initgroups");
1555 * PAM credentials may take the form of supplementary groups.
1556 * These will have been wiped by the above initgroups() call.
1557 * Reestablish them here.
1559 if (options.use_pam) {
1560 do_pam_setcred(use_privsep);
1562 # endif /* USE_PAM */
1563 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1564 irix_setusercontext(pw);
1565 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1570 if (set_id(pw->pw_name) != 0) {
1573 # endif /* USE_LIBIAF */
1575 #ifdef HAVE_SETPCRED
1577 * If we have a chroot directory, we set all creds except real
1578 * uid which we will need for chroot. If we don't have a
1579 * chroot directory, we don't override anything.
1582 char **creds = NULL, *chroot_creds[] =
1583 { "REAL_USER=root", NULL };
1585 if (options.chroot_directory != NULL &&
1586 strcasecmp(options.chroot_directory, "none") != 0)
1587 creds = chroot_creds;
1589 if (setpcred(pw->pw_name, creds) == -1)
1590 fatal("Failed to set process credentials");
1592 #endif /* HAVE_SETPCRED */
1595 ssh_selinux_setup_exec_context(pw->pw_name);
1598 if (options.chroot_directory != NULL &&
1599 strcasecmp(options.chroot_directory, "none") != 0) {
1600 tmp = tilde_expand_filename(options.chroot_directory,
1602 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1603 "u", pw->pw_name, (char *)NULL);
1604 safely_chroot(chroot_path, pw->pw_uid);
1609 #ifdef HAVE_LOGIN_CAP
1610 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1611 perror("unable to set user context (setuser)");
1615 /* Permanently switch to the desired uid. */
1616 permanently_set_uid(pw);
1620 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1621 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1625 do_pwchange(Session *s)
1628 fprintf(stderr, "WARNING: Your password has expired.\n");
1629 if (s->ttyfd != -1) {
1631 "You must change your password now and login again!\n");
1632 #ifdef PASSWD_NEEDS_USERNAME
1633 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1636 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1641 "Password change required but no TTY available.\n");
1647 launch_login(struct passwd *pw, const char *hostname)
1649 /* Launch login(1). */
1651 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1652 #ifdef xxxLOGIN_NEEDS_TERM
1653 (s->term ? s->term : "unknown"),
1654 #endif /* LOGIN_NEEDS_TERM */
1655 #ifdef LOGIN_NO_ENDOPT
1656 "-p", "-f", pw->pw_name, (char *)NULL);
1658 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1661 /* Login couldn't be executed, die. */
1668 child_close_fds(void)
1672 if (packet_get_connection_in() == packet_get_connection_out())
1673 close(packet_get_connection_in());
1675 close(packet_get_connection_in());
1676 close(packet_get_connection_out());
1679 * Close all descriptors related to channels. They will still remain
1680 * open in the parent.
1682 /* XXX better use close-on-exec? -markus */
1683 channel_close_all();
1686 * Close any extra file descriptors. Note that there may still be
1687 * descriptors left by system functions. They will be closed later.
1692 * Close any extra open file descriptors so that we don't have them
1693 * hanging around in clients. Note that we want to do this after
1694 * initgroups, because at least on Solaris 2.3 it leaves file
1697 for (i = 3; i < 64; i++)
1702 * Performs common processing for the child, such as setting up the
1703 * environment, closing extra file descriptors, setting the user and group
1704 * ids, and executing the command or shell.
1708 do_child(Session *s, const char *command)
1710 extern char **environ;
1712 char *argv[ARGV_MAX];
1713 const char *shell, *shell0, *hostname = NULL;
1714 struct passwd *pw = s->pw;
1717 /* remove hostkey from the child's memory */
1718 destroy_sensitive_data();
1720 /* Force a password change */
1721 if (s->authctxt->force_pwchange) {
1722 do_setusercontext(pw);
1728 /* login(1) is only called if we execute the login shell */
1729 if (options.use_login && command != NULL)
1730 options.use_login = 0;
1733 cray_setup(pw->pw_uid, pw->pw_name, command);
1734 #endif /* _UNICOS */
1737 * Login(1) does this as well, and it needs uid 0 for the "-h"
1738 * switch, so we let login(1) to this for us.
1740 if (!options.use_login) {
1742 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1743 if (!check_quietlogin(s, command))
1745 #else /* HAVE_OSF_SIA */
1746 /* When PAM is enabled we rely on it to do the nologin check */
1747 if (!options.use_pam)
1749 do_setusercontext(pw);
1751 * PAM session modules in do_setusercontext may have
1752 * generated messages, so if this in an interactive
1753 * login then display them too.
1755 if (!check_quietlogin(s, command))
1757 #endif /* HAVE_OSF_SIA */
1761 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1762 debug3("PAM session not opened, exiting");
1769 * Get the shell from the password data. An empty shell field is
1770 * legal, and means /bin/sh.
1772 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1775 * Make sure $SHELL points to the shell from the password file,
1776 * even if shell is overridden from login.conf
1778 env = do_setup_env(s, shell);
1780 #ifdef HAVE_LOGIN_CAP
1781 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1784 /* we have to stash the hostname before we close our socket. */
1785 if (options.use_login)
1786 hostname = get_remote_name_or_ip(utmp_len,
1789 * Close the connection descriptors; note that this is the child, and
1790 * the server will still have the socket open, and it is important
1791 * that we do not shutdown it. Note that the descriptors cannot be
1792 * closed before building the environment, as we call
1793 * get_remote_ipaddr there.
1798 * Must take new environment into use so that .ssh/rc,
1799 * /etc/ssh/sshrc and xauth are run in the proper environment.
1803 #if defined(KRB5) && defined(USE_AFS)
1805 * At this point, we check to see if AFS is active and if we have
1806 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1807 * if we can (and need to) extend the ticket into an AFS token. If
1808 * we don't do this, we run into potential problems if the user's
1809 * home directory is in AFS and it's not world-readable.
1812 if (options.kerberos_get_afs_token && k_hasafs() &&
1813 (s->authctxt->krb5_ctx != NULL)) {
1816 debug("Getting AFS token");
1820 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1821 krb5_afslog(s->authctxt->krb5_ctx,
1822 s->authctxt->krb5_fwd_ccache, cell, NULL);
1824 krb5_afslog_home(s->authctxt->krb5_ctx,
1825 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1829 /* Change current directory to the user's home directory. */
1830 if (chdir(pw->pw_dir) < 0) {
1831 /* Suppress missing homedir warning for chroot case */
1832 #ifdef HAVE_LOGIN_CAP
1833 r = login_getcapbool(lc, "requirehome", 0);
1835 if (r || options.chroot_directory == NULL ||
1836 strcasecmp(options.chroot_directory, "none") == 0)
1837 fprintf(stderr, "Could not chdir to home "
1838 "directory %s: %s\n", pw->pw_dir,
1844 closefrom(STDERR_FILENO + 1);
1846 if (!options.use_login)
1847 do_rc_files(s, shell);
1849 /* restore SIGPIPE for child */
1850 signal(SIGPIPE, SIG_DFL);
1852 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1853 printf("This service allows sftp connections only.\n");
1856 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1857 extern int optind, optreset;
1861 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1862 args = xstrdup(command ? command : "sftp-server");
1863 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1864 if (i < ARGV_MAX - 1)
1867 optind = optreset = 1;
1868 __progname = argv[0];
1870 ssh_selinux_change_context("sftpd_t");
1872 exit(sftp_server_main(i, argv, s->pw));
1877 if (options.use_login) {
1878 launch_login(pw, hostname);
1882 /* Get the last component of the shell name. */
1883 if ((shell0 = strrchr(shell, '/')) != NULL)
1889 * If we have no command, execute the shell. In this case, the shell
1890 * name to be passed in argv[0] is preceded by '-' to indicate that
1891 * this is a login shell.
1896 /* Start the shell. Set initial character to '-'. */
1899 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1900 >= sizeof(argv0) - 1) {
1906 /* Execute the shell. */
1909 execve(shell, argv, env);
1911 /* Executing the shell failed. */
1916 * Execute the command using the user's shell. This uses the -c
1917 * option to execute the command.
1919 argv[0] = (char *) shell0;
1921 argv[2] = (char *) command;
1923 execve(shell, argv, env);
1929 session_unused(int id)
1931 debug3("%s: session id %d unused", __func__, id);
1932 if (id >= options.max_sessions ||
1933 id >= sessions_nalloc) {
1934 fatal("%s: insane session id %d (max %d nalloc %d)",
1935 __func__, id, options.max_sessions, sessions_nalloc);
1937 bzero(&sessions[id], sizeof(*sessions));
1938 sessions[id].self = id;
1939 sessions[id].used = 0;
1940 sessions[id].chanid = -1;
1941 sessions[id].ptyfd = -1;
1942 sessions[id].ttyfd = -1;
1943 sessions[id].ptymaster = -1;
1944 sessions[id].x11_chanids = NULL;
1945 sessions[id].next_unused = sessions_first_unused;
1946 sessions_first_unused = id;
1954 if (sessions_first_unused == -1) {
1955 if (sessions_nalloc >= options.max_sessions)
1957 debug2("%s: allocate (allocated %d max %d)",
1958 __func__, sessions_nalloc, options.max_sessions);
1959 tmp = xrealloc(sessions, sessions_nalloc + 1,
1962 error("%s: cannot allocate %d sessions",
1963 __func__, sessions_nalloc + 1);
1967 session_unused(sessions_nalloc++);
1970 if (sessions_first_unused >= sessions_nalloc ||
1971 sessions_first_unused < 0) {
1972 fatal("%s: insane first_unused %d max %d nalloc %d",
1973 __func__, sessions_first_unused, options.max_sessions,
1977 s = &sessions[sessions_first_unused];
1979 fatal("%s: session %d already used",
1980 __func__, sessions_first_unused);
1982 sessions_first_unused = s->next_unused;
1984 s->next_unused = -1;
1985 debug("session_new: session %d", s->self);
1994 for (i = 0; i < sessions_nalloc; i++) {
1995 Session *s = &sessions[i];
1997 debug("dump: used %d next_unused %d session %d %p "
1998 "channel %d pid %ld",
2009 session_open(Authctxt *authctxt, int chanid)
2011 Session *s = session_new();
2012 debug("session_open: channel %d", chanid);
2014 error("no more sessions");
2017 s->authctxt = authctxt;
2018 s->pw = authctxt->pw;
2019 if (s->pw == NULL || !authctxt->valid)
2020 fatal("no user for session %d", s->self);
2021 debug("session_open: session %d: link with channel %d", s->self, chanid);
2027 session_by_tty(char *tty)
2030 for (i = 0; i < sessions_nalloc; i++) {
2031 Session *s = &sessions[i];
2032 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
2033 debug("session_by_tty: session %d tty %s", i, tty);
2037 debug("session_by_tty: unknown tty %.100s", tty);
2043 session_by_channel(int id)
2046 for (i = 0; i < sessions_nalloc; i++) {
2047 Session *s = &sessions[i];
2048 if (s->used && s->chanid == id) {
2049 debug("session_by_channel: session %d channel %d",
2054 debug("session_by_channel: unknown channel %d", id);
2060 session_by_x11_channel(int id)
2064 for (i = 0; i < sessions_nalloc; i++) {
2065 Session *s = &sessions[i];
2067 if (s->x11_chanids == NULL || !s->used)
2069 for (j = 0; s->x11_chanids[j] != -1; j++) {
2070 if (s->x11_chanids[j] == id) {
2071 debug("session_by_x11_channel: session %d "
2072 "channel %d", s->self, id);
2077 debug("session_by_x11_channel: unknown channel %d", id);
2083 session_by_pid(pid_t pid)
2086 debug("session_by_pid: pid %ld", (long)pid);
2087 for (i = 0; i < sessions_nalloc; i++) {
2088 Session *s = &sessions[i];
2089 if (s->used && s->pid == pid)
2092 error("session_by_pid: unknown pid %ld", (long)pid);
2098 session_window_change_req(Session *s)
2100 s->col = packet_get_int();
2101 s->row = packet_get_int();
2102 s->xpixel = packet_get_int();
2103 s->ypixel = packet_get_int();
2105 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2110 session_pty_req(Session *s)
2116 debug("Allocating a pty not permitted for this authentication.");
2119 if (s->ttyfd != -1) {
2120 packet_disconnect("Protocol error: you already have a pty.");
2124 s->term = packet_get_string(&len);
2127 s->col = packet_get_int();
2128 s->row = packet_get_int();
2130 s->row = packet_get_int();
2131 s->col = packet_get_int();
2133 s->xpixel = packet_get_int();
2134 s->ypixel = packet_get_int();
2136 if (strcmp(s->term, "") == 0) {
2141 /* Allocate a pty and open it. */
2142 debug("Allocating pty.");
2143 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
2150 error("session_pty_req: session %d alloc failed", s->self);
2153 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2155 /* for SSH1 the tty modes length is not given */
2157 n_bytes = packet_remaining();
2158 tty_parse_modes(s->ttyfd, &n_bytes);
2161 pty_setowner(s->pw, s->tty);
2163 /* Set window size from the packet. */
2164 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2167 session_proctitle(s);
2172 session_subsystem_req(Session *s)
2177 char *prog, *cmd, *subsys = packet_get_string(&len);
2181 logit("subsystem request for %.100s by user %s", subsys,
2184 for (i = 0; i < options.num_subsystems; i++) {
2185 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
2186 prog = options.subsystem_command[i];
2187 cmd = options.subsystem_args[i];
2188 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2189 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2190 debug("subsystem: %s", prog);
2192 if (stat(prog, &st) < 0)
2193 debug("subsystem: cannot stat %s: %s",
2194 prog, strerror(errno));
2195 s->is_subsystem = SUBSYSTEM_EXT;
2196 debug("subsystem: exec() %s", cmd);
2198 success = do_exec(s, cmd) == 0;
2204 logit("subsystem request for %.100s failed, subsystem not found",
2212 session_x11_req(Session *s)
2216 if (s->auth_proto != NULL || s->auth_data != NULL) {
2217 error("session_x11_req: session %d: "
2218 "x11 forwarding already active", s->self);
2221 s->single_connection = packet_get_char();
2222 s->auth_proto = packet_get_string(NULL);
2223 s->auth_data = packet_get_string(NULL);
2224 s->screen = packet_get_int();
2227 success = session_setup_x11fwd(s);
2229 xfree(s->auth_proto);
2230 xfree(s->auth_data);
2231 s->auth_proto = NULL;
2232 s->auth_data = NULL;
2238 session_shell_req(Session *s)
2241 return do_exec(s, NULL) == 0;
2245 session_exec_req(Session *s)
2249 char *command = packet_get_string(&len);
2251 success = do_exec(s, command) == 0;
2257 session_break_req(Session *s)
2260 packet_get_int(); /* ignored */
2263 if (s->ttyfd == -1 || tcsendbreak(s->ttyfd, 0) < 0)
2269 session_env_req(Session *s)
2272 u_int name_len, val_len, i;
2274 name = packet_get_string(&name_len);
2275 val = packet_get_string(&val_len);
2278 /* Don't set too many environment variables */
2279 if (s->num_env > 128) {
2280 debug2("Ignoring env request %s: too many env vars", name);
2284 for (i = 0; i < options.num_accept_env; i++) {
2285 if (match_pattern(name, options.accept_env[i])) {
2286 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2287 s->env = xrealloc(s->env, s->num_env + 1,
2289 s->env[s->num_env].name = name;
2290 s->env[s->num_env].val = val;
2295 debug2("Ignoring env request %s: disallowed name", name);
2304 session_auth_agent_req(Session *s)
2306 static int called = 0;
2308 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2309 debug("session_auth_agent_req: no_agent_forwarding_flag");
2316 return auth_input_request_forwarding(s->pw);
2321 session_input_channel_req(Channel *c, const char *rtype)
2326 if ((s = session_by_channel(c->self)) == NULL) {
2327 logit("session_input_channel_req: no session %d req %.100s",
2331 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2334 * a session is in LARVAL state until a shell, a command
2335 * or a subsystem is executed
2337 if (c->type == SSH_CHANNEL_LARVAL) {
2338 if (strcmp(rtype, "shell") == 0) {
2339 success = session_shell_req(s);
2340 } else if (strcmp(rtype, "exec") == 0) {
2341 success = session_exec_req(s);
2342 } else if (strcmp(rtype, "pty-req") == 0) {
2343 success = session_pty_req(s);
2344 } else if (strcmp(rtype, "x11-req") == 0) {
2345 success = session_x11_req(s);
2346 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2347 success = session_auth_agent_req(s);
2348 } else if (strcmp(rtype, "subsystem") == 0) {
2349 success = session_subsystem_req(s);
2350 } else if (strcmp(rtype, "env") == 0) {
2351 success = session_env_req(s);
2354 if (strcmp(rtype, "window-change") == 0) {
2355 success = session_window_change_req(s);
2356 } else if (strcmp(rtype, "break") == 0) {
2357 success = session_break_req(s);
2364 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2368 fatal("session_set_fds: called for proto != 2.0");
2370 * now that have a child and a pipe to the child,
2371 * we can activate our channel and register the fd's
2373 if (s->chanid == -1)
2374 fatal("no channel for session %d", s->self);
2375 if (options.hpn_disabled)
2376 channel_set_fds(s->chanid,
2378 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2379 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2381 channel_set_fds(s->chanid,
2383 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2384 1, is_tty, options.hpn_buffer_size);
2388 * Function to perform pty cleanup. Also called if we get aborted abnormally
2389 * (e.g., due to a dropped connection).
2392 session_pty_cleanup2(Session *s)
2395 error("session_pty_cleanup: no session");
2401 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2403 /* Record that the user has logged out. */
2405 record_logout(s->pid, s->tty, s->pw->pw_name);
2407 /* Release the pseudo-tty. */
2409 pty_release(s->tty);
2412 * Close the server side of the socket pairs. We must do this after
2413 * the pty cleanup, so that another process doesn't get this pty
2414 * while we're still cleaning up.
2416 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2417 error("close(s->ptymaster/%d): %s",
2418 s->ptymaster, strerror(errno));
2420 /* unlink pty from session */
2425 session_pty_cleanup(Session *s)
2427 PRIVSEP(session_pty_cleanup2(s));
2433 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2448 return "SIG@openssh.com";
2452 session_close_x11(int id)
2456 if ((c = channel_by_id(id)) == NULL) {
2457 debug("session_close_x11: x11 channel %d missing", id);
2459 /* Detach X11 listener */
2460 debug("session_close_x11: detach x11 channel %d", id);
2461 channel_cancel_cleanup(id);
2462 if (c->ostate != CHAN_OUTPUT_CLOSED)
2468 session_close_single_x11(int id, void *arg)
2473 debug3("session_close_single_x11: channel %d", id);
2474 channel_cancel_cleanup(id);
2475 if ((s = session_by_x11_channel(id)) == NULL)
2476 fatal("session_close_single_x11: no x11 channel %d", id);
2477 for (i = 0; s->x11_chanids[i] != -1; i++) {
2478 debug("session_close_single_x11: session %d: "
2479 "closing channel %d", s->self, s->x11_chanids[i]);
2481 * The channel "id" is already closing, but make sure we
2482 * close all of its siblings.
2484 if (s->x11_chanids[i] != id)
2485 session_close_x11(s->x11_chanids[i]);
2487 xfree(s->x11_chanids);
2488 s->x11_chanids = NULL;
2493 if (s->auth_proto) {
2494 xfree(s->auth_proto);
2495 s->auth_proto = NULL;
2498 xfree(s->auth_data);
2499 s->auth_data = NULL;
2501 if (s->auth_display) {
2502 xfree(s->auth_display);
2503 s->auth_display = NULL;
2508 session_exit_message(Session *s, int status)
2512 if ((c = channel_lookup(s->chanid)) == NULL)
2513 fatal("session_exit_message: session %d: no channel %d",
2514 s->self, s->chanid);
2515 debug("session_exit_message: session %d channel %d pid %ld",
2516 s->self, s->chanid, (long)s->pid);
2518 if (WIFEXITED(status)) {
2519 channel_request_start(s->chanid, "exit-status", 0);
2520 packet_put_int(WEXITSTATUS(status));
2522 } else if (WIFSIGNALED(status)) {
2523 channel_request_start(s->chanid, "exit-signal", 0);
2524 packet_put_cstring(sig2name(WTERMSIG(status)));
2526 packet_put_char(WCOREDUMP(status)? 1 : 0);
2527 #else /* WCOREDUMP */
2529 #endif /* WCOREDUMP */
2530 packet_put_cstring("");
2531 packet_put_cstring("");
2534 /* Some weird exit cause. Just exit. */
2535 packet_disconnect("wait returned status %04x.", status);
2538 /* disconnect channel */
2539 debug("session_exit_message: release channel %d", s->chanid);
2542 * Adjust cleanup callback attachment to send close messages when
2543 * the channel gets EOF. The session will be then be closed
2544 * by session_close_by_channel when the childs close their fds.
2546 channel_register_cleanup(c->self, session_close_by_channel, 1);
2549 * emulate a write failure with 'chan_write_failed', nobody will be
2550 * interested in data we write.
2551 * Note that we must not call 'chan_read_failed', since there could
2552 * be some more data waiting in the pipe.
2554 if (c->ostate != CHAN_OUTPUT_CLOSED)
2555 chan_write_failed(c);
2559 session_close(Session *s)
2563 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2565 session_pty_cleanup(s);
2571 xfree(s->x11_chanids);
2572 if (s->auth_display)
2573 xfree(s->auth_display);
2575 xfree(s->auth_data);
2577 xfree(s->auth_proto);
2578 if (s->env != NULL) {
2579 for (i = 0; i < s->num_env; i++) {
2580 xfree(s->env[i].name);
2581 xfree(s->env[i].val);
2585 session_proctitle(s);
2586 session_unused(s->self);
2590 session_close_by_pid(pid_t pid, int status)
2592 Session *s = session_by_pid(pid);
2594 debug("session_close_by_pid: no session for pid %ld",
2598 if (s->chanid != -1)
2599 session_exit_message(s, status);
2601 session_pty_cleanup(s);
2606 * this is called when a channel dies before
2607 * the session 'child' itself dies
2610 session_close_by_channel(int id, void *arg)
2612 Session *s = session_by_channel(id);
2616 debug("session_close_by_channel: no session for id %d", id);
2619 debug("session_close_by_channel: channel %d child %ld",
2622 debug("session_close_by_channel: channel %d: has child", id);
2624 * delay detach of session, but release pty, since
2625 * the fd's to the child are already closed
2628 session_pty_cleanup(s);
2631 /* detach by removing callback */
2632 channel_cancel_cleanup(s->chanid);
2634 /* Close any X11 listeners associated with this session */
2635 if (s->x11_chanids != NULL) {
2636 for (i = 0; s->x11_chanids[i] != -1; i++) {
2637 session_close_x11(s->x11_chanids[i]);
2638 s->x11_chanids[i] = -1;
2647 session_destroy_all(void (*closefunc)(Session *))
2650 for (i = 0; i < sessions_nalloc; i++) {
2651 Session *s = &sessions[i];
2653 if (closefunc != NULL)
2662 session_tty_list(void)
2664 static char buf[1024];
2669 for (i = 0; i < sessions_nalloc; i++) {
2670 Session *s = &sessions[i];
2671 if (s->used && s->ttyfd != -1) {
2673 if (strncmp(s->tty, "/dev/", 5) != 0) {
2674 cp = strrchr(s->tty, '/');
2675 cp = (cp == NULL) ? s->tty : cp + 1;
2680 strlcat(buf, ",", sizeof buf);
2681 strlcat(buf, cp, sizeof buf);
2685 strlcpy(buf, "notty", sizeof buf);
2690 session_proctitle(Session *s)
2693 error("no user for session %d", s->self);
2695 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2699 session_setup_x11fwd(Session *s)
2702 char display[512], auth_display[512];
2703 char hostname[MAXHOSTNAMELEN];
2706 if (no_x11_forwarding_flag) {
2707 packet_send_debug("X11 forwarding disabled in user configuration file.");
2710 if (!options.x11_forwarding) {
2711 debug("X11 forwarding disabled in server configuration file.");
2714 if (!options.xauth_location ||
2715 (stat(options.xauth_location, &st) == -1)) {
2716 packet_send_debug("No xauth program; cannot forward with spoofing.");
2719 if (options.use_login) {
2720 packet_send_debug("X11 forwarding disabled; "
2721 "not compatible with UseLogin=yes.");
2724 if (s->display != NULL) {
2725 debug("X11 display already set.");
2728 if (x11_create_display_inet(options.x11_display_offset,
2729 options.x11_use_localhost, s->single_connection,
2730 &s->display_number, &s->x11_chanids) == -1) {
2731 debug("x11_create_display_inet failed.");
2734 for (i = 0; s->x11_chanids[i] != -1; i++) {
2735 channel_register_cleanup(s->x11_chanids[i],
2736 session_close_single_x11, 0);
2739 /* Set up a suitable value for the DISPLAY variable. */
2740 if (gethostname(hostname, sizeof(hostname)) < 0)
2741 fatal("gethostname: %.100s", strerror(errno));
2743 * auth_display must be used as the displayname when the
2744 * authorization entry is added with xauth(1). This will be
2745 * different than the DISPLAY string for localhost displays.
2747 if (options.x11_use_localhost) {
2748 snprintf(display, sizeof display, "localhost:%u.%u",
2749 s->display_number, s->screen);
2750 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2751 s->display_number, s->screen);
2752 s->display = xstrdup(display);
2753 s->auth_display = xstrdup(auth_display);
2755 #ifdef IPADDR_IN_DISPLAY
2757 struct in_addr my_addr;
2759 he = gethostbyname(hostname);
2761 error("Can't get IP address for X11 DISPLAY.");
2762 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2765 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2766 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2767 s->display_number, s->screen);
2769 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2770 s->display_number, s->screen);
2772 s->display = xstrdup(display);
2773 s->auth_display = xstrdup(display);
2780 do_authenticated2(Authctxt *authctxt)
2782 server_loop2(authctxt);
2786 do_cleanup(Authctxt *authctxt)
2788 static int called = 0;
2790 debug("do_cleanup");
2792 /* no cleanup if we're in the child for login shell */
2796 /* avoid double cleanup */
2801 if (authctxt == NULL)
2805 if (options.use_pam) {
2807 sshpam_thread_cleanup();
2811 if (!authctxt->authenticated)
2815 if (options.kerberos_ticket_cleanup &&
2817 krb5_cleanup_proc(authctxt);
2821 if (compat20 && options.gss_cleanup_creds)
2822 ssh_gssapi_cleanup_creds();
2825 /* remove agent socket */
2826 auth_sock_cleanup_proc(authctxt->pw);
2829 * Cleanup ptys/utmp only if privsep is disabled,
2830 * or if running in monitor.
2832 if (!use_privsep || mm_is_monitor())
2833 session_destroy_all(session_pty_cleanup2);