1 /* $OpenBSD: session.c,v 1.206 2006/07/06 16:03:53 stevesk 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 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
51 #include <arpa/inet.h>
66 #include "auth-options.h"
67 #include "pathnames.h"
71 #include "serverloop.h"
75 #include "monitor_wrap.h"
77 #if defined(KRB5) && defined(USE_AFS)
87 Session *session_new(void);
88 void session_set_fds(Session *, int, int, int);
89 void session_pty_cleanup(Session *);
90 void session_proctitle(Session *);
91 int session_setup_x11fwd(Session *);
92 void do_exec_pty(Session *, const char *);
93 void do_exec_no_pty(Session *, const char *);
94 void do_exec(Session *, const char *);
95 void do_login(Session *, const char *);
96 #ifdef LOGIN_NEEDS_UTMPX
97 static void do_pre_login(Session *s);
99 void do_child(Session *, const char *);
101 int check_quietlogin(Session *, const char *);
103 static void do_authenticated1(Authctxt *);
104 static void do_authenticated2(Authctxt *);
106 static int session_pty_req(Session *);
109 extern ServerOptions options;
110 extern char *__progname;
111 extern int log_stderr;
112 extern int debug_flag;
113 extern u_int utmp_len;
114 extern int startup_pipe;
115 extern void destroy_sensitive_data(void);
116 extern Buffer loginmsg;
118 /* original command from peer. */
119 const char *original_command = NULL;
122 #define MAX_SESSIONS 10
123 Session sessions[MAX_SESSIONS];
125 #ifdef HAVE_LOGIN_CAP
129 static int is_child = 0;
131 /* Name and directory of socket for authentication agent forwarding. */
132 static char *auth_sock_name = NULL;
133 static char *auth_sock_dir = NULL;
135 /* removes the agent forwarding socket */
138 auth_sock_cleanup_proc(struct passwd *pw)
140 if (auth_sock_name != NULL) {
141 temporarily_use_uid(pw);
142 unlink(auth_sock_name);
143 rmdir(auth_sock_dir);
144 auth_sock_name = NULL;
150 auth_input_request_forwarding(struct passwd * pw)
154 struct sockaddr_un sunaddr;
156 if (auth_sock_name != NULL) {
157 error("authentication forwarding requested twice.");
161 /* Temporarily drop privileged uid for mkdir/bind. */
162 temporarily_use_uid(pw);
164 /* Allocate a buffer for the socket name, and format the name. */
165 auth_sock_name = xmalloc(MAXPATHLEN);
166 auth_sock_dir = xmalloc(MAXPATHLEN);
167 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
169 /* Create private directory for socket */
170 if (mkdtemp(auth_sock_dir) == NULL) {
171 packet_send_debug("Agent forwarding disabled: "
172 "mkdtemp() failed: %.100s", strerror(errno));
174 xfree(auth_sock_name);
175 xfree(auth_sock_dir);
176 auth_sock_name = NULL;
177 auth_sock_dir = NULL;
180 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
181 auth_sock_dir, (long) getpid());
183 /* Create the socket. */
184 sock = socket(AF_UNIX, SOCK_STREAM, 0);
186 packet_disconnect("socket: %.100s", strerror(errno));
188 /* Bind it to the name. */
189 memset(&sunaddr, 0, sizeof(sunaddr));
190 sunaddr.sun_family = AF_UNIX;
191 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
193 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
194 packet_disconnect("bind: %.100s", strerror(errno));
196 /* Restore the privileged uid. */
199 /* Start listening on the socket. */
200 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
201 packet_disconnect("listen: %.100s", strerror(errno));
203 /* Allocate a channel for the authentication agent socket. */
204 nc = channel_new("auth socket",
205 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
206 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
207 0, "auth socket", 1);
208 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
213 display_loginmsg(void)
215 if (buffer_len(&loginmsg) > 0) {
216 buffer_append(&loginmsg, "\0", 1);
217 printf("%s", (char *)buffer_ptr(&loginmsg));
218 buffer_clear(&loginmsg);
223 do_authenticated(Authctxt *authctxt)
225 setproctitle("%s", authctxt->pw->pw_name);
227 /* setup the channel layer */
228 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
229 channel_permit_all_opens();
232 do_authenticated2(authctxt);
234 do_authenticated1(authctxt);
236 do_cleanup(authctxt);
240 * Prepares for an interactive session. This is called after the user has
241 * been successfully authenticated. During this message exchange, pseudo
242 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
243 * are requested, etc.
246 do_authenticated1(Authctxt *authctxt)
250 int success, type, screen_flag;
251 int enable_compression_after_reply = 0;
252 u_int proto_len, data_len, dlen, compression_level = 0;
256 error("no more sessions");
259 s->authctxt = authctxt;
260 s->pw = authctxt->pw;
263 * We stay in this loop until the client requests to execute a shell
269 /* Get a packet from the client. */
270 type = packet_read();
272 /* Process the packet. */
274 case SSH_CMSG_REQUEST_COMPRESSION:
275 compression_level = packet_get_int();
277 if (compression_level < 1 || compression_level > 9) {
278 packet_send_debug("Received invalid compression level %d.",
282 if (options.compression == COMP_NONE) {
283 debug2("compression disabled");
286 /* Enable compression after we have responded with SUCCESS. */
287 enable_compression_after_reply = 1;
291 case SSH_CMSG_REQUEST_PTY:
292 success = session_pty_req(s);
295 case SSH_CMSG_X11_REQUEST_FORWARDING:
296 s->auth_proto = packet_get_string(&proto_len);
297 s->auth_data = packet_get_string(&data_len);
299 screen_flag = packet_get_protocol_flags() &
300 SSH_PROTOFLAG_SCREEN_NUMBER;
301 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
303 if (packet_remaining() == 4) {
305 debug2("Buggy client: "
306 "X11 screen flag missing");
307 s->screen = packet_get_int();
312 success = session_setup_x11fwd(s);
314 xfree(s->auth_proto);
316 s->auth_proto = NULL;
321 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
322 if (no_agent_forwarding_flag || compat13) {
323 debug("Authentication agent forwarding not permitted for this authentication.");
326 debug("Received authentication agent forwarding request.");
327 success = auth_input_request_forwarding(s->pw);
330 case SSH_CMSG_PORT_FORWARD_REQUEST:
331 if (no_port_forwarding_flag) {
332 debug("Port forwarding not permitted for this authentication.");
335 if (!options.allow_tcp_forwarding) {
336 debug("Port forwarding not permitted.");
339 debug("Received TCP/IP port forwarding request.");
340 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
344 case SSH_CMSG_MAX_PACKET_SIZE:
345 if (packet_set_maxsize(packet_get_int()) > 0)
349 case SSH_CMSG_EXEC_SHELL:
350 case SSH_CMSG_EXEC_CMD:
351 if (type == SSH_CMSG_EXEC_CMD) {
352 command = packet_get_string(&dlen);
353 debug("Exec command '%.500s'", command);
365 * Any unknown messages in this phase are ignored,
366 * and a failure message is returned.
368 logit("Unknown packet type received after authentication: %d", type);
370 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
374 /* Enable compression now that we have replied if appropriate. */
375 if (enable_compression_after_reply) {
376 enable_compression_after_reply = 0;
377 packet_start_compression(compression_level);
383 * This is called to fork and execute a command when we have no tty. This
384 * will call do_child from the child, and server_loop from the parent after
385 * setting up file descriptors and such.
388 do_exec_no_pty(Session *s, const char *command)
393 int pin[2], pout[2], perr[2];
394 /* Allocate pipes for communicating with the program. */
395 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
396 packet_disconnect("Could not create pipes: %.100s",
398 #else /* USE_PIPES */
399 int inout[2], err[2];
400 /* Uses socket pairs to communicate with the program. */
401 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
402 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
403 packet_disconnect("Could not create socket pairs: %.100s",
405 #endif /* USE_PIPES */
407 fatal("do_exec_no_pty: no session");
409 session_proctitle(s);
412 if (options.use_pam && !use_privsep)
416 /* Fork the child. */
417 if ((pid = fork()) == 0) {
420 /* Child. Reinitialize the log since the pid has changed. */
421 log_init(__progname, options.log_level, options.log_facility, log_stderr);
424 * Create a new session and process group since the 4.4BSD
425 * setlogin() affects the entire process group.
428 error("setsid failed: %.100s", strerror(errno));
432 * Redirect stdin. We close the parent side of the socket
433 * pair, and make the child side the standard input.
436 if (dup2(pin[0], 0) < 0)
437 perror("dup2 stdin");
440 /* Redirect stdout. */
442 if (dup2(pout[1], 1) < 0)
443 perror("dup2 stdout");
446 /* Redirect stderr. */
448 if (dup2(perr[1], 2) < 0)
449 perror("dup2 stderr");
451 #else /* USE_PIPES */
453 * Redirect stdin, stdout, and stderr. Stdin and stdout will
454 * use the same socket, as some programs (particularly rdist)
455 * seem to depend on it.
459 if (dup2(inout[0], 0) < 0) /* stdin */
460 perror("dup2 stdin");
461 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
462 perror("dup2 stdout");
463 if (dup2(err[0], 2) < 0) /* stderr */
464 perror("dup2 stderr");
465 #endif /* USE_PIPES */
468 cray_init_job(s->pw); /* set up cray jid and tmpdir */
471 /* Do processing for the child (exec command etc). */
472 do_child(s, command);
476 signal(WJSIGNAL, cray_job_termination_handler);
480 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
483 packet_disconnect("fork failed: %.100s", strerror(errno));
485 /* Set interactive/non-interactive mode. */
486 packet_set_interactive(s->display != NULL);
488 /* We are the parent. Close the child sides of the pipes. */
494 if (s->is_subsystem) {
498 session_set_fds(s, pin[1], pout[0], perr[0]);
500 /* Enter the interactive session. */
501 server_loop(pid, pin[1], pout[0], perr[0]);
502 /* server_loop has closed pin[1], pout[0], and perr[0]. */
504 #else /* USE_PIPES */
505 /* We are the parent. Close the child sides of the socket pairs. */
510 * Clear loginmsg, since it's the child's responsibility to display
511 * it to the user, otherwise multiple sessions may accumulate
512 * multiple copies of the login messages.
514 buffer_clear(&loginmsg);
517 * Enter the interactive session. Note: server_loop must be able to
518 * handle the case that fdin and fdout are the same.
521 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
523 server_loop(pid, inout[1], inout[1], err[1]);
524 /* server_loop has closed inout[1] and err[1]. */
526 #endif /* USE_PIPES */
530 * This is called to fork and execute a command when we have a tty. This
531 * will call do_child from the child, and server_loop from the parent after
532 * setting up file descriptors, controlling tty, updating wtmp, utmp,
533 * lastlog, and other such operations.
536 do_exec_pty(Session *s, const char *command)
538 int fdout, ptyfd, ttyfd, ptymaster;
542 fatal("do_exec_pty: no session");
547 if (options.use_pam) {
548 do_pam_set_tty(s->tty);
554 /* Fork the child. */
555 if ((pid = fork()) == 0) {
558 /* Child. Reinitialize the log because the pid has changed. */
559 log_init(__progname, options.log_level, options.log_facility, log_stderr);
560 /* Close the master side of the pseudo tty. */
563 /* Make the pseudo tty our controlling tty. */
564 pty_make_controlling_tty(&ttyfd, s->tty);
566 /* Redirect stdin/stdout/stderr from the pseudo tty. */
567 if (dup2(ttyfd, 0) < 0)
568 error("dup2 stdin: %s", strerror(errno));
569 if (dup2(ttyfd, 1) < 0)
570 error("dup2 stdout: %s", strerror(errno));
571 if (dup2(ttyfd, 2) < 0)
572 error("dup2 stderr: %s", strerror(errno));
574 /* Close the extra descriptor for the pseudo tty. */
577 /* record login, etc. similar to login(1) */
579 if (!(options.use_login && command == NULL)) {
581 cray_init_job(s->pw); /* set up cray jid and tmpdir */
583 do_login(s, command);
585 # ifdef LOGIN_NEEDS_UTMPX
591 /* Do common processing for the child, such as execing the command. */
592 do_child(s, command);
596 signal(WJSIGNAL, cray_job_termination_handler);
600 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
603 packet_disconnect("fork failed: %.100s", strerror(errno));
606 /* Parent. Close the slave side of the pseudo tty. */
610 * Create another descriptor of the pty master side for use as the
611 * standard input. We could use the original descriptor, but this
612 * simplifies code in server_loop. The descriptor is bidirectional.
616 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
618 /* we keep a reference to the pty master */
619 ptymaster = dup(ptyfd);
621 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
622 s->ptymaster = ptymaster;
624 /* Enter interactive session. */
625 packet_set_interactive(1);
627 session_set_fds(s, ptyfd, fdout, -1);
629 server_loop(pid, ptyfd, fdout, -1);
630 /* server_loop _has_ closed ptyfd and fdout. */
634 #ifdef LOGIN_NEEDS_UTMPX
636 do_pre_login(Session *s)
639 struct sockaddr_storage from;
640 pid_t pid = getpid();
643 * Get IP address of client. If the connection is not a socket, let
644 * the address be 0.0.0.0.
646 memset(&from, 0, sizeof(from));
647 fromlen = sizeof(from);
648 if (packet_connection_is_on_socket()) {
649 if (getpeername(packet_get_connection_in(),
650 (struct sockaddr *)&from, &fromlen) < 0) {
651 debug("getpeername: %.100s", strerror(errno));
656 record_utmp_only(pid, s->tty, s->pw->pw_name,
657 get_remote_name_or_ip(utmp_len, options.use_dns),
658 (struct sockaddr *)&from, fromlen);
663 * This is called to fork and execute a command. If another command is
664 * to be forced, execute that instead.
667 do_exec(Session *s, const char *command)
669 if (forced_command) {
670 original_command = command;
671 command = forced_command;
672 debug("Forced command '%.900s'", command);
675 #ifdef SSH_AUDIT_EVENTS
677 PRIVSEP(audit_run_command(command));
678 else if (s->ttyfd == -1) {
679 char *shell = s->pw->pw_shell;
681 if (shell[0] == '\0') /* empty shell means /bin/sh */
683 PRIVSEP(audit_run_command(shell));
688 do_exec_pty(s, command);
690 do_exec_no_pty(s, command);
692 original_command = NULL;
695 * Clear loginmsg: it's the child's responsibility to display
696 * it to the user, otherwise multiple sessions may accumulate
697 * multiple copies of the login messages.
699 buffer_clear(&loginmsg);
702 /* administrative, login(1)-like work */
704 do_login(Session *s, const char *command)
707 struct sockaddr_storage from;
708 struct passwd * pw = s->pw;
709 pid_t pid = getpid();
712 * Get IP address of client. If the connection is not a socket, let
713 * the address be 0.0.0.0.
715 memset(&from, 0, sizeof(from));
716 fromlen = sizeof(from);
717 if (packet_connection_is_on_socket()) {
718 if (getpeername(packet_get_connection_in(),
719 (struct sockaddr *) & from, &fromlen) < 0) {
720 debug("getpeername: %.100s", strerror(errno));
725 /* Record that there was a login on that tty from the remote host. */
727 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
728 get_remote_name_or_ip(utmp_len,
730 (struct sockaddr *)&from, fromlen);
734 * If password change is needed, do it now.
735 * This needs to occur before the ~/.hushlogin check.
737 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
740 s->authctxt->force_pwchange = 0;
741 /* XXX - signal [net] parent to enable forwardings */
745 if (check_quietlogin(s, command))
754 * Display the message of the day.
762 if (options.print_motd) {
763 #ifdef HAVE_LOGIN_CAP
764 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
767 f = fopen("/etc/motd", "r");
770 while (fgets(buf, sizeof(buf), f))
779 * Check for quiet login, either .hushlogin or command given.
782 check_quietlogin(Session *s, const char *command)
785 struct passwd *pw = s->pw;
788 /* Return 1 if .hushlogin exists or a command given. */
791 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
792 #ifdef HAVE_LOGIN_CAP
793 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
796 if (stat(buf, &st) >= 0)
803 * Sets the value of the given variable in the environment. If the variable
804 * already exists, its value is overriden.
807 child_set_env(char ***envp, u_int *envsizep, const char *name,
815 * If we're passed an uninitialized list, allocate a single null
816 * entry before continuing.
818 if (*envp == NULL && *envsizep == 0) {
819 *envp = xmalloc(sizeof(char *));
825 * Find the slot where the value should be stored. If the variable
826 * already exists, we reuse the slot; otherwise we append a new slot
827 * at the end of the array, expanding if necessary.
830 namelen = strlen(name);
831 for (i = 0; env[i]; i++)
832 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
835 /* Reuse the slot. */
838 /* New variable. Expand if necessary. */
840 if (i >= envsize - 1) {
842 fatal("child_set_env: too many env vars");
844 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
847 /* Need to set the NULL pointer at end of array beyond the new slot. */
851 /* Allocate space and format the variable in the appropriate slot. */
852 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
853 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
857 * Reads environment variables from the given file and adds/overrides them
858 * into the environment. If the file does not exist, this does nothing.
859 * Otherwise, it must consist of empty lines, comments (line starts with '#')
860 * and assignments of the form name=value. No other forms are allowed.
863 read_environment_file(char ***env, u_int *envsize,
864 const char *filename)
871 f = fopen(filename, "r");
875 while (fgets(buf, sizeof(buf), f)) {
877 fatal("Too many lines in environment file %s", filename);
878 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
880 if (!*cp || *cp == '#' || *cp == '\n')
882 if (strchr(cp, '\n'))
883 *strchr(cp, '\n') = '\0';
884 value = strchr(cp, '=');
886 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
891 * Replace the equals sign by nul, and advance value to
896 child_set_env(env, envsize, cp, value);
901 #ifdef HAVE_ETC_DEFAULT_LOGIN
903 * Return named variable from specified environment, or NULL if not present.
906 child_get_env(char **env, const char *name)
912 for (i=0; env[i] != NULL; i++)
913 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
914 return(env[i] + len + 1);
919 * Read /etc/default/login.
920 * We pick up the PATH (or SUPATH for root) and UMASK.
923 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
925 char **tmpenv = NULL, *var;
926 u_int i, tmpenvsize = 0;
930 * We don't want to copy the whole file to the child's environment,
931 * so we use a temporary environment and copy the variables we're
934 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
940 var = child_get_env(tmpenv, "SUPATH");
942 var = child_get_env(tmpenv, "PATH");
944 child_set_env(env, envsize, "PATH", var);
946 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
947 if (sscanf(var, "%5lo", &mask) == 1)
950 for (i = 0; tmpenv[i] != NULL; i++)
954 #endif /* HAVE_ETC_DEFAULT_LOGIN */
957 copy_environment(char **source, char ***env, u_int *envsize)
959 char *var_name, *var_val;
965 for(i = 0; source[i] != NULL; i++) {
966 var_name = xstrdup(source[i]);
967 if ((var_val = strstr(var_name, "=")) == NULL) {
973 debug3("Copy environment: %s=%s", var_name, var_val);
974 child_set_env(env, envsize, var_name, var_val);
981 do_setup_env(Session *s, const char *shell)
985 char **env, *laddr, *path = NULL;
986 struct passwd *pw = s->pw;
988 /* Initialize the environment. */
990 env = xcalloc(envsize, sizeof(char *));
995 * The Windows environment contains some setting which are
996 * important for a running system. They must not be dropped.
1001 p = fetch_windows_environment();
1002 copy_environment(p, &env, &envsize);
1003 free_windows_environment(p);
1008 /* Allow any GSSAPI methods that we've used to alter
1009 * the childs environment as they see fit
1011 ssh_gssapi_do_child(&env, &envsize);
1014 if (!options.use_login) {
1015 /* Set basic environment. */
1016 for (i = 0; i < s->num_env; i++)
1017 child_set_env(&env, &envsize, s->env[i].name,
1020 child_set_env(&env, &envsize, "USER", pw->pw_name);
1021 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1023 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1025 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1026 #ifdef HAVE_LOGIN_CAP
1027 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1028 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1030 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1031 #else /* HAVE_LOGIN_CAP */
1032 # ifndef HAVE_CYGWIN
1034 * There's no standard path on Windows. The path contains
1035 * important components pointing to the system directories,
1036 * needed for loading shared libraries. So the path better
1037 * remains intact here.
1039 # ifdef HAVE_ETC_DEFAULT_LOGIN
1040 read_etc_default_login(&env, &envsize, pw->pw_uid);
1041 path = child_get_env(env, "PATH");
1042 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1043 if (path == NULL || *path == '\0') {
1044 child_set_env(&env, &envsize, "PATH",
1045 s->pw->pw_uid == 0 ?
1046 SUPERUSER_PATH : _PATH_STDPATH);
1048 # endif /* HAVE_CYGWIN */
1049 #endif /* HAVE_LOGIN_CAP */
1051 snprintf(buf, sizeof buf, "%.200s/%.50s",
1052 _PATH_MAILDIR, pw->pw_name);
1053 child_set_env(&env, &envsize, "MAIL", buf);
1055 /* Normal systems set SHELL by default. */
1056 child_set_env(&env, &envsize, "SHELL", shell);
1059 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1061 /* Set custom environment options from RSA authentication. */
1062 if (!options.use_login) {
1063 while (custom_environment) {
1064 struct envstring *ce = custom_environment;
1067 for (i = 0; str[i] != '=' && str[i]; i++)
1069 if (str[i] == '=') {
1071 child_set_env(&env, &envsize, str, str + i + 1);
1073 custom_environment = ce->next;
1079 /* SSH_CLIENT deprecated */
1080 snprintf(buf, sizeof buf, "%.50s %d %d",
1081 get_remote_ipaddr(), get_remote_port(), get_local_port());
1082 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1084 laddr = get_local_ipaddr(packet_get_connection_in());
1085 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1086 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1088 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1091 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1093 child_set_env(&env, &envsize, "TERM", s->term);
1095 child_set_env(&env, &envsize, "DISPLAY", s->display);
1096 if (original_command)
1097 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1101 if (cray_tmpdir[0] != '\0')
1102 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1103 #endif /* _UNICOS */
1106 * Since we clear KRB5CCNAME at startup, if it's set now then it
1107 * must have been set by a native authentication method (eg AIX or
1108 * SIA), so copy it to the child.
1113 if ((cp = getenv("KRB5CCNAME")) != NULL)
1114 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1121 if ((cp = getenv("AUTHSTATE")) != NULL)
1122 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1123 read_environment_file(&env, &envsize, "/etc/environment");
1127 if (s->authctxt->krb5_ccname)
1128 child_set_env(&env, &envsize, "KRB5CCNAME",
1129 s->authctxt->krb5_ccname);
1133 * Pull in any environment variables that may have
1136 if (options.use_pam) {
1139 p = fetch_pam_child_environment();
1140 copy_environment(p, &env, &envsize);
1141 free_pam_environment(p);
1143 p = fetch_pam_environment();
1144 copy_environment(p, &env, &envsize);
1145 free_pam_environment(p);
1147 #endif /* USE_PAM */
1149 if (auth_sock_name != NULL)
1150 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1153 /* read $HOME/.ssh/environment. */
1154 if (options.permit_user_env && !options.use_login) {
1155 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1156 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1157 read_environment_file(&env, &envsize, buf);
1160 /* dump the environment */
1161 fprintf(stderr, "Environment:\n");
1162 for (i = 0; env[i]; i++)
1163 fprintf(stderr, " %.200s\n", env[i]);
1169 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1170 * first in this order).
1173 do_rc_files(Session *s, const char *shell)
1181 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1183 /* ignore _PATH_SSH_USER_RC for subsystems */
1184 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1185 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1186 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1188 fprintf(stderr, "Running %s\n", cmd);
1189 f = popen(cmd, "w");
1192 fprintf(f, "%s %s\n", s->auth_proto,
1196 fprintf(stderr, "Could not run %s\n",
1198 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1200 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1201 _PATH_SSH_SYSTEM_RC);
1202 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1205 fprintf(f, "%s %s\n", s->auth_proto,
1209 fprintf(stderr, "Could not run %s\n",
1210 _PATH_SSH_SYSTEM_RC);
1211 } else if (do_xauth && options.xauth_location != NULL) {
1212 /* Add authority data to .Xauthority if appropriate. */
1215 "Running %.500s remove %.100s\n",
1216 options.xauth_location, s->auth_display);
1218 "%.500s add %.100s %.100s %.100s\n",
1219 options.xauth_location, s->auth_display,
1220 s->auth_proto, s->auth_data);
1222 snprintf(cmd, sizeof cmd, "%s -q -",
1223 options.xauth_location);
1224 f = popen(cmd, "w");
1226 fprintf(f, "remove %s\n",
1228 fprintf(f, "add %s %s %s\n",
1229 s->auth_display, s->auth_proto,
1233 fprintf(stderr, "Could not run %s\n",
1240 do_nologin(struct passwd *pw)
1245 #ifdef HAVE_LOGIN_CAP
1246 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1247 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1248 _PATH_NOLOGIN), "r");
1251 f = fopen(_PATH_NOLOGIN, "r");
1254 /* /etc/nologin exists. Print its contents and exit. */
1255 logit("User %.100s not allowed because %s exists",
1256 pw->pw_name, _PATH_NOLOGIN);
1257 while (fgets(buf, sizeof(buf), f))
1265 /* Set login name, uid, gid, and groups. */
1267 do_setusercontext(struct passwd *pw)
1270 if (getuid() == 0 || geteuid() == 0)
1271 #endif /* HAVE_CYGWIN */
1274 #ifdef HAVE_SETPCRED
1275 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1276 fatal("Failed to set process credentials");
1277 #endif /* HAVE_SETPCRED */
1278 #ifdef HAVE_LOGIN_CAP
1283 if (options.gss_authentication) {
1284 temporarily_use_uid(pw);
1285 ssh_gssapi_storecreds();
1290 if (options.use_pam) {
1294 # endif /* USE_PAM */
1295 if (setusercontext(lc, pw, pw->pw_uid,
1296 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1297 perror("unable to set user context");
1301 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1302 /* Sets login uid for accounting */
1303 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1304 error("setluid: %s", strerror(errno));
1305 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1307 if (setlogin(pw->pw_name) < 0)
1308 error("setlogin failed: %s", strerror(errno));
1309 if (setgid(pw->pw_gid) < 0) {
1313 /* Initialize the group list. */
1314 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1315 perror("initgroups");
1320 if (options.gss_authentication) {
1321 temporarily_use_uid(pw);
1322 ssh_gssapi_storecreds();
1328 * PAM credentials may take the form of supplementary groups.
1329 * These will have been wiped by the above initgroups() call.
1330 * Reestablish them here.
1332 if (options.use_pam) {
1336 # endif /* USE_PAM */
1337 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1338 irix_setusercontext(pw);
1339 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1343 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1344 if (set_id(pw->pw_name) != 0) {
1347 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1348 /* Permanently switch to the desired uid. */
1349 permanently_set_uid(pw);
1356 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1357 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1360 ssh_selinux_setup_exec_context(pw->pw_name);
1365 do_pwchange(Session *s)
1368 fprintf(stderr, "WARNING: Your password has expired.\n");
1369 if (s->ttyfd != -1) {
1371 "You must change your password now and login again!\n");
1372 #ifdef PASSWD_NEEDS_USERNAME
1373 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1376 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1381 "Password change required but no TTY available.\n");
1387 launch_login(struct passwd *pw, const char *hostname)
1389 /* Launch login(1). */
1391 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1392 #ifdef xxxLOGIN_NEEDS_TERM
1393 (s->term ? s->term : "unknown"),
1394 #endif /* LOGIN_NEEDS_TERM */
1395 #ifdef LOGIN_NO_ENDOPT
1396 "-p", "-f", pw->pw_name, (char *)NULL);
1398 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1401 /* Login couldn't be executed, die. */
1408 child_close_fds(void)
1412 if (packet_get_connection_in() == packet_get_connection_out())
1413 close(packet_get_connection_in());
1415 close(packet_get_connection_in());
1416 close(packet_get_connection_out());
1419 * Close all descriptors related to channels. They will still remain
1420 * open in the parent.
1422 /* XXX better use close-on-exec? -markus */
1423 channel_close_all();
1426 * Close any extra file descriptors. Note that there may still be
1427 * descriptors left by system functions. They will be closed later.
1432 * Close any extra open file descriptors so that we don't have them
1433 * hanging around in clients. Note that we want to do this after
1434 * initgroups, because at least on Solaris 2.3 it leaves file
1437 for (i = 3; i < 64; i++)
1442 * Performs common processing for the child, such as setting up the
1443 * environment, closing extra file descriptors, setting the user and group
1444 * ids, and executing the command or shell.
1447 do_child(Session *s, const char *command)
1449 extern char **environ;
1452 const char *shell, *shell0, *hostname = NULL;
1453 struct passwd *pw = s->pw;
1455 /* remove hostkey from the child's memory */
1456 destroy_sensitive_data();
1458 /* Force a password change */
1459 if (s->authctxt->force_pwchange) {
1460 do_setusercontext(pw);
1466 /* login(1) is only called if we execute the login shell */
1467 if (options.use_login && command != NULL)
1468 options.use_login = 0;
1471 cray_setup(pw->pw_uid, pw->pw_name, command);
1472 #endif /* _UNICOS */
1475 * Login(1) does this as well, and it needs uid 0 for the "-h"
1476 * switch, so we let login(1) to this for us.
1478 if (!options.use_login) {
1480 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1481 if (!check_quietlogin(s, command))
1483 #else /* HAVE_OSF_SIA */
1484 /* When PAM is enabled we rely on it to do the nologin check */
1485 if (!options.use_pam)
1487 do_setusercontext(pw);
1489 * PAM session modules in do_setusercontext may have
1490 * generated messages, so if this in an interactive
1491 * login then display them too.
1493 if (!check_quietlogin(s, command))
1495 #endif /* HAVE_OSF_SIA */
1499 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1500 debug3("PAM session not opened, exiting");
1507 * Get the shell from the password data. An empty shell field is
1508 * legal, and means /bin/sh.
1510 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1513 * Make sure $SHELL points to the shell from the password file,
1514 * even if shell is overridden from login.conf
1516 env = do_setup_env(s, shell);
1518 #ifdef HAVE_LOGIN_CAP
1519 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1522 /* we have to stash the hostname before we close our socket. */
1523 if (options.use_login)
1524 hostname = get_remote_name_or_ip(utmp_len,
1527 * Close the connection descriptors; note that this is the child, and
1528 * the server will still have the socket open, and it is important
1529 * that we do not shutdown it. Note that the descriptors cannot be
1530 * closed before building the environment, as we call
1531 * get_remote_ipaddr there.
1536 * Must take new environment into use so that .ssh/rc,
1537 * /etc/ssh/sshrc and xauth are run in the proper environment.
1541 #if defined(KRB5) && defined(USE_AFS)
1543 * At this point, we check to see if AFS is active and if we have
1544 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1545 * if we can (and need to) extend the ticket into an AFS token. If
1546 * we don't do this, we run into potential problems if the user's
1547 * home directory is in AFS and it's not world-readable.
1550 if (options.kerberos_get_afs_token && k_hasafs() &&
1551 (s->authctxt->krb5_ctx != NULL)) {
1554 debug("Getting AFS token");
1558 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1559 krb5_afslog(s->authctxt->krb5_ctx,
1560 s->authctxt->krb5_fwd_ccache, cell, NULL);
1562 krb5_afslog_home(s->authctxt->krb5_ctx,
1563 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1567 /* Change current directory to the user's home directory. */
1568 if (chdir(pw->pw_dir) < 0) {
1569 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1570 pw->pw_dir, strerror(errno));
1571 #ifdef HAVE_LOGIN_CAP
1572 if (login_getcapbool(lc, "requirehome", 0))
1577 if (!options.use_login)
1578 do_rc_files(s, shell);
1580 /* restore SIGPIPE for child */
1581 signal(SIGPIPE, SIG_DFL);
1583 if (options.use_login) {
1584 launch_login(pw, hostname);
1588 /* Get the last component of the shell name. */
1589 if ((shell0 = strrchr(shell, '/')) != NULL)
1595 * If we have no command, execute the shell. In this case, the shell
1596 * name to be passed in argv[0] is preceded by '-' to indicate that
1597 * this is a login shell.
1602 /* Start the shell. Set initial character to '-'. */
1605 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1606 >= sizeof(argv0) - 1) {
1612 /* Execute the shell. */
1615 execve(shell, argv, env);
1617 /* Executing the shell failed. */
1622 * Execute the command using the user's shell. This uses the -c
1623 * option to execute the command.
1625 argv[0] = (char *) shell0;
1627 argv[2] = (char *) command;
1629 execve(shell, argv, env);
1638 static int did_init = 0;
1640 debug("session_new: init");
1641 for (i = 0; i < MAX_SESSIONS; i++) {
1642 sessions[i].used = 0;
1646 for (i = 0; i < MAX_SESSIONS; i++) {
1647 Session *s = &sessions[i];
1649 memset(s, 0, sizeof(*s));
1655 s->x11_chanids = NULL;
1656 debug("session_new: session %d", i);
1667 for (i = 0; i < MAX_SESSIONS; i++) {
1668 Session *s = &sessions[i];
1669 debug("dump: used %d session %d %p channel %d pid %ld",
1679 session_open(Authctxt *authctxt, int chanid)
1681 Session *s = session_new();
1682 debug("session_open: channel %d", chanid);
1684 error("no more sessions");
1687 s->authctxt = authctxt;
1688 s->pw = authctxt->pw;
1689 if (s->pw == NULL || !authctxt->valid)
1690 fatal("no user for session %d", s->self);
1691 debug("session_open: session %d: link with channel %d", s->self, chanid);
1697 session_by_tty(char *tty)
1700 for (i = 0; i < MAX_SESSIONS; i++) {
1701 Session *s = &sessions[i];
1702 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1703 debug("session_by_tty: session %d tty %s", i, tty);
1707 debug("session_by_tty: unknown tty %.100s", tty);
1713 session_by_channel(int id)
1716 for (i = 0; i < MAX_SESSIONS; i++) {
1717 Session *s = &sessions[i];
1718 if (s->used && s->chanid == id) {
1719 debug("session_by_channel: session %d channel %d", i, id);
1723 debug("session_by_channel: unknown channel %d", id);
1729 session_by_x11_channel(int id)
1733 for (i = 0; i < MAX_SESSIONS; i++) {
1734 Session *s = &sessions[i];
1736 if (s->x11_chanids == NULL || !s->used)
1738 for (j = 0; s->x11_chanids[j] != -1; j++) {
1739 if (s->x11_chanids[j] == id) {
1740 debug("session_by_x11_channel: session %d "
1741 "channel %d", s->self, id);
1746 debug("session_by_x11_channel: unknown channel %d", id);
1752 session_by_pid(pid_t pid)
1755 debug("session_by_pid: pid %ld", (long)pid);
1756 for (i = 0; i < MAX_SESSIONS; i++) {
1757 Session *s = &sessions[i];
1758 if (s->used && s->pid == pid)
1761 error("session_by_pid: unknown pid %ld", (long)pid);
1767 session_window_change_req(Session *s)
1769 s->col = packet_get_int();
1770 s->row = packet_get_int();
1771 s->xpixel = packet_get_int();
1772 s->ypixel = packet_get_int();
1774 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1779 session_pty_req(Session *s)
1785 debug("Allocating a pty not permitted for this authentication.");
1788 if (s->ttyfd != -1) {
1789 packet_disconnect("Protocol error: you already have a pty.");
1793 s->term = packet_get_string(&len);
1796 s->col = packet_get_int();
1797 s->row = packet_get_int();
1799 s->row = packet_get_int();
1800 s->col = packet_get_int();
1802 s->xpixel = packet_get_int();
1803 s->ypixel = packet_get_int();
1805 if (strcmp(s->term, "") == 0) {
1810 /* Allocate a pty and open it. */
1811 debug("Allocating pty.");
1812 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1818 error("session_pty_req: session %d alloc failed", s->self);
1821 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1823 /* for SSH1 the tty modes length is not given */
1825 n_bytes = packet_remaining();
1826 tty_parse_modes(s->ttyfd, &n_bytes);
1829 pty_setowner(s->pw, s->tty);
1831 /* Set window size from the packet. */
1832 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1835 session_proctitle(s);
1840 session_subsystem_req(Session *s)
1845 char *prog, *cmd, *subsys = packet_get_string(&len);
1849 logit("subsystem request for %.100s", subsys);
1851 for (i = 0; i < options.num_subsystems; i++) {
1852 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1853 prog = options.subsystem_command[i];
1854 cmd = options.subsystem_args[i];
1855 if (stat(prog, &st) < 0) {
1856 error("subsystem: cannot stat %s: %s", prog,
1860 debug("subsystem: exec() %s", cmd);
1861 s->is_subsystem = 1;
1869 logit("subsystem request for %.100s failed, subsystem not found",
1877 session_x11_req(Session *s)
1881 if (s->auth_proto != NULL || s->auth_data != NULL) {
1882 error("session_x11_req: session %d: "
1883 "x11 forwarding already active", s->self);
1886 s->single_connection = packet_get_char();
1887 s->auth_proto = packet_get_string(NULL);
1888 s->auth_data = packet_get_string(NULL);
1889 s->screen = packet_get_int();
1892 success = session_setup_x11fwd(s);
1894 xfree(s->auth_proto);
1895 xfree(s->auth_data);
1896 s->auth_proto = NULL;
1897 s->auth_data = NULL;
1903 session_shell_req(Session *s)
1911 session_exec_req(Session *s)
1914 char *command = packet_get_string(&len);
1916 do_exec(s, command);
1922 session_break_req(Session *s)
1925 packet_get_int(); /* ignored */
1928 if (s->ttyfd == -1 ||
1929 tcsendbreak(s->ttyfd, 0) < 0)
1935 session_env_req(Session *s)
1938 u_int name_len, val_len, i;
1940 name = packet_get_string(&name_len);
1941 val = packet_get_string(&val_len);
1944 /* Don't set too many environment variables */
1945 if (s->num_env > 128) {
1946 debug2("Ignoring env request %s: too many env vars", name);
1950 for (i = 0; i < options.num_accept_env; i++) {
1951 if (match_pattern(name, options.accept_env[i])) {
1952 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1953 s->env = xrealloc(s->env, s->num_env + 1,
1955 s->env[s->num_env].name = name;
1956 s->env[s->num_env].val = val;
1961 debug2("Ignoring env request %s: disallowed name", name);
1970 session_auth_agent_req(Session *s)
1972 static int called = 0;
1974 if (no_agent_forwarding_flag) {
1975 debug("session_auth_agent_req: no_agent_forwarding_flag");
1982 return auth_input_request_forwarding(s->pw);
1987 session_input_channel_req(Channel *c, const char *rtype)
1992 if ((s = session_by_channel(c->self)) == NULL) {
1993 logit("session_input_channel_req: no session %d req %.100s",
1997 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2000 * a session is in LARVAL state until a shell, a command
2001 * or a subsystem is executed
2003 if (c->type == SSH_CHANNEL_LARVAL) {
2004 if (strcmp(rtype, "shell") == 0) {
2005 success = session_shell_req(s);
2006 } else if (strcmp(rtype, "exec") == 0) {
2007 success = session_exec_req(s);
2008 } else if (strcmp(rtype, "pty-req") == 0) {
2009 success = session_pty_req(s);
2010 } else if (strcmp(rtype, "x11-req") == 0) {
2011 success = session_x11_req(s);
2012 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2013 success = session_auth_agent_req(s);
2014 } else if (strcmp(rtype, "subsystem") == 0) {
2015 success = session_subsystem_req(s);
2016 } else if (strcmp(rtype, "env") == 0) {
2017 success = session_env_req(s);
2020 if (strcmp(rtype, "window-change") == 0) {
2021 success = session_window_change_req(s);
2022 } else if (strcmp(rtype, "break") == 0) {
2023 success = session_break_req(s);
2030 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2033 fatal("session_set_fds: called for proto != 2.0");
2035 * now that have a child and a pipe to the child,
2036 * we can activate our channel and register the fd's
2038 if (s->chanid == -1)
2039 fatal("no channel for session %d", s->self);
2040 channel_set_fds(s->chanid,
2042 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2044 CHAN_SES_WINDOW_DEFAULT);
2048 * Function to perform pty cleanup. Also called if we get aborted abnormally
2049 * (e.g., due to a dropped connection).
2052 session_pty_cleanup2(Session *s)
2055 error("session_pty_cleanup: no session");
2061 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2063 /* Record that the user has logged out. */
2065 record_logout(s->pid, s->tty, s->pw->pw_name);
2067 /* Release the pseudo-tty. */
2069 pty_release(s->tty);
2072 * Close the server side of the socket pairs. We must do this after
2073 * the pty cleanup, so that another process doesn't get this pty
2074 * while we're still cleaning up.
2076 if (close(s->ptymaster) < 0)
2077 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2079 /* unlink pty from session */
2084 session_pty_cleanup(Session *s)
2086 PRIVSEP(session_pty_cleanup2(s));
2092 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2107 return "SIG@openssh.com";
2111 session_close_x11(int id)
2115 if ((c = channel_by_id(id)) == NULL) {
2116 debug("session_close_x11: x11 channel %d missing", id);
2118 /* Detach X11 listener */
2119 debug("session_close_x11: detach x11 channel %d", id);
2120 channel_cancel_cleanup(id);
2121 if (c->ostate != CHAN_OUTPUT_CLOSED)
2127 session_close_single_x11(int id, void *arg)
2132 debug3("session_close_single_x11: channel %d", id);
2133 channel_cancel_cleanup(id);
2134 if ((s = session_by_x11_channel(id)) == NULL)
2135 fatal("session_close_single_x11: no x11 channel %d", id);
2136 for (i = 0; s->x11_chanids[i] != -1; i++) {
2137 debug("session_close_single_x11: session %d: "
2138 "closing channel %d", s->self, s->x11_chanids[i]);
2140 * The channel "id" is already closing, but make sure we
2141 * close all of its siblings.
2143 if (s->x11_chanids[i] != id)
2144 session_close_x11(s->x11_chanids[i]);
2146 xfree(s->x11_chanids);
2147 s->x11_chanids = NULL;
2152 if (s->auth_proto) {
2153 xfree(s->auth_proto);
2154 s->auth_proto = NULL;
2157 xfree(s->auth_data);
2158 s->auth_data = NULL;
2160 if (s->auth_display) {
2161 xfree(s->auth_display);
2162 s->auth_display = NULL;
2167 session_exit_message(Session *s, int status)
2171 if ((c = channel_lookup(s->chanid)) == NULL)
2172 fatal("session_exit_message: session %d: no channel %d",
2173 s->self, s->chanid);
2174 debug("session_exit_message: session %d channel %d pid %ld",
2175 s->self, s->chanid, (long)s->pid);
2177 if (WIFEXITED(status)) {
2178 channel_request_start(s->chanid, "exit-status", 0);
2179 packet_put_int(WEXITSTATUS(status));
2181 } else if (WIFSIGNALED(status)) {
2182 channel_request_start(s->chanid, "exit-signal", 0);
2183 packet_put_cstring(sig2name(WTERMSIG(status)));
2185 packet_put_char(WCOREDUMP(status));
2186 #else /* WCOREDUMP */
2188 #endif /* WCOREDUMP */
2189 packet_put_cstring("");
2190 packet_put_cstring("");
2193 /* Some weird exit cause. Just exit. */
2194 packet_disconnect("wait returned status %04x.", status);
2197 /* disconnect channel */
2198 debug("session_exit_message: release channel %d", s->chanid);
2201 * Adjust cleanup callback attachment to send close messages when
2202 * the channel gets EOF. The session will be then be closed
2203 * by session_close_by_channel when the childs close their fds.
2205 channel_register_cleanup(c->self, session_close_by_channel, 1);
2208 * emulate a write failure with 'chan_write_failed', nobody will be
2209 * interested in data we write.
2210 * Note that we must not call 'chan_read_failed', since there could
2211 * be some more data waiting in the pipe.
2213 if (c->ostate != CHAN_OUTPUT_CLOSED)
2214 chan_write_failed(c);
2218 session_close(Session *s)
2222 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2224 session_pty_cleanup(s);
2230 xfree(s->x11_chanids);
2231 if (s->auth_display)
2232 xfree(s->auth_display);
2234 xfree(s->auth_data);
2236 xfree(s->auth_proto);
2238 for (i = 0; i < s->num_env; i++) {
2239 xfree(s->env[i].name);
2240 xfree(s->env[i].val);
2244 session_proctitle(s);
2248 session_close_by_pid(pid_t pid, int status)
2250 Session *s = session_by_pid(pid);
2252 debug("session_close_by_pid: no session for pid %ld",
2256 if (s->chanid != -1)
2257 session_exit_message(s, status);
2259 session_pty_cleanup(s);
2264 * this is called when a channel dies before
2265 * the session 'child' itself dies
2268 session_close_by_channel(int id, void *arg)
2270 Session *s = session_by_channel(id);
2274 debug("session_close_by_channel: no session for id %d", id);
2277 debug("session_close_by_channel: channel %d child %ld",
2280 debug("session_close_by_channel: channel %d: has child", id);
2282 * delay detach of session, but release pty, since
2283 * the fd's to the child are already closed
2286 session_pty_cleanup(s);
2289 /* detach by removing callback */
2290 channel_cancel_cleanup(s->chanid);
2292 /* Close any X11 listeners associated with this session */
2293 if (s->x11_chanids != NULL) {
2294 for (i = 0; s->x11_chanids[i] != -1; i++) {
2295 session_close_x11(s->x11_chanids[i]);
2296 s->x11_chanids[i] = -1;
2305 session_destroy_all(void (*closefunc)(Session *))
2308 for (i = 0; i < MAX_SESSIONS; i++) {
2309 Session *s = &sessions[i];
2311 if (closefunc != NULL)
2320 session_tty_list(void)
2322 static char buf[1024];
2327 for (i = 0; i < MAX_SESSIONS; i++) {
2328 Session *s = &sessions[i];
2329 if (s->used && s->ttyfd != -1) {
2331 if (strncmp(s->tty, "/dev/", 5) != 0) {
2332 cp = strrchr(s->tty, '/');
2333 cp = (cp == NULL) ? s->tty : cp + 1;
2338 strlcat(buf, ",", sizeof buf);
2339 strlcat(buf, cp, sizeof buf);
2343 strlcpy(buf, "notty", sizeof buf);
2348 session_proctitle(Session *s)
2351 error("no user for session %d", s->self);
2353 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2357 session_setup_x11fwd(Session *s)
2360 char display[512], auth_display[512];
2361 char hostname[MAXHOSTNAMELEN];
2364 if (no_x11_forwarding_flag) {
2365 packet_send_debug("X11 forwarding disabled in user configuration file.");
2368 if (!options.x11_forwarding) {
2369 debug("X11 forwarding disabled in server configuration file.");
2372 if (!options.xauth_location ||
2373 (stat(options.xauth_location, &st) == -1)) {
2374 packet_send_debug("No xauth program; cannot forward with spoofing.");
2377 if (options.use_login) {
2378 packet_send_debug("X11 forwarding disabled; "
2379 "not compatible with UseLogin=yes.");
2382 if (s->display != NULL) {
2383 debug("X11 display already set.");
2386 if (x11_create_display_inet(options.x11_display_offset,
2387 options.x11_use_localhost, s->single_connection,
2388 &s->display_number, &s->x11_chanids) == -1) {
2389 debug("x11_create_display_inet failed.");
2392 for (i = 0; s->x11_chanids[i] != -1; i++) {
2393 channel_register_cleanup(s->x11_chanids[i],
2394 session_close_single_x11, 0);
2397 /* Set up a suitable value for the DISPLAY variable. */
2398 if (gethostname(hostname, sizeof(hostname)) < 0)
2399 fatal("gethostname: %.100s", strerror(errno));
2401 * auth_display must be used as the displayname when the
2402 * authorization entry is added with xauth(1). This will be
2403 * different than the DISPLAY string for localhost displays.
2405 if (options.x11_use_localhost) {
2406 snprintf(display, sizeof display, "localhost:%u.%u",
2407 s->display_number, s->screen);
2408 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2409 s->display_number, s->screen);
2410 s->display = xstrdup(display);
2411 s->auth_display = xstrdup(auth_display);
2413 #ifdef IPADDR_IN_DISPLAY
2415 struct in_addr my_addr;
2417 he = gethostbyname(hostname);
2419 error("Can't get IP address for X11 DISPLAY.");
2420 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2423 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2424 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2425 s->display_number, s->screen);
2427 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2428 s->display_number, s->screen);
2430 s->display = xstrdup(display);
2431 s->auth_display = xstrdup(display);
2438 do_authenticated2(Authctxt *authctxt)
2440 server_loop2(authctxt);
2444 do_cleanup(Authctxt *authctxt)
2446 static int called = 0;
2448 debug("do_cleanup");
2450 /* no cleanup if we're in the child for login shell */
2454 /* avoid double cleanup */
2459 if (authctxt == NULL)
2462 if (options.kerberos_ticket_cleanup &&
2464 krb5_cleanup_proc(authctxt);
2468 if (compat20 && options.gss_cleanup_creds)
2469 ssh_gssapi_cleanup_creds();
2473 if (options.use_pam) {
2475 sshpam_thread_cleanup();
2479 /* remove agent socket */
2480 auth_sock_cleanup_proc(authctxt->pw);
2483 * Cleanup ptys/utmp only if privsep is disabled,
2484 * or if running in monitor.
2486 if (!use_privsep || mm_is_monitor())
2487 session_destroy_all(session_pty_cleanup2);