1 /* $OpenBSD: session.c,v 1.213 2006/07/26 02:35:17 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>
72 #include "auth-options.h"
73 #include "pathnames.h"
77 #include "serverloop.h"
81 #include "monitor_wrap.h"
83 #if defined(KRB5) && defined(USE_AFS)
93 Session *session_new(void);
94 void session_set_fds(Session *, int, int, int);
95 void session_pty_cleanup(Session *);
96 void session_proctitle(Session *);
97 int session_setup_x11fwd(Session *);
98 void do_exec_pty(Session *, const char *);
99 void do_exec_no_pty(Session *, const char *);
100 void do_exec(Session *, const char *);
101 void do_login(Session *, const char *);
102 #ifdef LOGIN_NEEDS_UTMPX
103 static void do_pre_login(Session *s);
105 void do_child(Session *, const char *);
107 int check_quietlogin(Session *, const char *);
109 static void do_authenticated1(Authctxt *);
110 static void do_authenticated2(Authctxt *);
112 static int session_pty_req(Session *);
115 extern ServerOptions options;
116 extern char *__progname;
117 extern int log_stderr;
118 extern int debug_flag;
119 extern u_int utmp_len;
120 extern int startup_pipe;
121 extern void destroy_sensitive_data(void);
122 extern Buffer loginmsg;
124 /* original command from peer. */
125 const char *original_command = NULL;
128 #define MAX_SESSIONS 10
129 Session sessions[MAX_SESSIONS];
131 #ifdef HAVE_LOGIN_CAP
135 static int is_child = 0;
137 /* Name and directory of socket for authentication agent forwarding. */
138 static char *auth_sock_name = NULL;
139 static char *auth_sock_dir = NULL;
141 /* removes the agent forwarding socket */
144 auth_sock_cleanup_proc(struct passwd *pw)
146 if (auth_sock_name != NULL) {
147 temporarily_use_uid(pw);
148 unlink(auth_sock_name);
149 rmdir(auth_sock_dir);
150 auth_sock_name = NULL;
156 auth_input_request_forwarding(struct passwd * pw)
160 struct sockaddr_un sunaddr;
162 if (auth_sock_name != NULL) {
163 error("authentication forwarding requested twice.");
167 /* Temporarily drop privileged uid for mkdir/bind. */
168 temporarily_use_uid(pw);
170 /* Allocate a buffer for the socket name, and format the name. */
171 auth_sock_name = xmalloc(MAXPATHLEN);
172 auth_sock_dir = xmalloc(MAXPATHLEN);
173 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
175 /* Create private directory for socket */
176 if (mkdtemp(auth_sock_dir) == NULL) {
177 packet_send_debug("Agent forwarding disabled: "
178 "mkdtemp() failed: %.100s", strerror(errno));
180 xfree(auth_sock_name);
181 xfree(auth_sock_dir);
182 auth_sock_name = NULL;
183 auth_sock_dir = NULL;
186 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
187 auth_sock_dir, (long) getpid());
189 /* Create the socket. */
190 sock = socket(AF_UNIX, SOCK_STREAM, 0);
192 packet_disconnect("socket: %.100s", strerror(errno));
194 /* Bind it to the name. */
195 memset(&sunaddr, 0, sizeof(sunaddr));
196 sunaddr.sun_family = AF_UNIX;
197 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
199 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
200 packet_disconnect("bind: %.100s", strerror(errno));
202 /* Restore the privileged uid. */
205 /* Start listening on the socket. */
206 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
207 packet_disconnect("listen: %.100s", strerror(errno));
209 /* Allocate a channel for the authentication agent socket. */
210 nc = channel_new("auth socket",
211 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
212 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
213 0, "auth socket", 1);
214 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
219 display_loginmsg(void)
221 if (buffer_len(&loginmsg) > 0) {
222 buffer_append(&loginmsg, "\0", 1);
223 printf("%s", (char *)buffer_ptr(&loginmsg));
224 buffer_clear(&loginmsg);
229 do_authenticated(Authctxt *authctxt)
231 setproctitle("%s", authctxt->pw->pw_name);
233 /* setup the channel layer */
234 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
235 channel_permit_all_opens();
238 do_authenticated2(authctxt);
240 do_authenticated1(authctxt);
242 do_cleanup(authctxt);
246 * Prepares for an interactive session. This is called after the user has
247 * been successfully authenticated. During this message exchange, pseudo
248 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
249 * are requested, etc.
252 do_authenticated1(Authctxt *authctxt)
256 int success, type, screen_flag;
257 int enable_compression_after_reply = 0;
258 u_int proto_len, data_len, dlen, compression_level = 0;
262 error("no more sessions");
265 s->authctxt = authctxt;
266 s->pw = authctxt->pw;
269 * We stay in this loop until the client requests to execute a shell
275 /* Get a packet from the client. */
276 type = packet_read();
278 /* Process the packet. */
280 case SSH_CMSG_REQUEST_COMPRESSION:
281 compression_level = packet_get_int();
283 if (compression_level < 1 || compression_level > 9) {
284 packet_send_debug("Received invalid compression level %d.",
288 if (options.compression == COMP_NONE) {
289 debug2("compression disabled");
292 /* Enable compression after we have responded with SUCCESS. */
293 enable_compression_after_reply = 1;
297 case SSH_CMSG_REQUEST_PTY:
298 success = session_pty_req(s);
301 case SSH_CMSG_X11_REQUEST_FORWARDING:
302 s->auth_proto = packet_get_string(&proto_len);
303 s->auth_data = packet_get_string(&data_len);
305 screen_flag = packet_get_protocol_flags() &
306 SSH_PROTOFLAG_SCREEN_NUMBER;
307 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
309 if (packet_remaining() == 4) {
311 debug2("Buggy client: "
312 "X11 screen flag missing");
313 s->screen = packet_get_int();
318 success = session_setup_x11fwd(s);
320 xfree(s->auth_proto);
322 s->auth_proto = NULL;
327 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
328 if (no_agent_forwarding_flag || compat13) {
329 debug("Authentication agent forwarding not permitted for this authentication.");
332 debug("Received authentication agent forwarding request.");
333 success = auth_input_request_forwarding(s->pw);
336 case SSH_CMSG_PORT_FORWARD_REQUEST:
337 if (no_port_forwarding_flag) {
338 debug("Port forwarding not permitted for this authentication.");
341 if (!options.allow_tcp_forwarding) {
342 debug("Port forwarding not permitted.");
345 debug("Received TCP/IP port forwarding request.");
346 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
347 options.gateway_ports) < 0) {
348 debug("Port forwarding failed.");
354 case SSH_CMSG_MAX_PACKET_SIZE:
355 if (packet_set_maxsize(packet_get_int()) > 0)
359 case SSH_CMSG_EXEC_SHELL:
360 case SSH_CMSG_EXEC_CMD:
361 if (type == SSH_CMSG_EXEC_CMD) {
362 command = packet_get_string(&dlen);
363 debug("Exec command '%.500s'", command);
375 * Any unknown messages in this phase are ignored,
376 * and a failure message is returned.
378 logit("Unknown packet type received after authentication: %d", type);
380 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
384 /* Enable compression now that we have replied if appropriate. */
385 if (enable_compression_after_reply) {
386 enable_compression_after_reply = 0;
387 packet_start_compression(compression_level);
393 * This is called to fork and execute a command when we have no tty. This
394 * will call do_child from the child, and server_loop from the parent after
395 * setting up file descriptors and such.
398 do_exec_no_pty(Session *s, const char *command)
403 int pin[2], pout[2], perr[2];
404 /* Allocate pipes for communicating with the program. */
405 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
406 packet_disconnect("Could not create pipes: %.100s",
408 #else /* USE_PIPES */
409 int inout[2], err[2];
410 /* Uses socket pairs to communicate with the program. */
411 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
412 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
413 packet_disconnect("Could not create socket pairs: %.100s",
415 #endif /* USE_PIPES */
417 fatal("do_exec_no_pty: no session");
419 session_proctitle(s);
422 if (options.use_pam && !use_privsep)
426 /* Fork the child. */
427 if ((pid = fork()) == 0) {
430 /* Child. Reinitialize the log since the pid has changed. */
431 log_init(__progname, options.log_level, options.log_facility, log_stderr);
434 * Create a new session and process group since the 4.4BSD
435 * setlogin() affects the entire process group.
438 error("setsid failed: %.100s", strerror(errno));
442 * Redirect stdin. We close the parent side of the socket
443 * pair, and make the child side the standard input.
446 if (dup2(pin[0], 0) < 0)
447 perror("dup2 stdin");
450 /* Redirect stdout. */
452 if (dup2(pout[1], 1) < 0)
453 perror("dup2 stdout");
456 /* Redirect stderr. */
458 if (dup2(perr[1], 2) < 0)
459 perror("dup2 stderr");
461 #else /* USE_PIPES */
463 * Redirect stdin, stdout, and stderr. Stdin and stdout will
464 * use the same socket, as some programs (particularly rdist)
465 * seem to depend on it.
469 if (dup2(inout[0], 0) < 0) /* stdin */
470 perror("dup2 stdin");
471 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
472 perror("dup2 stdout");
473 if (dup2(err[0], 2) < 0) /* stderr */
474 perror("dup2 stderr");
475 #endif /* USE_PIPES */
478 cray_init_job(s->pw); /* set up cray jid and tmpdir */
481 /* Do processing for the child (exec command etc). */
482 do_child(s, command);
486 signal(WJSIGNAL, cray_job_termination_handler);
490 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
493 packet_disconnect("fork failed: %.100s", strerror(errno));
495 /* Set interactive/non-interactive mode. */
496 packet_set_interactive(s->display != NULL);
498 /* We are the parent. Close the child sides of the pipes. */
504 if (s->is_subsystem) {
508 session_set_fds(s, pin[1], pout[0], perr[0]);
510 /* Enter the interactive session. */
511 server_loop(pid, pin[1], pout[0], perr[0]);
512 /* server_loop has closed pin[1], pout[0], and perr[0]. */
514 #else /* USE_PIPES */
515 /* We are the parent. Close the child sides of the socket pairs. */
520 * Clear loginmsg, since it's the child's responsibility to display
521 * it to the user, otherwise multiple sessions may accumulate
522 * multiple copies of the login messages.
524 buffer_clear(&loginmsg);
527 * Enter the interactive session. Note: server_loop must be able to
528 * handle the case that fdin and fdout are the same.
531 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
533 server_loop(pid, inout[1], inout[1], err[1]);
534 /* server_loop has closed inout[1] and err[1]. */
536 #endif /* USE_PIPES */
540 * This is called to fork and execute a command when we have a tty. This
541 * will call do_child from the child, and server_loop from the parent after
542 * setting up file descriptors, controlling tty, updating wtmp, utmp,
543 * lastlog, and other such operations.
546 do_exec_pty(Session *s, const char *command)
548 int fdout, ptyfd, ttyfd, ptymaster;
552 fatal("do_exec_pty: no session");
557 if (options.use_pam) {
558 do_pam_set_tty(s->tty);
564 /* Fork the child. */
565 if ((pid = fork()) == 0) {
568 /* Child. Reinitialize the log because the pid has changed. */
569 log_init(__progname, options.log_level, options.log_facility, log_stderr);
570 /* Close the master side of the pseudo tty. */
573 /* Make the pseudo tty our controlling tty. */
574 pty_make_controlling_tty(&ttyfd, s->tty);
576 /* Redirect stdin/stdout/stderr from the pseudo tty. */
577 if (dup2(ttyfd, 0) < 0)
578 error("dup2 stdin: %s", strerror(errno));
579 if (dup2(ttyfd, 1) < 0)
580 error("dup2 stdout: %s", strerror(errno));
581 if (dup2(ttyfd, 2) < 0)
582 error("dup2 stderr: %s", strerror(errno));
584 /* Close the extra descriptor for the pseudo tty. */
587 /* record login, etc. similar to login(1) */
589 if (!(options.use_login && command == NULL)) {
591 cray_init_job(s->pw); /* set up cray jid and tmpdir */
593 do_login(s, command);
595 # ifdef LOGIN_NEEDS_UTMPX
601 /* Do common processing for the child, such as execing the command. */
602 do_child(s, command);
606 signal(WJSIGNAL, cray_job_termination_handler);
610 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
613 packet_disconnect("fork failed: %.100s", strerror(errno));
616 /* Parent. Close the slave side of the pseudo tty. */
620 * Create another descriptor of the pty master side for use as the
621 * standard input. We could use the original descriptor, but this
622 * simplifies code in server_loop. The descriptor is bidirectional.
626 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
628 /* we keep a reference to the pty master */
629 ptymaster = dup(ptyfd);
631 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
632 s->ptymaster = ptymaster;
634 /* Enter interactive session. */
635 packet_set_interactive(1);
637 session_set_fds(s, ptyfd, fdout, -1);
639 server_loop(pid, ptyfd, fdout, -1);
640 /* server_loop _has_ closed ptyfd and fdout. */
644 #ifdef LOGIN_NEEDS_UTMPX
646 do_pre_login(Session *s)
649 struct sockaddr_storage from;
650 pid_t pid = getpid();
653 * Get IP address of client. If the connection is not a socket, let
654 * the address be 0.0.0.0.
656 memset(&from, 0, sizeof(from));
657 fromlen = sizeof(from);
658 if (packet_connection_is_on_socket()) {
659 if (getpeername(packet_get_connection_in(),
660 (struct sockaddr *)&from, &fromlen) < 0) {
661 debug("getpeername: %.100s", strerror(errno));
666 record_utmp_only(pid, s->tty, s->pw->pw_name,
667 get_remote_name_or_ip(utmp_len, options.use_dns),
668 (struct sockaddr *)&from, fromlen);
673 * This is called to fork and execute a command. If another command is
674 * to be forced, execute that instead.
677 do_exec(Session *s, const char *command)
679 if (options.adm_forced_command) {
680 original_command = command;
681 command = options.adm_forced_command;
682 debug("Forced command (config) '%.900s'", command);
683 } else if (forced_command) {
684 original_command = command;
685 command = forced_command;
686 debug("Forced command (key option) '%.900s'", command);
689 #ifdef SSH_AUDIT_EVENTS
691 PRIVSEP(audit_run_command(command));
692 else if (s->ttyfd == -1) {
693 char *shell = s->pw->pw_shell;
695 if (shell[0] == '\0') /* empty shell means /bin/sh */
697 PRIVSEP(audit_run_command(shell));
702 do_exec_pty(s, command);
704 do_exec_no_pty(s, command);
706 original_command = NULL;
709 * Clear loginmsg: it's the child's responsibility to display
710 * it to the user, otherwise multiple sessions may accumulate
711 * multiple copies of the login messages.
713 buffer_clear(&loginmsg);
716 /* administrative, login(1)-like work */
718 do_login(Session *s, const char *command)
721 struct sockaddr_storage from;
722 struct passwd * pw = s->pw;
723 pid_t pid = getpid();
726 * Get IP address of client. If the connection is not a socket, let
727 * the address be 0.0.0.0.
729 memset(&from, 0, sizeof(from));
730 fromlen = sizeof(from);
731 if (packet_connection_is_on_socket()) {
732 if (getpeername(packet_get_connection_in(),
733 (struct sockaddr *) & from, &fromlen) < 0) {
734 debug("getpeername: %.100s", strerror(errno));
739 /* Record that there was a login on that tty from the remote host. */
741 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
742 get_remote_name_or_ip(utmp_len,
744 (struct sockaddr *)&from, fromlen);
748 * If password change is needed, do it now.
749 * This needs to occur before the ~/.hushlogin check.
751 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
754 s->authctxt->force_pwchange = 0;
755 /* XXX - signal [net] parent to enable forwardings */
759 if (check_quietlogin(s, command))
768 * Display the message of the day.
776 if (options.print_motd) {
777 #ifdef HAVE_LOGIN_CAP
778 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
781 f = fopen("/etc/motd", "r");
784 while (fgets(buf, sizeof(buf), f))
793 * Check for quiet login, either .hushlogin or command given.
796 check_quietlogin(Session *s, const char *command)
799 struct passwd *pw = s->pw;
802 /* Return 1 if .hushlogin exists or a command given. */
805 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
806 #ifdef HAVE_LOGIN_CAP
807 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
810 if (stat(buf, &st) >= 0)
817 * Sets the value of the given variable in the environment. If the variable
818 * already exists, its value is overriden.
821 child_set_env(char ***envp, u_int *envsizep, const char *name,
829 * If we're passed an uninitialized list, allocate a single null
830 * entry before continuing.
832 if (*envp == NULL && *envsizep == 0) {
833 *envp = xmalloc(sizeof(char *));
839 * Find the slot where the value should be stored. If the variable
840 * already exists, we reuse the slot; otherwise we append a new slot
841 * at the end of the array, expanding if necessary.
844 namelen = strlen(name);
845 for (i = 0; env[i]; i++)
846 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
849 /* Reuse the slot. */
852 /* New variable. Expand if necessary. */
854 if (i >= envsize - 1) {
856 fatal("child_set_env: too many env vars");
858 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
861 /* Need to set the NULL pointer at end of array beyond the new slot. */
865 /* Allocate space and format the variable in the appropriate slot. */
866 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
867 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
871 * Reads environment variables from the given file and adds/overrides them
872 * into the environment. If the file does not exist, this does nothing.
873 * Otherwise, it must consist of empty lines, comments (line starts with '#')
874 * and assignments of the form name=value. No other forms are allowed.
877 read_environment_file(char ***env, u_int *envsize,
878 const char *filename)
885 f = fopen(filename, "r");
889 while (fgets(buf, sizeof(buf), f)) {
891 fatal("Too many lines in environment file %s", filename);
892 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
894 if (!*cp || *cp == '#' || *cp == '\n')
896 if (strchr(cp, '\n'))
897 *strchr(cp, '\n') = '\0';
898 value = strchr(cp, '=');
900 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
905 * Replace the equals sign by nul, and advance value to
910 child_set_env(env, envsize, cp, value);
915 #ifdef HAVE_ETC_DEFAULT_LOGIN
917 * Return named variable from specified environment, or NULL if not present.
920 child_get_env(char **env, const char *name)
926 for (i=0; env[i] != NULL; i++)
927 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
928 return(env[i] + len + 1);
933 * Read /etc/default/login.
934 * We pick up the PATH (or SUPATH for root) and UMASK.
937 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
939 char **tmpenv = NULL, *var;
940 u_int i, tmpenvsize = 0;
944 * We don't want to copy the whole file to the child's environment,
945 * so we use a temporary environment and copy the variables we're
948 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
954 var = child_get_env(tmpenv, "SUPATH");
956 var = child_get_env(tmpenv, "PATH");
958 child_set_env(env, envsize, "PATH", var);
960 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
961 if (sscanf(var, "%5lo", &mask) == 1)
964 for (i = 0; tmpenv[i] != NULL; i++)
968 #endif /* HAVE_ETC_DEFAULT_LOGIN */
971 copy_environment(char **source, char ***env, u_int *envsize)
973 char *var_name, *var_val;
979 for(i = 0; source[i] != NULL; i++) {
980 var_name = xstrdup(source[i]);
981 if ((var_val = strstr(var_name, "=")) == NULL) {
987 debug3("Copy environment: %s=%s", var_name, var_val);
988 child_set_env(env, envsize, var_name, var_val);
995 do_setup_env(Session *s, const char *shell)
1000 struct passwd *pw = s->pw;
1001 #ifndef HAVE_LOGIN_CAP
1005 /* Initialize the environment. */
1007 env = xcalloc(envsize, sizeof(char *));
1012 * The Windows environment contains some setting which are
1013 * important for a running system. They must not be dropped.
1018 p = fetch_windows_environment();
1019 copy_environment(p, &env, &envsize);
1020 free_windows_environment(p);
1025 /* Allow any GSSAPI methods that we've used to alter
1026 * the childs environment as they see fit
1028 ssh_gssapi_do_child(&env, &envsize);
1031 if (!options.use_login) {
1032 /* Set basic environment. */
1033 for (i = 0; i < s->num_env; i++)
1034 child_set_env(&env, &envsize, s->env[i].name,
1037 child_set_env(&env, &envsize, "USER", pw->pw_name);
1038 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1040 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1042 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1043 #ifdef HAVE_LOGIN_CAP
1044 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1045 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1047 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1048 #else /* HAVE_LOGIN_CAP */
1049 # ifndef HAVE_CYGWIN
1051 * There's no standard path on Windows. The path contains
1052 * important components pointing to the system directories,
1053 * needed for loading shared libraries. So the path better
1054 * remains intact here.
1056 # ifdef HAVE_ETC_DEFAULT_LOGIN
1057 read_etc_default_login(&env, &envsize, pw->pw_uid);
1058 path = child_get_env(env, "PATH");
1059 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1060 if (path == NULL || *path == '\0') {
1061 child_set_env(&env, &envsize, "PATH",
1062 s->pw->pw_uid == 0 ?
1063 SUPERUSER_PATH : _PATH_STDPATH);
1065 # endif /* HAVE_CYGWIN */
1066 #endif /* HAVE_LOGIN_CAP */
1068 snprintf(buf, sizeof buf, "%.200s/%.50s",
1069 _PATH_MAILDIR, pw->pw_name);
1070 child_set_env(&env, &envsize, "MAIL", buf);
1072 /* Normal systems set SHELL by default. */
1073 child_set_env(&env, &envsize, "SHELL", shell);
1076 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1078 /* Set custom environment options from RSA authentication. */
1079 if (!options.use_login) {
1080 while (custom_environment) {
1081 struct envstring *ce = custom_environment;
1084 for (i = 0; str[i] != '=' && str[i]; i++)
1086 if (str[i] == '=') {
1088 child_set_env(&env, &envsize, str, str + i + 1);
1090 custom_environment = ce->next;
1096 /* SSH_CLIENT deprecated */
1097 snprintf(buf, sizeof buf, "%.50s %d %d",
1098 get_remote_ipaddr(), get_remote_port(), get_local_port());
1099 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1101 laddr = get_local_ipaddr(packet_get_connection_in());
1102 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1103 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1105 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1108 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1110 child_set_env(&env, &envsize, "TERM", s->term);
1112 child_set_env(&env, &envsize, "DISPLAY", s->display);
1113 if (original_command)
1114 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1118 if (cray_tmpdir[0] != '\0')
1119 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1120 #endif /* _UNICOS */
1123 * Since we clear KRB5CCNAME at startup, if it's set now then it
1124 * must have been set by a native authentication method (eg AIX or
1125 * SIA), so copy it to the child.
1130 if ((cp = getenv("KRB5CCNAME")) != NULL)
1131 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1138 if ((cp = getenv("AUTHSTATE")) != NULL)
1139 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1140 read_environment_file(&env, &envsize, "/etc/environment");
1144 if (s->authctxt->krb5_ccname)
1145 child_set_env(&env, &envsize, "KRB5CCNAME",
1146 s->authctxt->krb5_ccname);
1150 * Pull in any environment variables that may have
1153 if (options.use_pam) {
1156 p = fetch_pam_child_environment();
1157 copy_environment(p, &env, &envsize);
1158 free_pam_environment(p);
1160 p = fetch_pam_environment();
1161 copy_environment(p, &env, &envsize);
1162 free_pam_environment(p);
1164 #endif /* USE_PAM */
1166 if (auth_sock_name != NULL)
1167 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1170 /* read $HOME/.ssh/environment. */
1171 if (options.permit_user_env && !options.use_login) {
1172 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1173 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1174 read_environment_file(&env, &envsize, buf);
1177 /* dump the environment */
1178 fprintf(stderr, "Environment:\n");
1179 for (i = 0; env[i]; i++)
1180 fprintf(stderr, " %.200s\n", env[i]);
1186 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1187 * first in this order).
1190 do_rc_files(Session *s, const char *shell)
1198 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1200 /* ignore _PATH_SSH_USER_RC for subsystems */
1201 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1202 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1203 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1205 fprintf(stderr, "Running %s\n", cmd);
1206 f = popen(cmd, "w");
1209 fprintf(f, "%s %s\n", s->auth_proto,
1213 fprintf(stderr, "Could not run %s\n",
1215 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1217 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1218 _PATH_SSH_SYSTEM_RC);
1219 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1222 fprintf(f, "%s %s\n", s->auth_proto,
1226 fprintf(stderr, "Could not run %s\n",
1227 _PATH_SSH_SYSTEM_RC);
1228 } else if (do_xauth && options.xauth_location != NULL) {
1229 /* Add authority data to .Xauthority if appropriate. */
1232 "Running %.500s remove %.100s\n",
1233 options.xauth_location, s->auth_display);
1235 "%.500s add %.100s %.100s %.100s\n",
1236 options.xauth_location, s->auth_display,
1237 s->auth_proto, s->auth_data);
1239 snprintf(cmd, sizeof cmd, "%s -q -",
1240 options.xauth_location);
1241 f = popen(cmd, "w");
1243 fprintf(f, "remove %s\n",
1245 fprintf(f, "add %s %s %s\n",
1246 s->auth_display, s->auth_proto,
1250 fprintf(stderr, "Could not run %s\n",
1257 do_nologin(struct passwd *pw)
1262 #ifdef HAVE_LOGIN_CAP
1263 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1264 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1265 _PATH_NOLOGIN), "r");
1268 f = fopen(_PATH_NOLOGIN, "r");
1271 /* /etc/nologin exists. Print its contents and exit. */
1272 logit("User %.100s not allowed because %s exists",
1273 pw->pw_name, _PATH_NOLOGIN);
1274 while (fgets(buf, sizeof(buf), f))
1282 /* Set login name, uid, gid, and groups. */
1284 do_setusercontext(struct passwd *pw)
1287 if (getuid() == 0 || geteuid() == 0)
1288 #endif /* HAVE_CYGWIN */
1291 #ifdef HAVE_SETPCRED
1292 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1293 fatal("Failed to set process credentials");
1294 #endif /* HAVE_SETPCRED */
1295 #ifdef HAVE_LOGIN_CAP
1300 if (options.gss_authentication) {
1301 temporarily_use_uid(pw);
1302 ssh_gssapi_storecreds();
1307 if (options.use_pam) {
1311 # endif /* USE_PAM */
1312 if (setusercontext(lc, pw, pw->pw_uid,
1313 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1314 perror("unable to set user context");
1318 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1319 /* Sets login uid for accounting */
1320 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1321 error("setluid: %s", strerror(errno));
1322 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1324 if (setlogin(pw->pw_name) < 0)
1325 error("setlogin failed: %s", strerror(errno));
1326 if (setgid(pw->pw_gid) < 0) {
1330 /* Initialize the group list. */
1331 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1332 perror("initgroups");
1337 if (options.gss_authentication) {
1338 temporarily_use_uid(pw);
1339 ssh_gssapi_storecreds();
1345 * PAM credentials may take the form of supplementary groups.
1346 * These will have been wiped by the above initgroups() call.
1347 * Reestablish them here.
1349 if (options.use_pam) {
1353 # endif /* USE_PAM */
1354 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1355 irix_setusercontext(pw);
1356 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1360 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1361 if (set_id(pw->pw_name) != 0) {
1364 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1365 /* Permanently switch to the desired uid. */
1366 permanently_set_uid(pw);
1373 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1374 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1377 ssh_selinux_setup_exec_context(pw->pw_name);
1382 do_pwchange(Session *s)
1385 fprintf(stderr, "WARNING: Your password has expired.\n");
1386 if (s->ttyfd != -1) {
1388 "You must change your password now and login again!\n");
1389 #ifdef PASSWD_NEEDS_USERNAME
1390 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1393 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1398 "Password change required but no TTY available.\n");
1404 launch_login(struct passwd *pw, const char *hostname)
1406 /* Launch login(1). */
1408 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1409 #ifdef xxxLOGIN_NEEDS_TERM
1410 (s->term ? s->term : "unknown"),
1411 #endif /* LOGIN_NEEDS_TERM */
1412 #ifdef LOGIN_NO_ENDOPT
1413 "-p", "-f", pw->pw_name, (char *)NULL);
1415 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1418 /* Login couldn't be executed, die. */
1425 child_close_fds(void)
1429 if (packet_get_connection_in() == packet_get_connection_out())
1430 close(packet_get_connection_in());
1432 close(packet_get_connection_in());
1433 close(packet_get_connection_out());
1436 * Close all descriptors related to channels. They will still remain
1437 * open in the parent.
1439 /* XXX better use close-on-exec? -markus */
1440 channel_close_all();
1443 * Close any extra file descriptors. Note that there may still be
1444 * descriptors left by system functions. They will be closed later.
1449 * Close any extra open file descriptors so that we don't have them
1450 * hanging around in clients. Note that we want to do this after
1451 * initgroups, because at least on Solaris 2.3 it leaves file
1454 for (i = 3; i < 64; i++)
1459 * Performs common processing for the child, such as setting up the
1460 * environment, closing extra file descriptors, setting the user and group
1461 * ids, and executing the command or shell.
1464 do_child(Session *s, const char *command)
1466 extern char **environ;
1469 const char *shell, *shell0, *hostname = NULL;
1470 struct passwd *pw = s->pw;
1472 /* remove hostkey from the child's memory */
1473 destroy_sensitive_data();
1475 /* Force a password change */
1476 if (s->authctxt->force_pwchange) {
1477 do_setusercontext(pw);
1483 /* login(1) is only called if we execute the login shell */
1484 if (options.use_login && command != NULL)
1485 options.use_login = 0;
1488 cray_setup(pw->pw_uid, pw->pw_name, command);
1489 #endif /* _UNICOS */
1492 * Login(1) does this as well, and it needs uid 0 for the "-h"
1493 * switch, so we let login(1) to this for us.
1495 if (!options.use_login) {
1497 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1498 if (!check_quietlogin(s, command))
1500 #else /* HAVE_OSF_SIA */
1501 /* When PAM is enabled we rely on it to do the nologin check */
1502 if (!options.use_pam)
1504 do_setusercontext(pw);
1506 * PAM session modules in do_setusercontext may have
1507 * generated messages, so if this in an interactive
1508 * login then display them too.
1510 if (!check_quietlogin(s, command))
1512 #endif /* HAVE_OSF_SIA */
1516 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1517 debug3("PAM session not opened, exiting");
1524 * Get the shell from the password data. An empty shell field is
1525 * legal, and means /bin/sh.
1527 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1530 * Make sure $SHELL points to the shell from the password file,
1531 * even if shell is overridden from login.conf
1533 env = do_setup_env(s, shell);
1535 #ifdef HAVE_LOGIN_CAP
1536 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1539 /* we have to stash the hostname before we close our socket. */
1540 if (options.use_login)
1541 hostname = get_remote_name_or_ip(utmp_len,
1544 * Close the connection descriptors; note that this is the child, and
1545 * the server will still have the socket open, and it is important
1546 * that we do not shutdown it. Note that the descriptors cannot be
1547 * closed before building the environment, as we call
1548 * get_remote_ipaddr there.
1553 * Must take new environment into use so that .ssh/rc,
1554 * /etc/ssh/sshrc and xauth are run in the proper environment.
1558 #if defined(KRB5) && defined(USE_AFS)
1560 * At this point, we check to see if AFS is active and if we have
1561 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1562 * if we can (and need to) extend the ticket into an AFS token. If
1563 * we don't do this, we run into potential problems if the user's
1564 * home directory is in AFS and it's not world-readable.
1567 if (options.kerberos_get_afs_token && k_hasafs() &&
1568 (s->authctxt->krb5_ctx != NULL)) {
1571 debug("Getting AFS token");
1575 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1576 krb5_afslog(s->authctxt->krb5_ctx,
1577 s->authctxt->krb5_fwd_ccache, cell, NULL);
1579 krb5_afslog_home(s->authctxt->krb5_ctx,
1580 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1584 /* Change current directory to the user's home directory. */
1585 if (chdir(pw->pw_dir) < 0) {
1586 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1587 pw->pw_dir, strerror(errno));
1588 #ifdef HAVE_LOGIN_CAP
1589 if (login_getcapbool(lc, "requirehome", 0))
1594 if (!options.use_login)
1595 do_rc_files(s, shell);
1597 /* restore SIGPIPE for child */
1598 signal(SIGPIPE, SIG_DFL);
1600 if (options.use_login) {
1601 launch_login(pw, hostname);
1605 /* Get the last component of the shell name. */
1606 if ((shell0 = strrchr(shell, '/')) != NULL)
1612 * If we have no command, execute the shell. In this case, the shell
1613 * name to be passed in argv[0] is preceded by '-' to indicate that
1614 * this is a login shell.
1619 /* Start the shell. Set initial character to '-'. */
1622 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1623 >= sizeof(argv0) - 1) {
1629 /* Execute the shell. */
1632 execve(shell, argv, env);
1634 /* Executing the shell failed. */
1639 * Execute the command using the user's shell. This uses the -c
1640 * option to execute the command.
1642 argv[0] = (char *) shell0;
1644 argv[2] = (char *) command;
1646 execve(shell, argv, env);
1655 static int did_init = 0;
1657 debug("session_new: init");
1658 for (i = 0; i < MAX_SESSIONS; i++) {
1659 sessions[i].used = 0;
1663 for (i = 0; i < MAX_SESSIONS; i++) {
1664 Session *s = &sessions[i];
1666 memset(s, 0, sizeof(*s));
1672 s->x11_chanids = NULL;
1673 debug("session_new: session %d", i);
1684 for (i = 0; i < MAX_SESSIONS; i++) {
1685 Session *s = &sessions[i];
1686 debug("dump: used %d session %d %p channel %d pid %ld",
1696 session_open(Authctxt *authctxt, int chanid)
1698 Session *s = session_new();
1699 debug("session_open: channel %d", chanid);
1701 error("no more sessions");
1704 s->authctxt = authctxt;
1705 s->pw = authctxt->pw;
1706 if (s->pw == NULL || !authctxt->valid)
1707 fatal("no user for session %d", s->self);
1708 debug("session_open: session %d: link with channel %d", s->self, chanid);
1714 session_by_tty(char *tty)
1717 for (i = 0; i < MAX_SESSIONS; i++) {
1718 Session *s = &sessions[i];
1719 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1720 debug("session_by_tty: session %d tty %s", i, tty);
1724 debug("session_by_tty: unknown tty %.100s", tty);
1730 session_by_channel(int id)
1733 for (i = 0; i < MAX_SESSIONS; i++) {
1734 Session *s = &sessions[i];
1735 if (s->used && s->chanid == id) {
1736 debug("session_by_channel: session %d channel %d", i, id);
1740 debug("session_by_channel: unknown channel %d", id);
1746 session_by_x11_channel(int id)
1750 for (i = 0; i < MAX_SESSIONS; i++) {
1751 Session *s = &sessions[i];
1753 if (s->x11_chanids == NULL || !s->used)
1755 for (j = 0; s->x11_chanids[j] != -1; j++) {
1756 if (s->x11_chanids[j] == id) {
1757 debug("session_by_x11_channel: session %d "
1758 "channel %d", s->self, id);
1763 debug("session_by_x11_channel: unknown channel %d", id);
1769 session_by_pid(pid_t pid)
1772 debug("session_by_pid: pid %ld", (long)pid);
1773 for (i = 0; i < MAX_SESSIONS; i++) {
1774 Session *s = &sessions[i];
1775 if (s->used && s->pid == pid)
1778 error("session_by_pid: unknown pid %ld", (long)pid);
1784 session_window_change_req(Session *s)
1786 s->col = packet_get_int();
1787 s->row = packet_get_int();
1788 s->xpixel = packet_get_int();
1789 s->ypixel = packet_get_int();
1791 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1796 session_pty_req(Session *s)
1802 debug("Allocating a pty not permitted for this authentication.");
1805 if (s->ttyfd != -1) {
1806 packet_disconnect("Protocol error: you already have a pty.");
1810 s->term = packet_get_string(&len);
1813 s->col = packet_get_int();
1814 s->row = packet_get_int();
1816 s->row = packet_get_int();
1817 s->col = packet_get_int();
1819 s->xpixel = packet_get_int();
1820 s->ypixel = packet_get_int();
1822 if (strcmp(s->term, "") == 0) {
1827 /* Allocate a pty and open it. */
1828 debug("Allocating pty.");
1829 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1835 error("session_pty_req: session %d alloc failed", s->self);
1838 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1840 /* for SSH1 the tty modes length is not given */
1842 n_bytes = packet_remaining();
1843 tty_parse_modes(s->ttyfd, &n_bytes);
1846 pty_setowner(s->pw, s->tty);
1848 /* Set window size from the packet. */
1849 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1852 session_proctitle(s);
1857 session_subsystem_req(Session *s)
1862 char *prog, *cmd, *subsys = packet_get_string(&len);
1866 logit("subsystem request for %.100s", subsys);
1868 for (i = 0; i < options.num_subsystems; i++) {
1869 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1870 prog = options.subsystem_command[i];
1871 cmd = options.subsystem_args[i];
1872 if (stat(prog, &st) < 0) {
1873 error("subsystem: cannot stat %s: %s", prog,
1877 debug("subsystem: exec() %s", cmd);
1878 s->is_subsystem = 1;
1886 logit("subsystem request for %.100s failed, subsystem not found",
1894 session_x11_req(Session *s)
1898 if (s->auth_proto != NULL || s->auth_data != NULL) {
1899 error("session_x11_req: session %d: "
1900 "x11 forwarding already active", s->self);
1903 s->single_connection = packet_get_char();
1904 s->auth_proto = packet_get_string(NULL);
1905 s->auth_data = packet_get_string(NULL);
1906 s->screen = packet_get_int();
1909 success = session_setup_x11fwd(s);
1911 xfree(s->auth_proto);
1912 xfree(s->auth_data);
1913 s->auth_proto = NULL;
1914 s->auth_data = NULL;
1920 session_shell_req(Session *s)
1928 session_exec_req(Session *s)
1931 char *command = packet_get_string(&len);
1933 do_exec(s, command);
1939 session_break_req(Session *s)
1942 packet_get_int(); /* ignored */
1945 if (s->ttyfd == -1 ||
1946 tcsendbreak(s->ttyfd, 0) < 0)
1952 session_env_req(Session *s)
1955 u_int name_len, val_len, i;
1957 name = packet_get_string(&name_len);
1958 val = packet_get_string(&val_len);
1961 /* Don't set too many environment variables */
1962 if (s->num_env > 128) {
1963 debug2("Ignoring env request %s: too many env vars", name);
1967 for (i = 0; i < options.num_accept_env; i++) {
1968 if (match_pattern(name, options.accept_env[i])) {
1969 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1970 s->env = xrealloc(s->env, s->num_env + 1,
1972 s->env[s->num_env].name = name;
1973 s->env[s->num_env].val = val;
1978 debug2("Ignoring env request %s: disallowed name", name);
1987 session_auth_agent_req(Session *s)
1989 static int called = 0;
1991 if (no_agent_forwarding_flag) {
1992 debug("session_auth_agent_req: no_agent_forwarding_flag");
1999 return auth_input_request_forwarding(s->pw);
2004 session_input_channel_req(Channel *c, const char *rtype)
2009 if ((s = session_by_channel(c->self)) == NULL) {
2010 logit("session_input_channel_req: no session %d req %.100s",
2014 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2017 * a session is in LARVAL state until a shell, a command
2018 * or a subsystem is executed
2020 if (c->type == SSH_CHANNEL_LARVAL) {
2021 if (strcmp(rtype, "shell") == 0) {
2022 success = session_shell_req(s);
2023 } else if (strcmp(rtype, "exec") == 0) {
2024 success = session_exec_req(s);
2025 } else if (strcmp(rtype, "pty-req") == 0) {
2026 success = session_pty_req(s);
2027 } else if (strcmp(rtype, "x11-req") == 0) {
2028 success = session_x11_req(s);
2029 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2030 success = session_auth_agent_req(s);
2031 } else if (strcmp(rtype, "subsystem") == 0) {
2032 success = session_subsystem_req(s);
2033 } else if (strcmp(rtype, "env") == 0) {
2034 success = session_env_req(s);
2037 if (strcmp(rtype, "window-change") == 0) {
2038 success = session_window_change_req(s);
2039 } else if (strcmp(rtype, "break") == 0) {
2040 success = session_break_req(s);
2047 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2050 fatal("session_set_fds: called for proto != 2.0");
2052 * now that have a child and a pipe to the child,
2053 * we can activate our channel and register the fd's
2055 if (s->chanid == -1)
2056 fatal("no channel for session %d", s->self);
2057 channel_set_fds(s->chanid,
2059 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2061 CHAN_SES_WINDOW_DEFAULT);
2065 * Function to perform pty cleanup. Also called if we get aborted abnormally
2066 * (e.g., due to a dropped connection).
2069 session_pty_cleanup2(Session *s)
2072 error("session_pty_cleanup: no session");
2078 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2080 /* Record that the user has logged out. */
2082 record_logout(s->pid, s->tty, s->pw->pw_name);
2084 /* Release the pseudo-tty. */
2086 pty_release(s->tty);
2089 * Close the server side of the socket pairs. We must do this after
2090 * the pty cleanup, so that another process doesn't get this pty
2091 * while we're still cleaning up.
2093 if (close(s->ptymaster) < 0)
2094 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2096 /* unlink pty from session */
2101 session_pty_cleanup(Session *s)
2103 PRIVSEP(session_pty_cleanup2(s));
2109 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2124 return "SIG@openssh.com";
2128 session_close_x11(int id)
2132 if ((c = channel_by_id(id)) == NULL) {
2133 debug("session_close_x11: x11 channel %d missing", id);
2135 /* Detach X11 listener */
2136 debug("session_close_x11: detach x11 channel %d", id);
2137 channel_cancel_cleanup(id);
2138 if (c->ostate != CHAN_OUTPUT_CLOSED)
2144 session_close_single_x11(int id, void *arg)
2149 debug3("session_close_single_x11: channel %d", id);
2150 channel_cancel_cleanup(id);
2151 if ((s = session_by_x11_channel(id)) == NULL)
2152 fatal("session_close_single_x11: no x11 channel %d", id);
2153 for (i = 0; s->x11_chanids[i] != -1; i++) {
2154 debug("session_close_single_x11: session %d: "
2155 "closing channel %d", s->self, s->x11_chanids[i]);
2157 * The channel "id" is already closing, but make sure we
2158 * close all of its siblings.
2160 if (s->x11_chanids[i] != id)
2161 session_close_x11(s->x11_chanids[i]);
2163 xfree(s->x11_chanids);
2164 s->x11_chanids = NULL;
2169 if (s->auth_proto) {
2170 xfree(s->auth_proto);
2171 s->auth_proto = NULL;
2174 xfree(s->auth_data);
2175 s->auth_data = NULL;
2177 if (s->auth_display) {
2178 xfree(s->auth_display);
2179 s->auth_display = NULL;
2184 session_exit_message(Session *s, int status)
2188 if ((c = channel_lookup(s->chanid)) == NULL)
2189 fatal("session_exit_message: session %d: no channel %d",
2190 s->self, s->chanid);
2191 debug("session_exit_message: session %d channel %d pid %ld",
2192 s->self, s->chanid, (long)s->pid);
2194 if (WIFEXITED(status)) {
2195 channel_request_start(s->chanid, "exit-status", 0);
2196 packet_put_int(WEXITSTATUS(status));
2198 } else if (WIFSIGNALED(status)) {
2199 channel_request_start(s->chanid, "exit-signal", 0);
2200 packet_put_cstring(sig2name(WTERMSIG(status)));
2202 packet_put_char(WCOREDUMP(status));
2203 #else /* WCOREDUMP */
2205 #endif /* WCOREDUMP */
2206 packet_put_cstring("");
2207 packet_put_cstring("");
2210 /* Some weird exit cause. Just exit. */
2211 packet_disconnect("wait returned status %04x.", status);
2214 /* disconnect channel */
2215 debug("session_exit_message: release channel %d", s->chanid);
2218 * Adjust cleanup callback attachment to send close messages when
2219 * the channel gets EOF. The session will be then be closed
2220 * by session_close_by_channel when the childs close their fds.
2222 channel_register_cleanup(c->self, session_close_by_channel, 1);
2225 * emulate a write failure with 'chan_write_failed', nobody will be
2226 * interested in data we write.
2227 * Note that we must not call 'chan_read_failed', since there could
2228 * be some more data waiting in the pipe.
2230 if (c->ostate != CHAN_OUTPUT_CLOSED)
2231 chan_write_failed(c);
2235 session_close(Session *s)
2239 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2241 session_pty_cleanup(s);
2247 xfree(s->x11_chanids);
2248 if (s->auth_display)
2249 xfree(s->auth_display);
2251 xfree(s->auth_data);
2253 xfree(s->auth_proto);
2255 for (i = 0; i < s->num_env; i++) {
2256 xfree(s->env[i].name);
2257 xfree(s->env[i].val);
2261 session_proctitle(s);
2265 session_close_by_pid(pid_t pid, int status)
2267 Session *s = session_by_pid(pid);
2269 debug("session_close_by_pid: no session for pid %ld",
2273 if (s->chanid != -1)
2274 session_exit_message(s, status);
2276 session_pty_cleanup(s);
2281 * this is called when a channel dies before
2282 * the session 'child' itself dies
2285 session_close_by_channel(int id, void *arg)
2287 Session *s = session_by_channel(id);
2291 debug("session_close_by_channel: no session for id %d", id);
2294 debug("session_close_by_channel: channel %d child %ld",
2297 debug("session_close_by_channel: channel %d: has child", id);
2299 * delay detach of session, but release pty, since
2300 * the fd's to the child are already closed
2303 session_pty_cleanup(s);
2306 /* detach by removing callback */
2307 channel_cancel_cleanup(s->chanid);
2309 /* Close any X11 listeners associated with this session */
2310 if (s->x11_chanids != NULL) {
2311 for (i = 0; s->x11_chanids[i] != -1; i++) {
2312 session_close_x11(s->x11_chanids[i]);
2313 s->x11_chanids[i] = -1;
2322 session_destroy_all(void (*closefunc)(Session *))
2325 for (i = 0; i < MAX_SESSIONS; i++) {
2326 Session *s = &sessions[i];
2328 if (closefunc != NULL)
2337 session_tty_list(void)
2339 static char buf[1024];
2344 for (i = 0; i < MAX_SESSIONS; i++) {
2345 Session *s = &sessions[i];
2346 if (s->used && s->ttyfd != -1) {
2348 if (strncmp(s->tty, "/dev/", 5) != 0) {
2349 cp = strrchr(s->tty, '/');
2350 cp = (cp == NULL) ? s->tty : cp + 1;
2355 strlcat(buf, ",", sizeof buf);
2356 strlcat(buf, cp, sizeof buf);
2360 strlcpy(buf, "notty", sizeof buf);
2365 session_proctitle(Session *s)
2368 error("no user for session %d", s->self);
2370 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2374 session_setup_x11fwd(Session *s)
2377 char display[512], auth_display[512];
2378 char hostname[MAXHOSTNAMELEN];
2381 if (no_x11_forwarding_flag) {
2382 packet_send_debug("X11 forwarding disabled in user configuration file.");
2385 if (!options.x11_forwarding) {
2386 debug("X11 forwarding disabled in server configuration file.");
2389 if (!options.xauth_location ||
2390 (stat(options.xauth_location, &st) == -1)) {
2391 packet_send_debug("No xauth program; cannot forward with spoofing.");
2394 if (options.use_login) {
2395 packet_send_debug("X11 forwarding disabled; "
2396 "not compatible with UseLogin=yes.");
2399 if (s->display != NULL) {
2400 debug("X11 display already set.");
2403 if (x11_create_display_inet(options.x11_display_offset,
2404 options.x11_use_localhost, s->single_connection,
2405 &s->display_number, &s->x11_chanids) == -1) {
2406 debug("x11_create_display_inet failed.");
2409 for (i = 0; s->x11_chanids[i] != -1; i++) {
2410 channel_register_cleanup(s->x11_chanids[i],
2411 session_close_single_x11, 0);
2414 /* Set up a suitable value for the DISPLAY variable. */
2415 if (gethostname(hostname, sizeof(hostname)) < 0)
2416 fatal("gethostname: %.100s", strerror(errno));
2418 * auth_display must be used as the displayname when the
2419 * authorization entry is added with xauth(1). This will be
2420 * different than the DISPLAY string for localhost displays.
2422 if (options.x11_use_localhost) {
2423 snprintf(display, sizeof display, "localhost:%u.%u",
2424 s->display_number, s->screen);
2425 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2426 s->display_number, s->screen);
2427 s->display = xstrdup(display);
2428 s->auth_display = xstrdup(auth_display);
2430 #ifdef IPADDR_IN_DISPLAY
2432 struct in_addr my_addr;
2434 he = gethostbyname(hostname);
2436 error("Can't get IP address for X11 DISPLAY.");
2437 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2440 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2441 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2442 s->display_number, s->screen);
2444 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2445 s->display_number, s->screen);
2447 s->display = xstrdup(display);
2448 s->auth_display = xstrdup(display);
2455 do_authenticated2(Authctxt *authctxt)
2457 server_loop2(authctxt);
2461 do_cleanup(Authctxt *authctxt)
2463 static int called = 0;
2465 debug("do_cleanup");
2467 /* no cleanup if we're in the child for login shell */
2471 /* avoid double cleanup */
2476 if (authctxt == NULL)
2479 if (options.kerberos_ticket_cleanup &&
2481 krb5_cleanup_proc(authctxt);
2485 if (compat20 && options.gss_cleanup_creds)
2486 ssh_gssapi_cleanup_creds();
2490 if (options.use_pam) {
2492 sshpam_thread_cleanup();
2496 /* remove agent socket */
2497 auth_sock_cleanup_proc(authctxt->pw);
2500 * Cleanup ptys/utmp only if privsep is disabled,
2501 * or if running in monitor.
2503 if (!use_privsep || mm_is_monitor())
2504 session_destroy_all(session_pty_cleanup2);