1 /* $OpenBSD: session.c,v 1.215 2006/08/01 23:22:47 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 #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>
74 #include "auth-options.h"
75 #include "pathnames.h"
79 #include "serverloop.h"
83 #include "monitor_wrap.h"
85 #if defined(KRB5) && defined(USE_AFS)
95 Session *session_new(void);
96 void session_set_fds(Session *, int, int, int);
97 void session_pty_cleanup(Session *);
98 void session_proctitle(Session *);
99 int session_setup_x11fwd(Session *);
100 void do_exec_pty(Session *, const char *);
101 void do_exec_no_pty(Session *, const char *);
102 void do_exec(Session *, const char *);
103 void do_login(Session *, const char *);
104 #ifdef LOGIN_NEEDS_UTMPX
105 static void do_pre_login(Session *s);
107 void do_child(Session *, const char *);
109 int check_quietlogin(Session *, const char *);
111 static void do_authenticated1(Authctxt *);
112 static void do_authenticated2(Authctxt *);
114 static int session_pty_req(Session *);
117 extern ServerOptions options;
118 extern char *__progname;
119 extern int log_stderr;
120 extern int debug_flag;
121 extern u_int utmp_len;
122 extern int startup_pipe;
123 extern void destroy_sensitive_data(void);
124 extern Buffer loginmsg;
126 /* original command from peer. */
127 const char *original_command = NULL;
130 #define MAX_SESSIONS 10
131 Session sessions[MAX_SESSIONS];
133 #ifdef HAVE_LOGIN_CAP
137 static int is_child = 0;
139 /* Name and directory of socket for authentication agent forwarding. */
140 static char *auth_sock_name = NULL;
141 static char *auth_sock_dir = NULL;
143 /* removes the agent forwarding socket */
146 auth_sock_cleanup_proc(struct passwd *pw)
148 if (auth_sock_name != NULL) {
149 temporarily_use_uid(pw);
150 unlink(auth_sock_name);
151 rmdir(auth_sock_dir);
152 auth_sock_name = NULL;
158 auth_input_request_forwarding(struct passwd * pw)
162 struct sockaddr_un sunaddr;
164 if (auth_sock_name != NULL) {
165 error("authentication forwarding requested twice.");
169 /* Temporarily drop privileged uid for mkdir/bind. */
170 temporarily_use_uid(pw);
172 /* Allocate a buffer for the socket name, and format the name. */
173 auth_sock_name = xmalloc(MAXPATHLEN);
174 auth_sock_dir = xmalloc(MAXPATHLEN);
175 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
177 /* Create private directory for socket */
178 if (mkdtemp(auth_sock_dir) == NULL) {
179 packet_send_debug("Agent forwarding disabled: "
180 "mkdtemp() failed: %.100s", strerror(errno));
182 xfree(auth_sock_name);
183 xfree(auth_sock_dir);
184 auth_sock_name = NULL;
185 auth_sock_dir = NULL;
188 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
189 auth_sock_dir, (long) getpid());
191 /* Create the socket. */
192 sock = socket(AF_UNIX, SOCK_STREAM, 0);
194 packet_disconnect("socket: %.100s", strerror(errno));
196 /* Bind it to the name. */
197 memset(&sunaddr, 0, sizeof(sunaddr));
198 sunaddr.sun_family = AF_UNIX;
199 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
201 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
202 packet_disconnect("bind: %.100s", strerror(errno));
204 /* Restore the privileged uid. */
207 /* Start listening on the socket. */
208 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
209 packet_disconnect("listen: %.100s", strerror(errno));
211 /* Allocate a channel for the authentication agent socket. */
212 nc = channel_new("auth socket",
213 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
214 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
215 0, "auth socket", 1);
216 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
221 display_loginmsg(void)
223 if (buffer_len(&loginmsg) > 0) {
224 buffer_append(&loginmsg, "\0", 1);
225 printf("%s", (char *)buffer_ptr(&loginmsg));
226 buffer_clear(&loginmsg);
231 do_authenticated(Authctxt *authctxt)
233 setproctitle("%s", authctxt->pw->pw_name);
235 /* setup the channel layer */
236 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
237 channel_permit_all_opens();
240 do_authenticated2(authctxt);
242 do_authenticated1(authctxt);
244 do_cleanup(authctxt);
248 * Prepares for an interactive session. This is called after the user has
249 * been successfully authenticated. During this message exchange, pseudo
250 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
251 * are requested, etc.
254 do_authenticated1(Authctxt *authctxt)
258 int success, type, screen_flag;
259 int enable_compression_after_reply = 0;
260 u_int proto_len, data_len, dlen, compression_level = 0;
264 error("no more sessions");
267 s->authctxt = authctxt;
268 s->pw = authctxt->pw;
271 * We stay in this loop until the client requests to execute a shell
277 /* Get a packet from the client. */
278 type = packet_read();
280 /* Process the packet. */
282 case SSH_CMSG_REQUEST_COMPRESSION:
283 compression_level = packet_get_int();
285 if (compression_level < 1 || compression_level > 9) {
286 packet_send_debug("Received invalid compression level %d.",
290 if (options.compression == COMP_NONE) {
291 debug2("compression disabled");
294 /* Enable compression after we have responded with SUCCESS. */
295 enable_compression_after_reply = 1;
299 case SSH_CMSG_REQUEST_PTY:
300 success = session_pty_req(s);
303 case SSH_CMSG_X11_REQUEST_FORWARDING:
304 s->auth_proto = packet_get_string(&proto_len);
305 s->auth_data = packet_get_string(&data_len);
307 screen_flag = packet_get_protocol_flags() &
308 SSH_PROTOFLAG_SCREEN_NUMBER;
309 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
311 if (packet_remaining() == 4) {
313 debug2("Buggy client: "
314 "X11 screen flag missing");
315 s->screen = packet_get_int();
320 success = session_setup_x11fwd(s);
322 xfree(s->auth_proto);
324 s->auth_proto = NULL;
329 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
330 if (no_agent_forwarding_flag || compat13) {
331 debug("Authentication agent forwarding not permitted for this authentication.");
334 debug("Received authentication agent forwarding request.");
335 success = auth_input_request_forwarding(s->pw);
338 case SSH_CMSG_PORT_FORWARD_REQUEST:
339 if (no_port_forwarding_flag) {
340 debug("Port forwarding not permitted for this authentication.");
343 if (!options.allow_tcp_forwarding) {
344 debug("Port forwarding not permitted.");
347 debug("Received TCP/IP port forwarding request.");
348 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
349 options.gateway_ports) < 0) {
350 debug("Port forwarding failed.");
356 case SSH_CMSG_MAX_PACKET_SIZE:
357 if (packet_set_maxsize(packet_get_int()) > 0)
361 case SSH_CMSG_EXEC_SHELL:
362 case SSH_CMSG_EXEC_CMD:
363 if (type == SSH_CMSG_EXEC_CMD) {
364 command = packet_get_string(&dlen);
365 debug("Exec command '%.500s'", command);
377 * Any unknown messages in this phase are ignored,
378 * and a failure message is returned.
380 logit("Unknown packet type received after authentication: %d", type);
382 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
386 /* Enable compression now that we have replied if appropriate. */
387 if (enable_compression_after_reply) {
388 enable_compression_after_reply = 0;
389 packet_start_compression(compression_level);
395 * This is called to fork and execute a command when we have no tty. This
396 * will call do_child from the child, and server_loop from the parent after
397 * setting up file descriptors and such.
400 do_exec_no_pty(Session *s, const char *command)
405 int pin[2], pout[2], perr[2];
406 /* Allocate pipes for communicating with the program. */
407 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
408 packet_disconnect("Could not create pipes: %.100s",
410 #else /* USE_PIPES */
411 int inout[2], err[2];
412 /* Uses socket pairs to communicate with the program. */
413 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
414 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
415 packet_disconnect("Could not create socket pairs: %.100s",
417 #endif /* USE_PIPES */
419 fatal("do_exec_no_pty: no session");
421 session_proctitle(s);
424 if (options.use_pam && !use_privsep)
428 /* Fork the child. */
429 if ((pid = fork()) == 0) {
432 /* Child. Reinitialize the log since the pid has changed. */
433 log_init(__progname, options.log_level, options.log_facility, log_stderr);
436 * Create a new session and process group since the 4.4BSD
437 * setlogin() affects the entire process group.
440 error("setsid failed: %.100s", strerror(errno));
444 * Redirect stdin. We close the parent side of the socket
445 * pair, and make the child side the standard input.
448 if (dup2(pin[0], 0) < 0)
449 perror("dup2 stdin");
452 /* Redirect stdout. */
454 if (dup2(pout[1], 1) < 0)
455 perror("dup2 stdout");
458 /* Redirect stderr. */
460 if (dup2(perr[1], 2) < 0)
461 perror("dup2 stderr");
463 #else /* USE_PIPES */
465 * Redirect stdin, stdout, and stderr. Stdin and stdout will
466 * use the same socket, as some programs (particularly rdist)
467 * seem to depend on it.
471 if (dup2(inout[0], 0) < 0) /* stdin */
472 perror("dup2 stdin");
473 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
474 perror("dup2 stdout");
475 if (dup2(err[0], 2) < 0) /* stderr */
476 perror("dup2 stderr");
477 #endif /* USE_PIPES */
480 cray_init_job(s->pw); /* set up cray jid and tmpdir */
483 /* Do processing for the child (exec command etc). */
484 do_child(s, command);
488 signal(WJSIGNAL, cray_job_termination_handler);
492 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
495 packet_disconnect("fork failed: %.100s", strerror(errno));
497 /* Set interactive/non-interactive mode. */
498 packet_set_interactive(s->display != NULL);
500 /* We are the parent. Close the child sides of the pipes. */
506 if (s->is_subsystem) {
510 session_set_fds(s, pin[1], pout[0], perr[0]);
512 /* Enter the interactive session. */
513 server_loop(pid, pin[1], pout[0], perr[0]);
514 /* server_loop has closed pin[1], pout[0], and perr[0]. */
516 #else /* USE_PIPES */
517 /* We are the parent. Close the child sides of the socket pairs. */
522 * Clear loginmsg, since it's the child's responsibility to display
523 * it to the user, otherwise multiple sessions may accumulate
524 * multiple copies of the login messages.
526 buffer_clear(&loginmsg);
529 * Enter the interactive session. Note: server_loop must be able to
530 * handle the case that fdin and fdout are the same.
533 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
535 server_loop(pid, inout[1], inout[1], err[1]);
536 /* server_loop has closed inout[1] and err[1]. */
538 #endif /* USE_PIPES */
542 * This is called to fork and execute a command when we have a tty. This
543 * will call do_child from the child, and server_loop from the parent after
544 * setting up file descriptors, controlling tty, updating wtmp, utmp,
545 * lastlog, and other such operations.
548 do_exec_pty(Session *s, const char *command)
550 int fdout, ptyfd, ttyfd, ptymaster;
554 fatal("do_exec_pty: no session");
559 if (options.use_pam) {
560 do_pam_set_tty(s->tty);
566 /* Fork the child. */
567 if ((pid = fork()) == 0) {
570 /* Child. Reinitialize the log because the pid has changed. */
571 log_init(__progname, options.log_level, options.log_facility, log_stderr);
572 /* Close the master side of the pseudo tty. */
575 /* Make the pseudo tty our controlling tty. */
576 pty_make_controlling_tty(&ttyfd, s->tty);
578 /* Redirect stdin/stdout/stderr from the pseudo tty. */
579 if (dup2(ttyfd, 0) < 0)
580 error("dup2 stdin: %s", strerror(errno));
581 if (dup2(ttyfd, 1) < 0)
582 error("dup2 stdout: %s", strerror(errno));
583 if (dup2(ttyfd, 2) < 0)
584 error("dup2 stderr: %s", strerror(errno));
586 /* Close the extra descriptor for the pseudo tty. */
589 /* record login, etc. similar to login(1) */
591 if (!(options.use_login && command == NULL)) {
593 cray_init_job(s->pw); /* set up cray jid and tmpdir */
595 do_login(s, command);
597 # ifdef LOGIN_NEEDS_UTMPX
603 /* Do common processing for the child, such as execing the command. */
604 do_child(s, command);
608 signal(WJSIGNAL, cray_job_termination_handler);
612 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
615 packet_disconnect("fork failed: %.100s", strerror(errno));
618 /* Parent. Close the slave side of the pseudo tty. */
622 * Create another descriptor of the pty master side for use as the
623 * standard input. We could use the original descriptor, but this
624 * simplifies code in server_loop. The descriptor is bidirectional.
628 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
630 /* we keep a reference to the pty master */
631 ptymaster = dup(ptyfd);
633 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
634 s->ptymaster = ptymaster;
636 /* Enter interactive session. */
637 packet_set_interactive(1);
639 session_set_fds(s, ptyfd, fdout, -1);
641 server_loop(pid, ptyfd, fdout, -1);
642 /* server_loop _has_ closed ptyfd and fdout. */
646 #ifdef LOGIN_NEEDS_UTMPX
648 do_pre_login(Session *s)
651 struct sockaddr_storage from;
652 pid_t pid = getpid();
655 * Get IP address of client. If the connection is not a socket, let
656 * the address be 0.0.0.0.
658 memset(&from, 0, sizeof(from));
659 fromlen = sizeof(from);
660 if (packet_connection_is_on_socket()) {
661 if (getpeername(packet_get_connection_in(),
662 (struct sockaddr *)&from, &fromlen) < 0) {
663 debug("getpeername: %.100s", strerror(errno));
668 record_utmp_only(pid, s->tty, s->pw->pw_name,
669 get_remote_name_or_ip(utmp_len, options.use_dns),
670 (struct sockaddr *)&from, fromlen);
675 * This is called to fork and execute a command. If another command is
676 * to be forced, execute that instead.
679 do_exec(Session *s, const char *command)
681 if (options.adm_forced_command) {
682 original_command = command;
683 command = options.adm_forced_command;
684 debug("Forced command (config) '%.900s'", command);
685 } else if (forced_command) {
686 original_command = command;
687 command = forced_command;
688 debug("Forced command (key option) '%.900s'", command);
691 #ifdef SSH_AUDIT_EVENTS
693 PRIVSEP(audit_run_command(command));
694 else if (s->ttyfd == -1) {
695 char *shell = s->pw->pw_shell;
697 if (shell[0] == '\0') /* empty shell means /bin/sh */
699 PRIVSEP(audit_run_command(shell));
704 do_exec_pty(s, command);
706 do_exec_no_pty(s, command);
708 original_command = NULL;
711 * Clear loginmsg: it's the child's responsibility to display
712 * it to the user, otherwise multiple sessions may accumulate
713 * multiple copies of the login messages.
715 buffer_clear(&loginmsg);
718 /* administrative, login(1)-like work */
720 do_login(Session *s, const char *command)
723 struct sockaddr_storage from;
724 struct passwd * pw = s->pw;
725 pid_t pid = getpid();
728 * Get IP address of client. If the connection is not a socket, let
729 * the address be 0.0.0.0.
731 memset(&from, 0, sizeof(from));
732 fromlen = sizeof(from);
733 if (packet_connection_is_on_socket()) {
734 if (getpeername(packet_get_connection_in(),
735 (struct sockaddr *) & from, &fromlen) < 0) {
736 debug("getpeername: %.100s", strerror(errno));
741 /* Record that there was a login on that tty from the remote host. */
743 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
744 get_remote_name_or_ip(utmp_len,
746 (struct sockaddr *)&from, fromlen);
750 * If password change is needed, do it now.
751 * This needs to occur before the ~/.hushlogin check.
753 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
756 s->authctxt->force_pwchange = 0;
757 /* XXX - signal [net] parent to enable forwardings */
761 if (check_quietlogin(s, command))
770 * Display the message of the day.
778 if (options.print_motd) {
779 #ifdef HAVE_LOGIN_CAP
780 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
783 f = fopen("/etc/motd", "r");
786 while (fgets(buf, sizeof(buf), f))
795 * Check for quiet login, either .hushlogin or command given.
798 check_quietlogin(Session *s, const char *command)
801 struct passwd *pw = s->pw;
804 /* Return 1 if .hushlogin exists or a command given. */
807 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
808 #ifdef HAVE_LOGIN_CAP
809 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
812 if (stat(buf, &st) >= 0)
819 * Sets the value of the given variable in the environment. If the variable
820 * already exists, its value is overriden.
823 child_set_env(char ***envp, u_int *envsizep, const char *name,
831 * If we're passed an uninitialized list, allocate a single null
832 * entry before continuing.
834 if (*envp == NULL && *envsizep == 0) {
835 *envp = xmalloc(sizeof(char *));
841 * Find the slot where the value should be stored. If the variable
842 * already exists, we reuse the slot; otherwise we append a new slot
843 * at the end of the array, expanding if necessary.
846 namelen = strlen(name);
847 for (i = 0; env[i]; i++)
848 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
851 /* Reuse the slot. */
854 /* New variable. Expand if necessary. */
856 if (i >= envsize - 1) {
858 fatal("child_set_env: too many env vars");
860 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
863 /* Need to set the NULL pointer at end of array beyond the new slot. */
867 /* Allocate space and format the variable in the appropriate slot. */
868 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
869 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
873 * Reads environment variables from the given file and adds/overrides them
874 * into the environment. If the file does not exist, this does nothing.
875 * Otherwise, it must consist of empty lines, comments (line starts with '#')
876 * and assignments of the form name=value. No other forms are allowed.
879 read_environment_file(char ***env, u_int *envsize,
880 const char *filename)
887 f = fopen(filename, "r");
891 while (fgets(buf, sizeof(buf), f)) {
893 fatal("Too many lines in environment file %s", filename);
894 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
896 if (!*cp || *cp == '#' || *cp == '\n')
898 if (strchr(cp, '\n'))
899 *strchr(cp, '\n') = '\0';
900 value = strchr(cp, '=');
902 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
907 * Replace the equals sign by nul, and advance value to
912 child_set_env(env, envsize, cp, value);
917 #ifdef HAVE_ETC_DEFAULT_LOGIN
919 * Return named variable from specified environment, or NULL if not present.
922 child_get_env(char **env, const char *name)
928 for (i=0; env[i] != NULL; i++)
929 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
930 return(env[i] + len + 1);
935 * Read /etc/default/login.
936 * We pick up the PATH (or SUPATH for root) and UMASK.
939 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
941 char **tmpenv = NULL, *var;
942 u_int i, tmpenvsize = 0;
946 * We don't want to copy the whole file to the child's environment,
947 * so we use a temporary environment and copy the variables we're
950 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
956 var = child_get_env(tmpenv, "SUPATH");
958 var = child_get_env(tmpenv, "PATH");
960 child_set_env(env, envsize, "PATH", var);
962 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
963 if (sscanf(var, "%5lo", &mask) == 1)
966 for (i = 0; tmpenv[i] != NULL; i++)
970 #endif /* HAVE_ETC_DEFAULT_LOGIN */
973 copy_environment(char **source, char ***env, u_int *envsize)
975 char *var_name, *var_val;
981 for(i = 0; source[i] != NULL; i++) {
982 var_name = xstrdup(source[i]);
983 if ((var_val = strstr(var_name, "=")) == NULL) {
989 debug3("Copy environment: %s=%s", var_name, var_val);
990 child_set_env(env, envsize, var_name, var_val);
997 do_setup_env(Session *s, const char *shell)
1002 struct passwd *pw = s->pw;
1003 #ifndef HAVE_LOGIN_CAP
1007 /* Initialize the environment. */
1009 env = xcalloc(envsize, sizeof(char *));
1014 * The Windows environment contains some setting which are
1015 * important for a running system. They must not be dropped.
1020 p = fetch_windows_environment();
1021 copy_environment(p, &env, &envsize);
1022 free_windows_environment(p);
1027 /* Allow any GSSAPI methods that we've used to alter
1028 * the childs environment as they see fit
1030 ssh_gssapi_do_child(&env, &envsize);
1033 if (!options.use_login) {
1034 /* Set basic environment. */
1035 for (i = 0; i < s->num_env; i++)
1036 child_set_env(&env, &envsize, s->env[i].name,
1039 child_set_env(&env, &envsize, "USER", pw->pw_name);
1040 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1042 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1044 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1045 #ifdef HAVE_LOGIN_CAP
1046 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1047 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1049 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1050 #else /* HAVE_LOGIN_CAP */
1051 # ifndef HAVE_CYGWIN
1053 * There's no standard path on Windows. The path contains
1054 * important components pointing to the system directories,
1055 * needed for loading shared libraries. So the path better
1056 * remains intact here.
1058 # ifdef HAVE_ETC_DEFAULT_LOGIN
1059 read_etc_default_login(&env, &envsize, pw->pw_uid);
1060 path = child_get_env(env, "PATH");
1061 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1062 if (path == NULL || *path == '\0') {
1063 child_set_env(&env, &envsize, "PATH",
1064 s->pw->pw_uid == 0 ?
1065 SUPERUSER_PATH : _PATH_STDPATH);
1067 # endif /* HAVE_CYGWIN */
1068 #endif /* HAVE_LOGIN_CAP */
1070 snprintf(buf, sizeof buf, "%.200s/%.50s",
1071 _PATH_MAILDIR, pw->pw_name);
1072 child_set_env(&env, &envsize, "MAIL", buf);
1074 /* Normal systems set SHELL by default. */
1075 child_set_env(&env, &envsize, "SHELL", shell);
1078 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1080 /* Set custom environment options from RSA authentication. */
1081 if (!options.use_login) {
1082 while (custom_environment) {
1083 struct envstring *ce = custom_environment;
1086 for (i = 0; str[i] != '=' && str[i]; i++)
1088 if (str[i] == '=') {
1090 child_set_env(&env, &envsize, str, str + i + 1);
1092 custom_environment = ce->next;
1098 /* SSH_CLIENT deprecated */
1099 snprintf(buf, sizeof buf, "%.50s %d %d",
1100 get_remote_ipaddr(), get_remote_port(), get_local_port());
1101 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1103 laddr = get_local_ipaddr(packet_get_connection_in());
1104 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1105 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1107 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1110 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1112 child_set_env(&env, &envsize, "TERM", s->term);
1114 child_set_env(&env, &envsize, "DISPLAY", s->display);
1115 if (original_command)
1116 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1120 if (cray_tmpdir[0] != '\0')
1121 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1122 #endif /* _UNICOS */
1125 * Since we clear KRB5CCNAME at startup, if it's set now then it
1126 * must have been set by a native authentication method (eg AIX or
1127 * SIA), so copy it to the child.
1132 if ((cp = getenv("KRB5CCNAME")) != NULL)
1133 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1140 if ((cp = getenv("AUTHSTATE")) != NULL)
1141 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1142 read_environment_file(&env, &envsize, "/etc/environment");
1146 if (s->authctxt->krb5_ccname)
1147 child_set_env(&env, &envsize, "KRB5CCNAME",
1148 s->authctxt->krb5_ccname);
1152 * Pull in any environment variables that may have
1155 if (options.use_pam) {
1158 p = fetch_pam_child_environment();
1159 copy_environment(p, &env, &envsize);
1160 free_pam_environment(p);
1162 p = fetch_pam_environment();
1163 copy_environment(p, &env, &envsize);
1164 free_pam_environment(p);
1166 #endif /* USE_PAM */
1168 if (auth_sock_name != NULL)
1169 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1172 /* read $HOME/.ssh/environment. */
1173 if (options.permit_user_env && !options.use_login) {
1174 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1175 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1176 read_environment_file(&env, &envsize, buf);
1179 /* dump the environment */
1180 fprintf(stderr, "Environment:\n");
1181 for (i = 0; env[i]; i++)
1182 fprintf(stderr, " %.200s\n", env[i]);
1188 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1189 * first in this order).
1192 do_rc_files(Session *s, const char *shell)
1200 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1202 /* ignore _PATH_SSH_USER_RC for subsystems */
1203 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1204 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1205 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1207 fprintf(stderr, "Running %s\n", cmd);
1208 f = popen(cmd, "w");
1211 fprintf(f, "%s %s\n", s->auth_proto,
1215 fprintf(stderr, "Could not run %s\n",
1217 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1219 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1220 _PATH_SSH_SYSTEM_RC);
1221 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1224 fprintf(f, "%s %s\n", s->auth_proto,
1228 fprintf(stderr, "Could not run %s\n",
1229 _PATH_SSH_SYSTEM_RC);
1230 } else if (do_xauth && options.xauth_location != NULL) {
1231 /* Add authority data to .Xauthority if appropriate. */
1234 "Running %.500s remove %.100s\n",
1235 options.xauth_location, s->auth_display);
1237 "%.500s add %.100s %.100s %.100s\n",
1238 options.xauth_location, s->auth_display,
1239 s->auth_proto, s->auth_data);
1241 snprintf(cmd, sizeof cmd, "%s -q -",
1242 options.xauth_location);
1243 f = popen(cmd, "w");
1245 fprintf(f, "remove %s\n",
1247 fprintf(f, "add %s %s %s\n",
1248 s->auth_display, s->auth_proto,
1252 fprintf(stderr, "Could not run %s\n",
1259 do_nologin(struct passwd *pw)
1264 #ifdef HAVE_LOGIN_CAP
1265 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1266 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1267 _PATH_NOLOGIN), "r");
1270 f = fopen(_PATH_NOLOGIN, "r");
1273 /* /etc/nologin exists. Print its contents and exit. */
1274 logit("User %.100s not allowed because %s exists",
1275 pw->pw_name, _PATH_NOLOGIN);
1276 while (fgets(buf, sizeof(buf), f))
1284 /* Set login name, uid, gid, and groups. */
1286 do_setusercontext(struct passwd *pw)
1289 if (getuid() == 0 || geteuid() == 0)
1290 #endif /* HAVE_CYGWIN */
1293 #ifdef HAVE_SETPCRED
1294 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1295 fatal("Failed to set process credentials");
1296 #endif /* HAVE_SETPCRED */
1297 #ifdef HAVE_LOGIN_CAP
1302 if (options.gss_authentication) {
1303 temporarily_use_uid(pw);
1304 ssh_gssapi_storecreds();
1309 if (options.use_pam) {
1313 # endif /* USE_PAM */
1314 if (setusercontext(lc, pw, pw->pw_uid,
1315 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1316 perror("unable to set user context");
1320 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1321 /* Sets login uid for accounting */
1322 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1323 error("setluid: %s", strerror(errno));
1324 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1326 if (setlogin(pw->pw_name) < 0)
1327 error("setlogin failed: %s", strerror(errno));
1328 if (setgid(pw->pw_gid) < 0) {
1332 /* Initialize the group list. */
1333 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1334 perror("initgroups");
1339 if (options.gss_authentication) {
1340 temporarily_use_uid(pw);
1341 ssh_gssapi_storecreds();
1347 * PAM credentials may take the form of supplementary groups.
1348 * These will have been wiped by the above initgroups() call.
1349 * Reestablish them here.
1351 if (options.use_pam) {
1355 # endif /* USE_PAM */
1356 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1357 irix_setusercontext(pw);
1358 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1362 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1363 if (set_id(pw->pw_name) != 0) {
1366 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1367 /* Permanently switch to the desired uid. */
1368 permanently_set_uid(pw);
1375 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1376 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1379 ssh_selinux_setup_exec_context(pw->pw_name);
1384 do_pwchange(Session *s)
1387 fprintf(stderr, "WARNING: Your password has expired.\n");
1388 if (s->ttyfd != -1) {
1390 "You must change your password now and login again!\n");
1391 #ifdef PASSWD_NEEDS_USERNAME
1392 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1395 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1400 "Password change required but no TTY available.\n");
1406 launch_login(struct passwd *pw, const char *hostname)
1408 /* Launch login(1). */
1410 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1411 #ifdef xxxLOGIN_NEEDS_TERM
1412 (s->term ? s->term : "unknown"),
1413 #endif /* LOGIN_NEEDS_TERM */
1414 #ifdef LOGIN_NO_ENDOPT
1415 "-p", "-f", pw->pw_name, (char *)NULL);
1417 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1420 /* Login couldn't be executed, die. */
1427 child_close_fds(void)
1431 if (packet_get_connection_in() == packet_get_connection_out())
1432 close(packet_get_connection_in());
1434 close(packet_get_connection_in());
1435 close(packet_get_connection_out());
1438 * Close all descriptors related to channels. They will still remain
1439 * open in the parent.
1441 /* XXX better use close-on-exec? -markus */
1442 channel_close_all();
1445 * Close any extra file descriptors. Note that there may still be
1446 * descriptors left by system functions. They will be closed later.
1451 * Close any extra open file descriptors so that we don't have them
1452 * hanging around in clients. Note that we want to do this after
1453 * initgroups, because at least on Solaris 2.3 it leaves file
1456 for (i = 3; i < 64; i++)
1461 * Performs common processing for the child, such as setting up the
1462 * environment, closing extra file descriptors, setting the user and group
1463 * ids, and executing the command or shell.
1466 do_child(Session *s, const char *command)
1468 extern char **environ;
1471 const char *shell, *shell0, *hostname = NULL;
1472 struct passwd *pw = s->pw;
1474 /* remove hostkey from the child's memory */
1475 destroy_sensitive_data();
1477 /* Force a password change */
1478 if (s->authctxt->force_pwchange) {
1479 do_setusercontext(pw);
1485 /* login(1) is only called if we execute the login shell */
1486 if (options.use_login && command != NULL)
1487 options.use_login = 0;
1490 cray_setup(pw->pw_uid, pw->pw_name, command);
1491 #endif /* _UNICOS */
1494 * Login(1) does this as well, and it needs uid 0 for the "-h"
1495 * switch, so we let login(1) to this for us.
1497 if (!options.use_login) {
1499 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1500 if (!check_quietlogin(s, command))
1502 #else /* HAVE_OSF_SIA */
1503 /* When PAM is enabled we rely on it to do the nologin check */
1504 if (!options.use_pam)
1506 do_setusercontext(pw);
1508 * PAM session modules in do_setusercontext may have
1509 * generated messages, so if this in an interactive
1510 * login then display them too.
1512 if (!check_quietlogin(s, command))
1514 #endif /* HAVE_OSF_SIA */
1518 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1519 debug3("PAM session not opened, exiting");
1526 * Get the shell from the password data. An empty shell field is
1527 * legal, and means /bin/sh.
1529 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1532 * Make sure $SHELL points to the shell from the password file,
1533 * even if shell is overridden from login.conf
1535 env = do_setup_env(s, shell);
1537 #ifdef HAVE_LOGIN_CAP
1538 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1541 /* we have to stash the hostname before we close our socket. */
1542 if (options.use_login)
1543 hostname = get_remote_name_or_ip(utmp_len,
1546 * Close the connection descriptors; note that this is the child, and
1547 * the server will still have the socket open, and it is important
1548 * that we do not shutdown it. Note that the descriptors cannot be
1549 * closed before building the environment, as we call
1550 * get_remote_ipaddr there.
1555 * Must take new environment into use so that .ssh/rc,
1556 * /etc/ssh/sshrc and xauth are run in the proper environment.
1560 #if defined(KRB5) && defined(USE_AFS)
1562 * At this point, we check to see if AFS is active and if we have
1563 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1564 * if we can (and need to) extend the ticket into an AFS token. If
1565 * we don't do this, we run into potential problems if the user's
1566 * home directory is in AFS and it's not world-readable.
1569 if (options.kerberos_get_afs_token && k_hasafs() &&
1570 (s->authctxt->krb5_ctx != NULL)) {
1573 debug("Getting AFS token");
1577 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1578 krb5_afslog(s->authctxt->krb5_ctx,
1579 s->authctxt->krb5_fwd_ccache, cell, NULL);
1581 krb5_afslog_home(s->authctxt->krb5_ctx,
1582 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1586 /* Change current directory to the user's home directory. */
1587 if (chdir(pw->pw_dir) < 0) {
1588 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1589 pw->pw_dir, strerror(errno));
1590 #ifdef HAVE_LOGIN_CAP
1591 if (login_getcapbool(lc, "requirehome", 0))
1596 if (!options.use_login)
1597 do_rc_files(s, shell);
1599 /* restore SIGPIPE for child */
1600 signal(SIGPIPE, SIG_DFL);
1602 if (options.use_login) {
1603 launch_login(pw, hostname);
1607 /* Get the last component of the shell name. */
1608 if ((shell0 = strrchr(shell, '/')) != NULL)
1614 * If we have no command, execute the shell. In this case, the shell
1615 * name to be passed in argv[0] is preceded by '-' to indicate that
1616 * this is a login shell.
1621 /* Start the shell. Set initial character to '-'. */
1624 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1625 >= sizeof(argv0) - 1) {
1631 /* Execute the shell. */
1634 execve(shell, argv, env);
1636 /* Executing the shell failed. */
1641 * Execute the command using the user's shell. This uses the -c
1642 * option to execute the command.
1644 argv[0] = (char *) shell0;
1646 argv[2] = (char *) command;
1648 execve(shell, argv, env);
1657 static int did_init = 0;
1659 debug("session_new: init");
1660 for (i = 0; i < MAX_SESSIONS; i++) {
1661 sessions[i].used = 0;
1665 for (i = 0; i < MAX_SESSIONS; i++) {
1666 Session *s = &sessions[i];
1668 memset(s, 0, sizeof(*s));
1674 s->x11_chanids = NULL;
1675 debug("session_new: session %d", i);
1686 for (i = 0; i < MAX_SESSIONS; i++) {
1687 Session *s = &sessions[i];
1688 debug("dump: used %d session %d %p channel %d pid %ld",
1698 session_open(Authctxt *authctxt, int chanid)
1700 Session *s = session_new();
1701 debug("session_open: channel %d", chanid);
1703 error("no more sessions");
1706 s->authctxt = authctxt;
1707 s->pw = authctxt->pw;
1708 if (s->pw == NULL || !authctxt->valid)
1709 fatal("no user for session %d", s->self);
1710 debug("session_open: session %d: link with channel %d", s->self, chanid);
1716 session_by_tty(char *tty)
1719 for (i = 0; i < MAX_SESSIONS; i++) {
1720 Session *s = &sessions[i];
1721 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1722 debug("session_by_tty: session %d tty %s", i, tty);
1726 debug("session_by_tty: unknown tty %.100s", tty);
1732 session_by_channel(int id)
1735 for (i = 0; i < MAX_SESSIONS; i++) {
1736 Session *s = &sessions[i];
1737 if (s->used && s->chanid == id) {
1738 debug("session_by_channel: session %d channel %d", i, id);
1742 debug("session_by_channel: unknown channel %d", id);
1748 session_by_x11_channel(int id)
1752 for (i = 0; i < MAX_SESSIONS; i++) {
1753 Session *s = &sessions[i];
1755 if (s->x11_chanids == NULL || !s->used)
1757 for (j = 0; s->x11_chanids[j] != -1; j++) {
1758 if (s->x11_chanids[j] == id) {
1759 debug("session_by_x11_channel: session %d "
1760 "channel %d", s->self, id);
1765 debug("session_by_x11_channel: unknown channel %d", id);
1771 session_by_pid(pid_t pid)
1774 debug("session_by_pid: pid %ld", (long)pid);
1775 for (i = 0; i < MAX_SESSIONS; i++) {
1776 Session *s = &sessions[i];
1777 if (s->used && s->pid == pid)
1780 error("session_by_pid: unknown pid %ld", (long)pid);
1786 session_window_change_req(Session *s)
1788 s->col = packet_get_int();
1789 s->row = packet_get_int();
1790 s->xpixel = packet_get_int();
1791 s->ypixel = packet_get_int();
1793 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1798 session_pty_req(Session *s)
1804 debug("Allocating a pty not permitted for this authentication.");
1807 if (s->ttyfd != -1) {
1808 packet_disconnect("Protocol error: you already have a pty.");
1812 s->term = packet_get_string(&len);
1815 s->col = packet_get_int();
1816 s->row = packet_get_int();
1818 s->row = packet_get_int();
1819 s->col = packet_get_int();
1821 s->xpixel = packet_get_int();
1822 s->ypixel = packet_get_int();
1824 if (strcmp(s->term, "") == 0) {
1829 /* Allocate a pty and open it. */
1830 debug("Allocating pty.");
1831 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1837 error("session_pty_req: session %d alloc failed", s->self);
1840 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1842 /* for SSH1 the tty modes length is not given */
1844 n_bytes = packet_remaining();
1845 tty_parse_modes(s->ttyfd, &n_bytes);
1848 pty_setowner(s->pw, s->tty);
1850 /* Set window size from the packet. */
1851 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1854 session_proctitle(s);
1859 session_subsystem_req(Session *s)
1864 char *prog, *cmd, *subsys = packet_get_string(&len);
1868 logit("subsystem request for %.100s", subsys);
1870 for (i = 0; i < options.num_subsystems; i++) {
1871 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1872 prog = options.subsystem_command[i];
1873 cmd = options.subsystem_args[i];
1874 if (stat(prog, &st) < 0) {
1875 error("subsystem: cannot stat %s: %s", prog,
1879 debug("subsystem: exec() %s", cmd);
1880 s->is_subsystem = 1;
1888 logit("subsystem request for %.100s failed, subsystem not found",
1896 session_x11_req(Session *s)
1900 if (s->auth_proto != NULL || s->auth_data != NULL) {
1901 error("session_x11_req: session %d: "
1902 "x11 forwarding already active", s->self);
1905 s->single_connection = packet_get_char();
1906 s->auth_proto = packet_get_string(NULL);
1907 s->auth_data = packet_get_string(NULL);
1908 s->screen = packet_get_int();
1911 success = session_setup_x11fwd(s);
1913 xfree(s->auth_proto);
1914 xfree(s->auth_data);
1915 s->auth_proto = NULL;
1916 s->auth_data = NULL;
1922 session_shell_req(Session *s)
1930 session_exec_req(Session *s)
1933 char *command = packet_get_string(&len);
1935 do_exec(s, command);
1941 session_break_req(Session *s)
1944 packet_get_int(); /* ignored */
1947 if (s->ttyfd == -1 ||
1948 tcsendbreak(s->ttyfd, 0) < 0)
1954 session_env_req(Session *s)
1957 u_int name_len, val_len, i;
1959 name = packet_get_string(&name_len);
1960 val = packet_get_string(&val_len);
1963 /* Don't set too many environment variables */
1964 if (s->num_env > 128) {
1965 debug2("Ignoring env request %s: too many env vars", name);
1969 for (i = 0; i < options.num_accept_env; i++) {
1970 if (match_pattern(name, options.accept_env[i])) {
1971 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1972 s->env = xrealloc(s->env, s->num_env + 1,
1974 s->env[s->num_env].name = name;
1975 s->env[s->num_env].val = val;
1980 debug2("Ignoring env request %s: disallowed name", name);
1989 session_auth_agent_req(Session *s)
1991 static int called = 0;
1993 if (no_agent_forwarding_flag) {
1994 debug("session_auth_agent_req: no_agent_forwarding_flag");
2001 return auth_input_request_forwarding(s->pw);
2006 session_input_channel_req(Channel *c, const char *rtype)
2011 if ((s = session_by_channel(c->self)) == NULL) {
2012 logit("session_input_channel_req: no session %d req %.100s",
2016 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2019 * a session is in LARVAL state until a shell, a command
2020 * or a subsystem is executed
2022 if (c->type == SSH_CHANNEL_LARVAL) {
2023 if (strcmp(rtype, "shell") == 0) {
2024 success = session_shell_req(s);
2025 } else if (strcmp(rtype, "exec") == 0) {
2026 success = session_exec_req(s);
2027 } else if (strcmp(rtype, "pty-req") == 0) {
2028 success = session_pty_req(s);
2029 } else if (strcmp(rtype, "x11-req") == 0) {
2030 success = session_x11_req(s);
2031 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2032 success = session_auth_agent_req(s);
2033 } else if (strcmp(rtype, "subsystem") == 0) {
2034 success = session_subsystem_req(s);
2035 } else if (strcmp(rtype, "env") == 0) {
2036 success = session_env_req(s);
2039 if (strcmp(rtype, "window-change") == 0) {
2040 success = session_window_change_req(s);
2041 } else if (strcmp(rtype, "break") == 0) {
2042 success = session_break_req(s);
2049 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2052 fatal("session_set_fds: called for proto != 2.0");
2054 * now that have a child and a pipe to the child,
2055 * we can activate our channel and register the fd's
2057 if (s->chanid == -1)
2058 fatal("no channel for session %d", s->self);
2059 channel_set_fds(s->chanid,
2061 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2063 CHAN_SES_WINDOW_DEFAULT);
2067 * Function to perform pty cleanup. Also called if we get aborted abnormally
2068 * (e.g., due to a dropped connection).
2071 session_pty_cleanup2(Session *s)
2074 error("session_pty_cleanup: no session");
2080 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2082 /* Record that the user has logged out. */
2084 record_logout(s->pid, s->tty, s->pw->pw_name);
2086 /* Release the pseudo-tty. */
2088 pty_release(s->tty);
2091 * Close the server side of the socket pairs. We must do this after
2092 * the pty cleanup, so that another process doesn't get this pty
2093 * while we're still cleaning up.
2095 if (close(s->ptymaster) < 0)
2096 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2098 /* unlink pty from session */
2103 session_pty_cleanup(Session *s)
2105 PRIVSEP(session_pty_cleanup2(s));
2111 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2126 return "SIG@openssh.com";
2130 session_close_x11(int id)
2134 if ((c = channel_by_id(id)) == NULL) {
2135 debug("session_close_x11: x11 channel %d missing", id);
2137 /* Detach X11 listener */
2138 debug("session_close_x11: detach x11 channel %d", id);
2139 channel_cancel_cleanup(id);
2140 if (c->ostate != CHAN_OUTPUT_CLOSED)
2146 session_close_single_x11(int id, void *arg)
2151 debug3("session_close_single_x11: channel %d", id);
2152 channel_cancel_cleanup(id);
2153 if ((s = session_by_x11_channel(id)) == NULL)
2154 fatal("session_close_single_x11: no x11 channel %d", id);
2155 for (i = 0; s->x11_chanids[i] != -1; i++) {
2156 debug("session_close_single_x11: session %d: "
2157 "closing channel %d", s->self, s->x11_chanids[i]);
2159 * The channel "id" is already closing, but make sure we
2160 * close all of its siblings.
2162 if (s->x11_chanids[i] != id)
2163 session_close_x11(s->x11_chanids[i]);
2165 xfree(s->x11_chanids);
2166 s->x11_chanids = NULL;
2171 if (s->auth_proto) {
2172 xfree(s->auth_proto);
2173 s->auth_proto = NULL;
2176 xfree(s->auth_data);
2177 s->auth_data = NULL;
2179 if (s->auth_display) {
2180 xfree(s->auth_display);
2181 s->auth_display = NULL;
2186 session_exit_message(Session *s, int status)
2190 if ((c = channel_lookup(s->chanid)) == NULL)
2191 fatal("session_exit_message: session %d: no channel %d",
2192 s->self, s->chanid);
2193 debug("session_exit_message: session %d channel %d pid %ld",
2194 s->self, s->chanid, (long)s->pid);
2196 if (WIFEXITED(status)) {
2197 channel_request_start(s->chanid, "exit-status", 0);
2198 packet_put_int(WEXITSTATUS(status));
2200 } else if (WIFSIGNALED(status)) {
2201 channel_request_start(s->chanid, "exit-signal", 0);
2202 packet_put_cstring(sig2name(WTERMSIG(status)));
2204 packet_put_char(WCOREDUMP(status));
2205 #else /* WCOREDUMP */
2207 #endif /* WCOREDUMP */
2208 packet_put_cstring("");
2209 packet_put_cstring("");
2212 /* Some weird exit cause. Just exit. */
2213 packet_disconnect("wait returned status %04x.", status);
2216 /* disconnect channel */
2217 debug("session_exit_message: release channel %d", s->chanid);
2220 * Adjust cleanup callback attachment to send close messages when
2221 * the channel gets EOF. The session will be then be closed
2222 * by session_close_by_channel when the childs close their fds.
2224 channel_register_cleanup(c->self, session_close_by_channel, 1);
2227 * emulate a write failure with 'chan_write_failed', nobody will be
2228 * interested in data we write.
2229 * Note that we must not call 'chan_read_failed', since there could
2230 * be some more data waiting in the pipe.
2232 if (c->ostate != CHAN_OUTPUT_CLOSED)
2233 chan_write_failed(c);
2237 session_close(Session *s)
2241 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2243 session_pty_cleanup(s);
2249 xfree(s->x11_chanids);
2250 if (s->auth_display)
2251 xfree(s->auth_display);
2253 xfree(s->auth_data);
2255 xfree(s->auth_proto);
2257 for (i = 0; i < s->num_env; i++) {
2258 xfree(s->env[i].name);
2259 xfree(s->env[i].val);
2263 session_proctitle(s);
2267 session_close_by_pid(pid_t pid, int status)
2269 Session *s = session_by_pid(pid);
2271 debug("session_close_by_pid: no session for pid %ld",
2275 if (s->chanid != -1)
2276 session_exit_message(s, status);
2278 session_pty_cleanup(s);
2283 * this is called when a channel dies before
2284 * the session 'child' itself dies
2287 session_close_by_channel(int id, void *arg)
2289 Session *s = session_by_channel(id);
2293 debug("session_close_by_channel: no session for id %d", id);
2296 debug("session_close_by_channel: channel %d child %ld",
2299 debug("session_close_by_channel: channel %d: has child", id);
2301 * delay detach of session, but release pty, since
2302 * the fd's to the child are already closed
2305 session_pty_cleanup(s);
2308 /* detach by removing callback */
2309 channel_cancel_cleanup(s->chanid);
2311 /* Close any X11 listeners associated with this session */
2312 if (s->x11_chanids != NULL) {
2313 for (i = 0; s->x11_chanids[i] != -1; i++) {
2314 session_close_x11(s->x11_chanids[i]);
2315 s->x11_chanids[i] = -1;
2324 session_destroy_all(void (*closefunc)(Session *))
2327 for (i = 0; i < MAX_SESSIONS; i++) {
2328 Session *s = &sessions[i];
2330 if (closefunc != NULL)
2339 session_tty_list(void)
2341 static char buf[1024];
2346 for (i = 0; i < MAX_SESSIONS; i++) {
2347 Session *s = &sessions[i];
2348 if (s->used && s->ttyfd != -1) {
2350 if (strncmp(s->tty, "/dev/", 5) != 0) {
2351 cp = strrchr(s->tty, '/');
2352 cp = (cp == NULL) ? s->tty : cp + 1;
2357 strlcat(buf, ",", sizeof buf);
2358 strlcat(buf, cp, sizeof buf);
2362 strlcpy(buf, "notty", sizeof buf);
2367 session_proctitle(Session *s)
2370 error("no user for session %d", s->self);
2372 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2376 session_setup_x11fwd(Session *s)
2379 char display[512], auth_display[512];
2380 char hostname[MAXHOSTNAMELEN];
2383 if (no_x11_forwarding_flag) {
2384 packet_send_debug("X11 forwarding disabled in user configuration file.");
2387 if (!options.x11_forwarding) {
2388 debug("X11 forwarding disabled in server configuration file.");
2391 if (!options.xauth_location ||
2392 (stat(options.xauth_location, &st) == -1)) {
2393 packet_send_debug("No xauth program; cannot forward with spoofing.");
2396 if (options.use_login) {
2397 packet_send_debug("X11 forwarding disabled; "
2398 "not compatible with UseLogin=yes.");
2401 if (s->display != NULL) {
2402 debug("X11 display already set.");
2405 if (x11_create_display_inet(options.x11_display_offset,
2406 options.x11_use_localhost, s->single_connection,
2407 &s->display_number, &s->x11_chanids) == -1) {
2408 debug("x11_create_display_inet failed.");
2411 for (i = 0; s->x11_chanids[i] != -1; i++) {
2412 channel_register_cleanup(s->x11_chanids[i],
2413 session_close_single_x11, 0);
2416 /* Set up a suitable value for the DISPLAY variable. */
2417 if (gethostname(hostname, sizeof(hostname)) < 0)
2418 fatal("gethostname: %.100s", strerror(errno));
2420 * auth_display must be used as the displayname when the
2421 * authorization entry is added with xauth(1). This will be
2422 * different than the DISPLAY string for localhost displays.
2424 if (options.x11_use_localhost) {
2425 snprintf(display, sizeof display, "localhost:%u.%u",
2426 s->display_number, s->screen);
2427 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2428 s->display_number, s->screen);
2429 s->display = xstrdup(display);
2430 s->auth_display = xstrdup(auth_display);
2432 #ifdef IPADDR_IN_DISPLAY
2434 struct in_addr my_addr;
2436 he = gethostbyname(hostname);
2438 error("Can't get IP address for X11 DISPLAY.");
2439 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2442 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2443 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2444 s->display_number, s->screen);
2446 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2447 s->display_number, s->screen);
2449 s->display = xstrdup(display);
2450 s->auth_display = xstrdup(display);
2457 do_authenticated2(Authctxt *authctxt)
2459 server_loop2(authctxt);
2463 do_cleanup(Authctxt *authctxt)
2465 static int called = 0;
2467 debug("do_cleanup");
2469 /* no cleanup if we're in the child for login shell */
2473 /* avoid double cleanup */
2478 if (authctxt == NULL)
2481 if (options.kerberos_ticket_cleanup &&
2483 krb5_cleanup_proc(authctxt);
2487 if (compat20 && options.gss_cleanup_creds)
2488 ssh_gssapi_cleanup_creds();
2492 if (options.use_pam) {
2494 sshpam_thread_cleanup();
2498 /* remove agent socket */
2499 auth_sock_cleanup_proc(authctxt->pw);
2502 * Cleanup ptys/utmp only if privsep is disabled,
2503 * or if running in monitor.
2505 if (!use_privsep || mm_is_monitor())
2506 session_destroy_all(session_pty_cleanup2);