2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * As far as I am concerned, the code I have written for this software
6 * can be used freely for any purpose. Any derived versions of this
7 * software must be clearly marked as such, and if the derived work is
8 * incompatible with the protocol description in the RFC file, it must be
9 * called by a name other than "ssh" or "Secure Shell".
11 * SSH2 support by Markus Friedl.
12 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 RCSID("$OpenBSD: session.c,v 1.191 2005/12/24 02:27:41 djm Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
61 #include "monitor_wrap.h"
63 #if defined(KRB5) && defined(USE_AFS)
73 Session *session_new(void);
74 void session_set_fds(Session *, int, int, int);
75 void session_pty_cleanup(Session *);
76 void session_proctitle(Session *);
77 int session_setup_x11fwd(Session *);
78 void do_exec_pty(Session *, const char *);
79 void do_exec_no_pty(Session *, const char *);
80 void do_exec(Session *, const char *);
81 void do_login(Session *, const char *);
82 #ifdef LOGIN_NEEDS_UTMPX
83 static void do_pre_login(Session *s);
85 void do_child(Session *, const char *);
87 int check_quietlogin(Session *, const char *);
89 static void do_authenticated1(Authctxt *);
90 static void do_authenticated2(Authctxt *);
92 static int session_pty_req(Session *);
95 extern ServerOptions options;
96 extern char *__progname;
97 extern int log_stderr;
98 extern int debug_flag;
99 extern u_int utmp_len;
100 extern int startup_pipe;
101 extern void destroy_sensitive_data(void);
102 extern Buffer loginmsg;
104 /* original command from peer. */
105 const char *original_command = NULL;
108 #define MAX_SESSIONS 10
109 Session sessions[MAX_SESSIONS];
111 #ifdef HAVE_LOGIN_CAP
115 static int is_child = 0;
117 /* Name and directory of socket for authentication agent forwarding. */
118 static char *auth_sock_name = NULL;
119 static char *auth_sock_dir = NULL;
121 /* removes the agent forwarding socket */
124 auth_sock_cleanup_proc(struct passwd *pw)
126 if (auth_sock_name != NULL) {
127 temporarily_use_uid(pw);
128 unlink(auth_sock_name);
129 rmdir(auth_sock_dir);
130 auth_sock_name = NULL;
136 auth_input_request_forwarding(struct passwd * pw)
140 struct sockaddr_un sunaddr;
142 if (auth_sock_name != NULL) {
143 error("authentication forwarding requested twice.");
147 /* Temporarily drop privileged uid for mkdir/bind. */
148 temporarily_use_uid(pw);
150 /* Allocate a buffer for the socket name, and format the name. */
151 auth_sock_name = xmalloc(MAXPATHLEN);
152 auth_sock_dir = xmalloc(MAXPATHLEN);
153 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
155 /* Create private directory for socket */
156 if (mkdtemp(auth_sock_dir) == NULL) {
157 packet_send_debug("Agent forwarding disabled: "
158 "mkdtemp() failed: %.100s", strerror(errno));
160 xfree(auth_sock_name);
161 xfree(auth_sock_dir);
162 auth_sock_name = NULL;
163 auth_sock_dir = NULL;
166 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
167 auth_sock_dir, (long) getpid());
169 /* Create the socket. */
170 sock = socket(AF_UNIX, SOCK_STREAM, 0);
172 packet_disconnect("socket: %.100s", strerror(errno));
174 /* Bind it to the name. */
175 memset(&sunaddr, 0, sizeof(sunaddr));
176 sunaddr.sun_family = AF_UNIX;
177 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
179 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
180 packet_disconnect("bind: %.100s", strerror(errno));
182 /* Restore the privileged uid. */
185 /* Start listening on the socket. */
186 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
187 packet_disconnect("listen: %.100s", strerror(errno));
189 /* Allocate a channel for the authentication agent socket. */
190 nc = channel_new("auth socket",
191 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
192 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
193 0, "auth socket", 1);
194 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
199 display_loginmsg(void)
201 if (buffer_len(&loginmsg) > 0) {
202 buffer_append(&loginmsg, "\0", 1);
203 printf("%s", (char *)buffer_ptr(&loginmsg));
204 buffer_clear(&loginmsg);
209 do_authenticated(Authctxt *authctxt)
211 setproctitle("%s", authctxt->pw->pw_name);
213 /* setup the channel layer */
214 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
215 channel_permit_all_opens();
218 do_authenticated2(authctxt);
220 do_authenticated1(authctxt);
222 do_cleanup(authctxt);
226 * Prepares for an interactive session. This is called after the user has
227 * been successfully authenticated. During this message exchange, pseudo
228 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
229 * are requested, etc.
232 do_authenticated1(Authctxt *authctxt)
236 int success, type, screen_flag;
237 int enable_compression_after_reply = 0;
238 u_int proto_len, data_len, dlen, compression_level = 0;
242 error("no more sessions");
245 s->authctxt = authctxt;
246 s->pw = authctxt->pw;
249 * We stay in this loop until the client requests to execute a shell
255 /* Get a packet from the client. */
256 type = packet_read();
258 /* Process the packet. */
260 case SSH_CMSG_REQUEST_COMPRESSION:
261 compression_level = packet_get_int();
263 if (compression_level < 1 || compression_level > 9) {
264 packet_send_debug("Received invalid compression level %d.",
268 if (options.compression == COMP_NONE) {
269 debug2("compression disabled");
272 /* Enable compression after we have responded with SUCCESS. */
273 enable_compression_after_reply = 1;
277 case SSH_CMSG_REQUEST_PTY:
278 success = session_pty_req(s);
281 case SSH_CMSG_X11_REQUEST_FORWARDING:
282 s->auth_proto = packet_get_string(&proto_len);
283 s->auth_data = packet_get_string(&data_len);
285 screen_flag = packet_get_protocol_flags() &
286 SSH_PROTOFLAG_SCREEN_NUMBER;
287 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
289 if (packet_remaining() == 4) {
291 debug2("Buggy client: "
292 "X11 screen flag missing");
293 s->screen = packet_get_int();
298 success = session_setup_x11fwd(s);
300 xfree(s->auth_proto);
302 s->auth_proto = NULL;
307 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
308 if (no_agent_forwarding_flag || compat13) {
309 debug("Authentication agent forwarding not permitted for this authentication.");
312 debug("Received authentication agent forwarding request.");
313 success = auth_input_request_forwarding(s->pw);
316 case SSH_CMSG_PORT_FORWARD_REQUEST:
317 if (no_port_forwarding_flag) {
318 debug("Port forwarding not permitted for this authentication.");
321 if (!options.allow_tcp_forwarding) {
322 debug("Port forwarding not permitted.");
325 debug("Received TCP/IP port forwarding request.");
326 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
330 case SSH_CMSG_MAX_PACKET_SIZE:
331 if (packet_set_maxsize(packet_get_int()) > 0)
335 case SSH_CMSG_EXEC_SHELL:
336 case SSH_CMSG_EXEC_CMD:
337 if (type == SSH_CMSG_EXEC_CMD) {
338 command = packet_get_string(&dlen);
339 debug("Exec command '%.500s'", command);
351 * Any unknown messages in this phase are ignored,
352 * and a failure message is returned.
354 logit("Unknown packet type received after authentication: %d", type);
356 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
360 /* Enable compression now that we have replied if appropriate. */
361 if (enable_compression_after_reply) {
362 enable_compression_after_reply = 0;
363 packet_start_compression(compression_level);
369 * This is called to fork and execute a command when we have no tty. This
370 * will call do_child from the child, and server_loop from the parent after
371 * setting up file descriptors and such.
374 do_exec_no_pty(Session *s, const char *command)
379 int pin[2], pout[2], perr[2];
380 /* Allocate pipes for communicating with the program. */
381 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
382 packet_disconnect("Could not create pipes: %.100s",
384 #else /* USE_PIPES */
385 int inout[2], err[2];
386 /* Uses socket pairs to communicate with the program. */
387 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
388 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
389 packet_disconnect("Could not create socket pairs: %.100s",
391 #endif /* USE_PIPES */
393 fatal("do_exec_no_pty: no session");
395 session_proctitle(s);
398 if (options.use_pam && !use_privsep)
402 /* Fork the child. */
403 if ((pid = fork()) == 0) {
406 /* Child. Reinitialize the log since the pid has changed. */
407 log_init(__progname, options.log_level, options.log_facility, log_stderr);
410 * Create a new session and process group since the 4.4BSD
411 * setlogin() affects the entire process group.
414 error("setsid failed: %.100s", strerror(errno));
418 * Redirect stdin. We close the parent side of the socket
419 * pair, and make the child side the standard input.
422 if (dup2(pin[0], 0) < 0)
423 perror("dup2 stdin");
426 /* Redirect stdout. */
428 if (dup2(pout[1], 1) < 0)
429 perror("dup2 stdout");
432 /* Redirect stderr. */
434 if (dup2(perr[1], 2) < 0)
435 perror("dup2 stderr");
437 #else /* USE_PIPES */
439 * Redirect stdin, stdout, and stderr. Stdin and stdout will
440 * use the same socket, as some programs (particularly rdist)
441 * seem to depend on it.
445 if (dup2(inout[0], 0) < 0) /* stdin */
446 perror("dup2 stdin");
447 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
448 perror("dup2 stdout");
449 if (dup2(err[0], 2) < 0) /* stderr */
450 perror("dup2 stderr");
451 #endif /* USE_PIPES */
454 cray_init_job(s->pw); /* set up cray jid and tmpdir */
457 /* Do processing for the child (exec command etc). */
458 do_child(s, command);
462 signal(WJSIGNAL, cray_job_termination_handler);
466 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
469 packet_disconnect("fork failed: %.100s", strerror(errno));
471 /* Set interactive/non-interactive mode. */
472 packet_set_interactive(s->display != NULL);
474 /* We are the parent. Close the child sides of the pipes. */
480 if (s->is_subsystem) {
484 session_set_fds(s, pin[1], pout[0], perr[0]);
486 /* Enter the interactive session. */
487 server_loop(pid, pin[1], pout[0], perr[0]);
488 /* server_loop has closed pin[1], pout[0], and perr[0]. */
490 #else /* USE_PIPES */
491 /* We are the parent. Close the child sides of the socket pairs. */
496 * Clear loginmsg, since it's the child's responsibility to display
497 * it to the user, otherwise multiple sessions may accumulate
498 * multiple copies of the login messages.
500 buffer_clear(&loginmsg);
503 * Enter the interactive session. Note: server_loop must be able to
504 * handle the case that fdin and fdout are the same.
507 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
509 server_loop(pid, inout[1], inout[1], err[1]);
510 /* server_loop has closed inout[1] and err[1]. */
512 #endif /* USE_PIPES */
516 * This is called to fork and execute a command when we have a tty. This
517 * will call do_child from the child, and server_loop from the parent after
518 * setting up file descriptors, controlling tty, updating wtmp, utmp,
519 * lastlog, and other such operations.
522 do_exec_pty(Session *s, const char *command)
524 int fdout, ptyfd, ttyfd, ptymaster;
528 fatal("do_exec_pty: no session");
533 if (options.use_pam) {
534 do_pam_set_tty(s->tty);
540 /* Fork the child. */
541 if ((pid = fork()) == 0) {
544 /* Child. Reinitialize the log because the pid has changed. */
545 log_init(__progname, options.log_level, options.log_facility, log_stderr);
546 /* Close the master side of the pseudo tty. */
549 /* Make the pseudo tty our controlling tty. */
550 pty_make_controlling_tty(&ttyfd, s->tty);
552 /* Redirect stdin/stdout/stderr from the pseudo tty. */
553 if (dup2(ttyfd, 0) < 0)
554 error("dup2 stdin: %s", strerror(errno));
555 if (dup2(ttyfd, 1) < 0)
556 error("dup2 stdout: %s", strerror(errno));
557 if (dup2(ttyfd, 2) < 0)
558 error("dup2 stderr: %s", strerror(errno));
560 /* Close the extra descriptor for the pseudo tty. */
563 /* record login, etc. similar to login(1) */
565 if (!(options.use_login && command == NULL)) {
567 cray_init_job(s->pw); /* set up cray jid and tmpdir */
569 do_login(s, command);
571 # ifdef LOGIN_NEEDS_UTMPX
577 /* Do common processing for the child, such as execing the command. */
578 do_child(s, command);
582 signal(WJSIGNAL, cray_job_termination_handler);
586 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
589 packet_disconnect("fork failed: %.100s", strerror(errno));
592 /* Parent. Close the slave side of the pseudo tty. */
596 * Create another descriptor of the pty master side for use as the
597 * standard input. We could use the original descriptor, but this
598 * simplifies code in server_loop. The descriptor is bidirectional.
602 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
604 /* we keep a reference to the pty master */
605 ptymaster = dup(ptyfd);
607 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
608 s->ptymaster = ptymaster;
610 /* Enter interactive session. */
611 packet_set_interactive(1);
613 session_set_fds(s, ptyfd, fdout, -1);
615 server_loop(pid, ptyfd, fdout, -1);
616 /* server_loop _has_ closed ptyfd and fdout. */
620 #ifdef LOGIN_NEEDS_UTMPX
622 do_pre_login(Session *s)
625 struct sockaddr_storage from;
626 pid_t pid = getpid();
629 * Get IP address of client. If the connection is not a socket, let
630 * the address be 0.0.0.0.
632 memset(&from, 0, sizeof(from));
633 fromlen = sizeof(from);
634 if (packet_connection_is_on_socket()) {
635 if (getpeername(packet_get_connection_in(),
636 (struct sockaddr *) & from, &fromlen) < 0) {
637 debug("getpeername: %.100s", strerror(errno));
642 record_utmp_only(pid, s->tty, s->pw->pw_name,
643 get_remote_name_or_ip(utmp_len, options.use_dns),
644 (struct sockaddr *)&from, fromlen);
649 * This is called to fork and execute a command. If another command is
650 * to be forced, execute that instead.
653 do_exec(Session *s, const char *command)
655 if (forced_command) {
656 original_command = command;
657 command = forced_command;
658 debug("Forced command '%.900s'", command);
661 #ifdef SSH_AUDIT_EVENTS
663 PRIVSEP(audit_run_command(command));
664 else if (s->ttyfd == -1) {
665 char *shell = s->pw->pw_shell;
667 if (shell[0] == '\0') /* empty shell means /bin/sh */
669 PRIVSEP(audit_run_command(shell));
674 do_exec_pty(s, command);
676 do_exec_no_pty(s, command);
678 original_command = NULL;
681 * Clear loginmsg: it's the child's responsibility to display
682 * it to the user, otherwise multiple sessions may accumulate
683 * multiple copies of the login messages.
685 buffer_clear(&loginmsg);
688 /* administrative, login(1)-like work */
690 do_login(Session *s, const char *command)
693 struct sockaddr_storage from;
694 struct passwd * pw = s->pw;
695 pid_t pid = getpid();
698 * Get IP address of client. If the connection is not a socket, let
699 * the address be 0.0.0.0.
701 memset(&from, 0, sizeof(from));
702 fromlen = sizeof(from);
703 if (packet_connection_is_on_socket()) {
704 if (getpeername(packet_get_connection_in(),
705 (struct sockaddr *) & from, &fromlen) < 0) {
706 debug("getpeername: %.100s", strerror(errno));
711 /* Record that there was a login on that tty from the remote host. */
713 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
714 get_remote_name_or_ip(utmp_len,
716 (struct sockaddr *)&from, fromlen);
720 * If password change is needed, do it now.
721 * This needs to occur before the ~/.hushlogin check.
723 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
726 s->authctxt->force_pwchange = 0;
727 /* XXX - signal [net] parent to enable forwardings */
731 if (check_quietlogin(s, command))
740 * Display the message of the day.
747 #ifdef HAVE_LOGIN_CAP
751 #ifdef HAVE_LOGIN_CAP
752 fname = login_getcapstr(lc, "copyright", NULL, NULL);
753 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
754 while (fgets(buf, sizeof(buf), f) != NULL)
758 #endif /* HAVE_LOGIN_CAP */
759 (void)printf("%s\n\t%s %s\n",
760 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
761 "The Regents of the University of California. ",
762 "All rights reserved.");
766 if (options.print_motd) {
767 #ifdef HAVE_LOGIN_CAP
768 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
771 f = fopen("/etc/motd", "r");
774 while (fgets(buf, sizeof(buf), f))
783 * Check for quiet login, either .hushlogin or command given.
786 check_quietlogin(Session *s, const char *command)
789 struct passwd *pw = s->pw;
792 /* Return 1 if .hushlogin exists or a command given. */
795 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
796 #ifdef HAVE_LOGIN_CAP
797 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
800 if (stat(buf, &st) >= 0)
807 * Sets the value of the given variable in the environment. If the variable
808 * already exists, its value is overriden.
811 child_set_env(char ***envp, u_int *envsizep, const char *name,
819 * If we're passed an uninitialized list, allocate a single null
820 * entry before continuing.
822 if (*envp == NULL && *envsizep == 0) {
823 *envp = xmalloc(sizeof(char *));
829 * Find the slot where the value should be stored. If the variable
830 * already exists, we reuse the slot; otherwise we append a new slot
831 * at the end of the array, expanding if necessary.
834 namelen = strlen(name);
835 for (i = 0; env[i]; i++)
836 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
839 /* Reuse the slot. */
842 /* New variable. Expand if necessary. */
844 if (i >= envsize - 1) {
846 fatal("child_set_env: too many env vars");
848 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
851 /* Need to set the NULL pointer at end of array beyond the new slot. */
855 /* Allocate space and format the variable in the appropriate slot. */
856 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
857 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
861 * Reads environment variables from the given file and adds/overrides them
862 * into the environment. If the file does not exist, this does nothing.
863 * Otherwise, it must consist of empty lines, comments (line starts with '#')
864 * and assignments of the form name=value. No other forms are allowed.
867 read_environment_file(char ***env, u_int *envsize,
868 const char *filename)
875 f = fopen(filename, "r");
879 while (fgets(buf, sizeof(buf), f)) {
881 fatal("Too many lines in environment file %s", filename);
882 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
884 if (!*cp || *cp == '#' || *cp == '\n')
886 if (strchr(cp, '\n'))
887 *strchr(cp, '\n') = '\0';
888 value = strchr(cp, '=');
890 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
895 * Replace the equals sign by nul, and advance value to
900 child_set_env(env, envsize, cp, value);
905 #ifdef HAVE_ETC_DEFAULT_LOGIN
907 * Return named variable from specified environment, or NULL if not present.
910 child_get_env(char **env, const char *name)
916 for (i=0; env[i] != NULL; i++)
917 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
918 return(env[i] + len + 1);
923 * Read /etc/default/login.
924 * We pick up the PATH (or SUPATH for root) and UMASK.
927 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
929 char **tmpenv = NULL, *var;
930 u_int i, tmpenvsize = 0;
934 * We don't want to copy the whole file to the child's environment,
935 * so we use a temporary environment and copy the variables we're
938 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
944 var = child_get_env(tmpenv, "SUPATH");
946 var = child_get_env(tmpenv, "PATH");
948 child_set_env(env, envsize, "PATH", var);
950 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
951 if (sscanf(var, "%5lo", &mask) == 1)
954 for (i = 0; tmpenv[i] != NULL; i++)
958 #endif /* HAVE_ETC_DEFAULT_LOGIN */
961 copy_environment(char **source, char ***env, u_int *envsize)
963 char *var_name, *var_val;
969 for(i = 0; source[i] != NULL; i++) {
970 var_name = xstrdup(source[i]);
971 if ((var_val = strstr(var_name, "=")) == NULL) {
977 debug3("Copy environment: %s=%s", var_name, var_val);
978 child_set_env(env, envsize, var_name, var_val);
985 do_setup_env(Session *s, const char *shell)
989 char **env, *laddr, *path = NULL;
990 #ifdef HAVE_LOGIN_CAP
991 extern char **environ;
994 struct passwd *pw = s->pw;
996 /* Initialize the environment. */
998 env = xmalloc(envsize * sizeof(char *));
1003 * The Windows environment contains some setting which are
1004 * important for a running system. They must not be dropped.
1009 p = fetch_windows_environment();
1010 copy_environment(p, &env, &envsize);
1011 free_windows_environment(p);
1016 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1019 /* Allow any GSSAPI methods that we've used to alter
1020 * the childs environment as they see fit
1022 ssh_gssapi_do_child(&env, &envsize);
1025 if (!options.use_login) {
1026 /* Set basic environment. */
1027 for (i = 0; i < s->num_env; i++)
1028 child_set_env(&env, &envsize, s->env[i].name,
1031 child_set_env(&env, &envsize, "USER", pw->pw_name);
1032 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1034 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1036 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1037 snprintf(buf, sizeof buf, "%.200s/%.50s",
1038 _PATH_MAILDIR, pw->pw_name);
1039 child_set_env(&env, &envsize, "MAIL", buf);
1040 #ifdef HAVE_LOGIN_CAP
1041 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1042 child_set_env(&env, &envsize, "TERM", "su");
1044 environ = xmalloc(sizeof(char *));
1046 (void) setusercontext(lc, pw, pw->pw_uid,
1047 LOGIN_SETENV|LOGIN_SETPATH);
1048 copy_environment(environ, &env, &envsize);
1049 for (var = environ; *var != NULL; ++var)
1053 #else /* HAVE_LOGIN_CAP */
1054 # ifndef HAVE_CYGWIN
1056 * There's no standard path on Windows. The path contains
1057 * important components pointing to the system directories,
1058 * needed for loading shared libraries. So the path better
1059 * remains intact here.
1061 # ifdef HAVE_ETC_DEFAULT_LOGIN
1062 read_etc_default_login(&env, &envsize, pw->pw_uid);
1063 path = child_get_env(env, "PATH");
1064 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1065 if (path == NULL || *path == '\0') {
1066 child_set_env(&env, &envsize, "PATH",
1067 s->pw->pw_uid == 0 ?
1068 SUPERUSER_PATH : _PATH_STDPATH);
1070 # endif /* HAVE_CYGWIN */
1071 #endif /* HAVE_LOGIN_CAP */
1073 /* Normal systems set SHELL by default. */
1074 child_set_env(&env, &envsize, "SHELL", shell);
1077 /* Set custom environment options from RSA authentication. */
1078 if (!options.use_login) {
1079 while (custom_environment) {
1080 struct envstring *ce = custom_environment;
1083 for (i = 0; str[i] != '=' && str[i]; i++)
1085 if (str[i] == '=') {
1087 child_set_env(&env, &envsize, str, str + i + 1);
1089 custom_environment = ce->next;
1095 /* SSH_CLIENT deprecated */
1096 snprintf(buf, sizeof buf, "%.50s %d %d",
1097 get_remote_ipaddr(), get_remote_port(), get_local_port());
1098 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1100 laddr = get_local_ipaddr(packet_get_connection_in());
1101 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1102 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1104 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1107 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1109 child_set_env(&env, &envsize, "TERM", s->term);
1111 child_set_env(&env, &envsize, "DISPLAY", s->display);
1112 if (original_command)
1113 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1117 if (cray_tmpdir[0] != '\0')
1118 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1119 #endif /* _UNICOS */
1122 * Since we clear KRB5CCNAME at startup, if it's set now then it
1123 * must have been set by a native authentication method (eg AIX or
1124 * SIA), so copy it to the child.
1129 if ((cp = getenv("KRB5CCNAME")) != NULL)
1130 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1137 if ((cp = getenv("AUTHSTATE")) != NULL)
1138 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1139 read_environment_file(&env, &envsize, "/etc/environment");
1143 if (s->authctxt->krb5_ccname)
1144 child_set_env(&env, &envsize, "KRB5CCNAME",
1145 s->authctxt->krb5_ccname);
1149 * Pull in any environment variables that may have
1152 if (options.use_pam) {
1155 p = fetch_pam_child_environment();
1156 copy_environment(p, &env, &envsize);
1157 free_pam_environment(p);
1159 p = fetch_pam_environment();
1160 copy_environment(p, &env, &envsize);
1161 free_pam_environment(p);
1163 #endif /* USE_PAM */
1165 if (auth_sock_name != NULL)
1166 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1169 /* read $HOME/.ssh/environment. */
1170 if (options.permit_user_env && !options.use_login) {
1171 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1172 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1173 read_environment_file(&env, &envsize, buf);
1176 /* dump the environment */
1177 fprintf(stderr, "Environment:\n");
1178 for (i = 0; env[i]; i++)
1179 fprintf(stderr, " %.200s\n", env[i]);
1185 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1186 * first in this order).
1189 do_rc_files(Session *s, const char *shell)
1197 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1199 /* ignore _PATH_SSH_USER_RC for subsystems */
1200 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1201 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1202 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1204 fprintf(stderr, "Running %s\n", cmd);
1205 f = popen(cmd, "w");
1208 fprintf(f, "%s %s\n", s->auth_proto,
1212 fprintf(stderr, "Could not run %s\n",
1214 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1216 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1217 _PATH_SSH_SYSTEM_RC);
1218 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1221 fprintf(f, "%s %s\n", s->auth_proto,
1225 fprintf(stderr, "Could not run %s\n",
1226 _PATH_SSH_SYSTEM_RC);
1227 } else if (do_xauth && options.xauth_location != NULL) {
1228 /* Add authority data to .Xauthority if appropriate. */
1231 "Running %.500s remove %.100s\n",
1232 options.xauth_location, s->auth_display);
1234 "%.500s add %.100s %.100s %.100s\n",
1235 options.xauth_location, s->auth_display,
1236 s->auth_proto, s->auth_data);
1238 snprintf(cmd, sizeof cmd, "%s -q -",
1239 options.xauth_location);
1240 f = popen(cmd, "w");
1242 fprintf(f, "remove %s\n",
1244 fprintf(f, "add %s %s %s\n",
1245 s->auth_display, s->auth_proto,
1249 fprintf(stderr, "Could not run %s\n",
1256 do_nologin(struct passwd *pw)
1261 #ifdef HAVE_LOGIN_CAP
1262 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1263 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1264 _PATH_NOLOGIN), "r");
1267 f = fopen(_PATH_NOLOGIN, "r");
1270 /* /etc/nologin exists. Print its contents and exit. */
1271 logit("User %.100s not allowed because %s exists",
1272 pw->pw_name, _PATH_NOLOGIN);
1273 while (fgets(buf, sizeof(buf), f))
1281 /* Set login name, uid, gid, and groups. */
1283 do_setusercontext(struct passwd *pw)
1286 if (getuid() == 0 || geteuid() == 0)
1287 #endif /* HAVE_CYGWIN */
1290 #ifdef HAVE_SETPCRED
1291 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1292 fatal("Failed to set process credentials");
1293 #endif /* HAVE_SETPCRED */
1294 #ifdef HAVE_LOGIN_CAP
1299 if (options.gss_authentication) {
1300 temporarily_use_uid(pw);
1301 ssh_gssapi_storecreds();
1306 if (options.use_pam) {
1310 # endif /* USE_PAM */
1311 if (setusercontext(lc, pw, pw->pw_uid,
1312 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1313 perror("unable to set user context");
1317 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1318 /* Sets login uid for accounting */
1319 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1320 error("setluid: %s", strerror(errno));
1321 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1323 if (setlogin(pw->pw_name) < 0)
1324 error("setlogin failed: %s", strerror(errno));
1325 if (setgid(pw->pw_gid) < 0) {
1329 /* Initialize the group list. */
1330 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1331 perror("initgroups");
1336 if (options.gss_authentication) {
1337 temporarily_use_uid(pw);
1338 ssh_gssapi_storecreds();
1344 * PAM credentials may take the form of supplementary groups.
1345 * These will have been wiped by the above initgroups() call.
1346 * Reestablish them here.
1348 if (options.use_pam) {
1352 # endif /* USE_PAM */
1353 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1354 irix_setusercontext(pw);
1355 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1359 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1360 if (set_id(pw->pw_name) != 0) {
1363 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1364 /* Permanently switch to the desired uid. */
1365 permanently_set_uid(pw);
1372 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1373 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1377 do_pwchange(Session *s)
1380 fprintf(stderr, "WARNING: Your password has expired.\n");
1381 if (s->ttyfd != -1) {
1383 "You must change your password now and login again!\n");
1384 #ifdef PASSWD_NEEDS_USERNAME
1385 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1388 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1393 "Password change required but no TTY available.\n");
1399 launch_login(struct passwd *pw, const char *hostname)
1401 /* Launch login(1). */
1403 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1404 #ifdef xxxLOGIN_NEEDS_TERM
1405 (s->term ? s->term : "unknown"),
1406 #endif /* LOGIN_NEEDS_TERM */
1407 #ifdef LOGIN_NO_ENDOPT
1408 "-p", "-f", pw->pw_name, (char *)NULL);
1410 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1413 /* Login couldn't be executed, die. */
1420 child_close_fds(void)
1424 if (packet_get_connection_in() == packet_get_connection_out())
1425 close(packet_get_connection_in());
1427 close(packet_get_connection_in());
1428 close(packet_get_connection_out());
1431 * Close all descriptors related to channels. They will still remain
1432 * open in the parent.
1434 /* XXX better use close-on-exec? -markus */
1435 channel_close_all();
1438 * Close any extra file descriptors. Note that there may still be
1439 * descriptors left by system functions. They will be closed later.
1444 * Close any extra open file descriptors so that we don't have them
1445 * hanging around in clients. Note that we want to do this after
1446 * initgroups, because at least on Solaris 2.3 it leaves file
1449 for (i = 3; i < 64; i++)
1454 * Performs common processing for the child, such as setting up the
1455 * environment, closing extra file descriptors, setting the user and group
1456 * ids, and executing the command or shell.
1459 do_child(Session *s, const char *command)
1461 extern char **environ;
1464 const char *shell, *shell0, *hostname = NULL;
1465 struct passwd *pw = s->pw;
1466 #ifdef HAVE_LOGIN_CAP
1470 /* remove hostkey from the child's memory */
1471 destroy_sensitive_data();
1473 /* Force a password change */
1474 if (s->authctxt->force_pwchange) {
1475 do_setusercontext(pw);
1481 /* login(1) is only called if we execute the login shell */
1482 if (options.use_login && command != NULL)
1483 options.use_login = 0;
1486 cray_setup(pw->pw_uid, pw->pw_name, command);
1487 #endif /* _UNICOS */
1490 * Login(1) does this as well, and it needs uid 0 for the "-h"
1491 * switch, so we let login(1) to this for us.
1493 if (!options.use_login) {
1495 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1496 if (!check_quietlogin(s, command))
1498 #else /* HAVE_OSF_SIA */
1499 /* When PAM is enabled we rely on it to do the nologin check */
1500 if (!options.use_pam)
1502 do_setusercontext(pw);
1504 * PAM session modules in do_setusercontext may have
1505 * generated messages, so if this in an interactive
1506 * login then display them too.
1508 if (!check_quietlogin(s, command))
1510 #endif /* HAVE_OSF_SIA */
1514 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1515 debug3("PAM session not opened, exiting");
1522 * Get the shell from the password data. An empty shell field is
1523 * legal, and means /bin/sh.
1525 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1528 * Make sure $SHELL points to the shell from the password file,
1529 * even if shell is overridden from login.conf
1531 env = do_setup_env(s, shell);
1533 #ifdef HAVE_LOGIN_CAP
1534 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1537 /* we have to stash the hostname before we close our socket. */
1538 if (options.use_login)
1539 hostname = get_remote_name_or_ip(utmp_len,
1542 * Close the connection descriptors; note that this is the child, and
1543 * the server will still have the socket open, and it is important
1544 * that we do not shutdown it. Note that the descriptors cannot be
1545 * closed before building the environment, as we call
1546 * get_remote_ipaddr there.
1551 * Must take new environment into use so that .ssh/rc,
1552 * /etc/ssh/sshrc and xauth are run in the proper environment.
1556 #ifdef HAVE_LOGIN_CAP
1557 lc_requirehome = login_getcapbool(lc, "requirehome", 0);
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
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 *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 cmd = options.subsystem_command[i];
1873 if (stat(cmd, &st) < 0) {
1874 error("subsystem: cannot stat %s: %s", cmd,
1878 debug("subsystem: exec() %s", cmd);
1879 s->is_subsystem = 1;
1887 logit("subsystem request for %.100s failed, subsystem not found",
1895 session_x11_req(Session *s)
1899 if (s->auth_proto != NULL || s->auth_data != NULL) {
1900 error("session_x11_req: session %d: "
1901 "x11 forwarding already active", s->self);
1904 s->single_connection = packet_get_char();
1905 s->auth_proto = packet_get_string(NULL);
1906 s->auth_data = packet_get_string(NULL);
1907 s->screen = packet_get_int();
1910 success = session_setup_x11fwd(s);
1912 xfree(s->auth_proto);
1913 xfree(s->auth_data);
1914 s->auth_proto = NULL;
1915 s->auth_data = NULL;
1921 session_shell_req(Session *s)
1929 session_exec_req(Session *s)
1932 char *command = packet_get_string(&len);
1934 do_exec(s, command);
1940 session_break_req(Session *s)
1943 packet_get_int(); /* ignored */
1946 if (s->ttyfd == -1 ||
1947 tcsendbreak(s->ttyfd, 0) < 0)
1953 session_env_req(Session *s)
1956 u_int name_len, val_len, i;
1958 name = packet_get_string(&name_len);
1959 val = packet_get_string(&val_len);
1962 /* Don't set too many environment variables */
1963 if (s->num_env > 128) {
1964 debug2("Ignoring env request %s: too many env vars", name);
1968 for (i = 0; i < options.num_accept_env; i++) {
1969 if (match_pattern(name, options.accept_env[i])) {
1970 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1971 s->env = xrealloc(s->env, sizeof(*s->env) *
1973 s->env[s->num_env].name = name;
1974 s->env[s->num_env].val = val;
1979 debug2("Ignoring env request %s: disallowed name", name);
1988 session_auth_agent_req(Session *s)
1990 static int called = 0;
1992 if (no_agent_forwarding_flag) {
1993 debug("session_auth_agent_req: no_agent_forwarding_flag");
2000 return auth_input_request_forwarding(s->pw);
2005 session_input_channel_req(Channel *c, const char *rtype)
2010 if ((s = session_by_channel(c->self)) == NULL) {
2011 logit("session_input_channel_req: no session %d req %.100s",
2015 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2018 * a session is in LARVAL state until a shell, a command
2019 * or a subsystem is executed
2021 if (c->type == SSH_CHANNEL_LARVAL) {
2022 if (strcmp(rtype, "shell") == 0) {
2023 success = session_shell_req(s);
2024 } else if (strcmp(rtype, "exec") == 0) {
2025 success = session_exec_req(s);
2026 } else if (strcmp(rtype, "pty-req") == 0) {
2027 success = session_pty_req(s);
2028 } else if (strcmp(rtype, "x11-req") == 0) {
2029 success = session_x11_req(s);
2030 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2031 success = session_auth_agent_req(s);
2032 } else if (strcmp(rtype, "subsystem") == 0) {
2033 success = session_subsystem_req(s);
2034 } else if (strcmp(rtype, "env") == 0) {
2035 success = session_env_req(s);
2038 if (strcmp(rtype, "window-change") == 0) {
2039 success = session_window_change_req(s);
2040 } else if (strcmp(rtype, "break") == 0) {
2041 success = session_break_req(s);
2048 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2051 fatal("session_set_fds: called for proto != 2.0");
2053 * now that have a child and a pipe to the child,
2054 * we can activate our channel and register the fd's
2056 if (s->chanid == -1)
2057 fatal("no channel for session %d", s->self);
2058 channel_set_fds(s->chanid,
2060 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2062 CHAN_SES_WINDOW_DEFAULT);
2066 * Function to perform pty cleanup. Also called if we get aborted abnormally
2067 * (e.g., due to a dropped connection).
2070 session_pty_cleanup2(Session *s)
2073 error("session_pty_cleanup: no session");
2079 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2081 /* Record that the user has logged out. */
2083 record_logout(s->pid, s->tty, s->pw->pw_name);
2085 /* Release the pseudo-tty. */
2087 pty_release(s->tty);
2090 * Close the server side of the socket pairs. We must do this after
2091 * the pty cleanup, so that another process doesn't get this pty
2092 * while we're still cleaning up.
2094 if (close(s->ptymaster) < 0)
2095 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2097 /* unlink pty from session */
2102 session_pty_cleanup(Session *s)
2104 PRIVSEP(session_pty_cleanup2(s));
2110 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2125 return "SIG@openssh.com";
2129 session_close_x11(int id)
2133 if ((c = channel_by_id(id)) == NULL) {
2134 debug("session_close_x11: x11 channel %d missing", id);
2136 /* Detach X11 listener */
2137 debug("session_close_x11: detach x11 channel %d", id);
2138 channel_cancel_cleanup(id);
2139 if (c->ostate != CHAN_OUTPUT_CLOSED)
2145 session_close_single_x11(int id, void *arg)
2150 debug3("session_close_single_x11: channel %d", id);
2151 channel_cancel_cleanup(id);
2152 if ((s = session_by_x11_channel(id)) == NULL)
2153 fatal("session_close_single_x11: no x11 channel %d", id);
2154 for (i = 0; s->x11_chanids[i] != -1; i++) {
2155 debug("session_close_single_x11: session %d: "
2156 "closing channel %d", s->self, s->x11_chanids[i]);
2158 * The channel "id" is already closing, but make sure we
2159 * close all of its siblings.
2161 if (s->x11_chanids[i] != id)
2162 session_close_x11(s->x11_chanids[i]);
2164 xfree(s->x11_chanids);
2165 s->x11_chanids = NULL;
2170 if (s->auth_proto) {
2171 xfree(s->auth_proto);
2172 s->auth_proto = NULL;
2175 xfree(s->auth_data);
2176 s->auth_data = NULL;
2178 if (s->auth_display) {
2179 xfree(s->auth_display);
2180 s->auth_display = NULL;
2185 session_exit_message(Session *s, int status)
2189 if ((c = channel_lookup(s->chanid)) == NULL)
2190 fatal("session_exit_message: session %d: no channel %d",
2191 s->self, s->chanid);
2192 debug("session_exit_message: session %d channel %d pid %ld",
2193 s->self, s->chanid, (long)s->pid);
2195 if (WIFEXITED(status)) {
2196 channel_request_start(s->chanid, "exit-status", 0);
2197 packet_put_int(WEXITSTATUS(status));
2199 } else if (WIFSIGNALED(status)) {
2200 channel_request_start(s->chanid, "exit-signal", 0);
2201 packet_put_cstring(sig2name(WTERMSIG(status)));
2203 packet_put_char(WCOREDUMP(status));
2204 #else /* WCOREDUMP */
2206 #endif /* WCOREDUMP */
2207 packet_put_cstring("");
2208 packet_put_cstring("");
2211 /* Some weird exit cause. Just exit. */
2212 packet_disconnect("wait returned status %04x.", status);
2215 /* disconnect channel */
2216 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);
2282 * this is called when a channel dies before
2283 * the session 'child' itself dies
2286 session_close_by_channel(int id, void *arg)
2288 Session *s = session_by_channel(id);
2292 debug("session_close_by_channel: no session for id %d", id);
2295 debug("session_close_by_channel: channel %d child %ld",
2298 debug("session_close_by_channel: channel %d: has child", id);
2300 * delay detach of session, but release pty, since
2301 * the fd's to the child are already closed
2304 session_pty_cleanup(s);
2307 /* detach by removing callback */
2308 channel_cancel_cleanup(s->chanid);
2310 /* Close any X11 listeners associated with this session */
2311 if (s->x11_chanids != NULL) {
2312 for (i = 0; s->x11_chanids[i] != -1; i++) {
2313 session_close_x11(s->x11_chanids[i]);
2314 s->x11_chanids[i] = -1;
2323 session_destroy_all(void (*closefunc)(Session *))
2326 for (i = 0; i < MAX_SESSIONS; i++) {
2327 Session *s = &sessions[i];
2329 if (closefunc != NULL)
2338 session_tty_list(void)
2340 static char buf[1024];
2345 for (i = 0; i < MAX_SESSIONS; i++) {
2346 Session *s = &sessions[i];
2347 if (s->used && s->ttyfd != -1) {
2349 if (strncmp(s->tty, "/dev/", 5) != 0) {
2350 cp = strrchr(s->tty, '/');
2351 cp = (cp == NULL) ? s->tty : cp + 1;
2356 strlcat(buf, ",", sizeof buf);
2357 strlcat(buf, cp, sizeof buf);
2361 strlcpy(buf, "notty", sizeof buf);
2366 session_proctitle(Session *s)
2369 error("no user for session %d", s->self);
2371 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2375 session_setup_x11fwd(Session *s)
2378 char display[512], auth_display[512];
2379 char hostname[MAXHOSTNAMELEN];
2382 if (no_x11_forwarding_flag) {
2383 packet_send_debug("X11 forwarding disabled in user configuration file.");
2386 if (!options.x11_forwarding) {
2387 debug("X11 forwarding disabled in server configuration file.");
2390 if (!options.xauth_location ||
2391 (stat(options.xauth_location, &st) == -1)) {
2392 packet_send_debug("No xauth program; cannot forward with spoofing.");
2395 if (options.use_login) {
2396 packet_send_debug("X11 forwarding disabled; "
2397 "not compatible with UseLogin=yes.");
2400 if (s->display != NULL) {
2401 debug("X11 display already set.");
2404 if (x11_create_display_inet(options.x11_display_offset,
2405 options.x11_use_localhost, s->single_connection,
2406 &s->display_number, &s->x11_chanids) == -1) {
2407 debug("x11_create_display_inet failed.");
2410 for (i = 0; s->x11_chanids[i] != -1; i++) {
2411 channel_register_cleanup(s->x11_chanids[i],
2412 session_close_single_x11, 0);
2415 /* Set up a suitable value for the DISPLAY variable. */
2416 if (gethostname(hostname, sizeof(hostname)) < 0)
2417 fatal("gethostname: %.100s", strerror(errno));
2419 * auth_display must be used as the displayname when the
2420 * authorization entry is added with xauth(1). This will be
2421 * different than the DISPLAY string for localhost displays.
2423 if (options.x11_use_localhost) {
2424 snprintf(display, sizeof display, "localhost:%u.%u",
2425 s->display_number, s->screen);
2426 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2427 s->display_number, s->screen);
2428 s->display = xstrdup(display);
2429 s->auth_display = xstrdup(auth_display);
2431 #ifdef IPADDR_IN_DISPLAY
2433 struct in_addr my_addr;
2435 he = gethostbyname(hostname);
2437 error("Can't get IP address for X11 DISPLAY.");
2438 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2441 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2442 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2443 s->display_number, s->screen);
2445 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2446 s->display_number, s->screen);
2448 s->display = xstrdup(display);
2449 s->auth_display = xstrdup(display);
2456 do_authenticated2(Authctxt *authctxt)
2458 server_loop2(authctxt);
2462 do_cleanup(Authctxt *authctxt)
2464 static int called = 0;
2466 debug("do_cleanup");
2468 /* no cleanup if we're in the child for login shell */
2472 /* avoid double cleanup */
2477 if (authctxt == NULL)
2480 if (options.kerberos_ticket_cleanup &&
2482 krb5_cleanup_proc(authctxt);
2486 if (compat20 && options.gss_cleanup_creds)
2487 ssh_gssapi_cleanup_creds();
2491 if (options.use_pam) {
2493 sshpam_thread_cleanup();
2497 /* remove agent socket */
2498 auth_sock_cleanup_proc(authctxt->pw);
2501 * Cleanup ptys/utmp only if privsep is disabled,
2502 * or if running in monitor.
2504 if (!use_privsep || mm_is_monitor())
2505 session_destroy_all(session_pty_cleanup2);