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.172 2004/01/30 09:48:57 markus Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
60 #include "monitor_wrap.h"
62 #if defined(KRB5) && defined(USE_AFS)
72 Session *session_new(void);
73 void session_set_fds(Session *, int, int, int);
74 void session_pty_cleanup(Session *);
75 void session_proctitle(Session *);
76 int session_setup_x11fwd(Session *);
77 void do_exec_pty(Session *, const char *);
78 void do_exec_no_pty(Session *, const char *);
79 void do_exec(Session *, const char *);
80 void do_login(Session *, const char *);
81 #ifdef LOGIN_NEEDS_UTMPX
82 static void do_pre_login(Session *s);
84 void do_child(Session *, const char *);
86 int check_quietlogin(Session *, const char *);
88 static void do_authenticated1(Authctxt *);
89 static void do_authenticated2(Authctxt *);
91 static int session_pty_req(Session *);
94 extern ServerOptions options;
95 extern char *__progname;
96 extern int log_stderr;
97 extern int debug_flag;
98 extern u_int utmp_len;
99 extern int startup_pipe;
100 extern void destroy_sensitive_data(void);
101 extern Buffer loginmsg;
103 /* original command from peer. */
104 const char *original_command = NULL;
107 #define MAX_SESSIONS 10
108 Session sessions[MAX_SESSIONS];
110 #ifdef HAVE_LOGIN_CAP
114 static int is_child = 0;
116 /* Name and directory of socket for authentication agent forwarding. */
117 static char *auth_sock_name = NULL;
118 static char *auth_sock_dir = NULL;
120 /* removes the agent forwarding socket */
123 auth_sock_cleanup_proc(struct passwd *pw)
125 if (auth_sock_name != NULL) {
126 temporarily_use_uid(pw);
127 unlink(auth_sock_name);
128 rmdir(auth_sock_dir);
129 auth_sock_name = NULL;
135 auth_input_request_forwarding(struct passwd * pw)
139 struct sockaddr_un sunaddr;
141 if (auth_sock_name != NULL) {
142 error("authentication forwarding requested twice.");
146 /* Temporarily drop privileged uid for mkdir/bind. */
147 temporarily_use_uid(pw);
149 /* Allocate a buffer for the socket name, and format the name. */
150 auth_sock_name = xmalloc(MAXPATHLEN);
151 auth_sock_dir = xmalloc(MAXPATHLEN);
152 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
154 /* Create private directory for socket */
155 if (mkdtemp(auth_sock_dir) == NULL) {
156 packet_send_debug("Agent forwarding disabled: "
157 "mkdtemp() failed: %.100s", strerror(errno));
159 xfree(auth_sock_name);
160 xfree(auth_sock_dir);
161 auth_sock_name = NULL;
162 auth_sock_dir = NULL;
165 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
166 auth_sock_dir, (long) getpid());
168 /* Create the socket. */
169 sock = socket(AF_UNIX, SOCK_STREAM, 0);
171 packet_disconnect("socket: %.100s", strerror(errno));
173 /* Bind it to the name. */
174 memset(&sunaddr, 0, sizeof(sunaddr));
175 sunaddr.sun_family = AF_UNIX;
176 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
178 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
179 packet_disconnect("bind: %.100s", strerror(errno));
181 /* Restore the privileged uid. */
184 /* Start listening on the socket. */
185 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
186 packet_disconnect("listen: %.100s", strerror(errno));
188 /* Allocate a channel for the authentication agent socket. */
189 nc = channel_new("auth socket",
190 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
191 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
192 0, "auth socket", 1);
193 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
198 display_loginmsg(void)
200 if (buffer_len(&loginmsg) > 0) {
201 buffer_append(&loginmsg, "\0", 1);
202 printf("%s\n", (char *)buffer_ptr(&loginmsg));
203 buffer_clear(&loginmsg);
208 do_authenticated(Authctxt *authctxt)
210 setproctitle("%s", authctxt->pw->pw_name);
213 * Cancel the alarm we set to limit the time taken for
217 if (startup_pipe != -1) {
221 /* setup the channel layer */
222 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
223 channel_permit_all_opens();
226 do_authenticated2(authctxt);
228 do_authenticated1(authctxt);
230 do_cleanup(authctxt);
234 * Prepares for an interactive session. This is called after the user has
235 * been successfully authenticated. During this message exchange, pseudo
236 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
237 * are requested, etc.
240 do_authenticated1(Authctxt *authctxt)
244 int success, type, screen_flag;
245 int enable_compression_after_reply = 0;
246 u_int proto_len, data_len, dlen, compression_level = 0;
249 s->authctxt = authctxt;
250 s->pw = authctxt->pw;
253 * We stay in this loop until the client requests to execute a shell
259 /* Get a packet from the client. */
260 type = packet_read();
262 /* Process the packet. */
264 case SSH_CMSG_REQUEST_COMPRESSION:
265 compression_level = packet_get_int();
267 if (compression_level < 1 || compression_level > 9) {
268 packet_send_debug("Received illegal compression level %d.",
272 if (!options.compression) {
273 debug2("compression disabled");
276 /* Enable compression after we have responded with SUCCESS. */
277 enable_compression_after_reply = 1;
281 case SSH_CMSG_REQUEST_PTY:
282 success = session_pty_req(s);
285 case SSH_CMSG_X11_REQUEST_FORWARDING:
286 s->auth_proto = packet_get_string(&proto_len);
287 s->auth_data = packet_get_string(&data_len);
289 screen_flag = packet_get_protocol_flags() &
290 SSH_PROTOFLAG_SCREEN_NUMBER;
291 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
293 if (packet_remaining() == 4) {
295 debug2("Buggy client: "
296 "X11 screen flag missing");
297 s->screen = packet_get_int();
302 success = session_setup_x11fwd(s);
304 xfree(s->auth_proto);
306 s->auth_proto = NULL;
311 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
312 if (no_agent_forwarding_flag || compat13) {
313 debug("Authentication agent forwarding not permitted for this authentication.");
316 debug("Received authentication agent forwarding request.");
317 success = auth_input_request_forwarding(s->pw);
320 case SSH_CMSG_PORT_FORWARD_REQUEST:
321 if (no_port_forwarding_flag) {
322 debug("Port forwarding not permitted for this authentication.");
325 if (!options.allow_tcp_forwarding) {
326 debug("Port forwarding not permitted.");
329 debug("Received TCP/IP port forwarding request.");
330 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
334 case SSH_CMSG_MAX_PACKET_SIZE:
335 if (packet_set_maxsize(packet_get_int()) > 0)
339 case SSH_CMSG_EXEC_SHELL:
340 case SSH_CMSG_EXEC_CMD:
341 if (type == SSH_CMSG_EXEC_CMD) {
342 command = packet_get_string(&dlen);
343 debug("Exec command '%.500s'", command);
355 * Any unknown messages in this phase are ignored,
356 * and a failure message is returned.
358 logit("Unknown packet type received after authentication: %d", type);
360 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
364 /* Enable compression now that we have replied if appropriate. */
365 if (enable_compression_after_reply) {
366 enable_compression_after_reply = 0;
367 packet_start_compression(compression_level);
373 * This is called to fork and execute a command when we have no tty. This
374 * will call do_child from the child, and server_loop from the parent after
375 * setting up file descriptors and such.
378 do_exec_no_pty(Session *s, const char *command)
383 int pin[2], pout[2], perr[2];
384 /* Allocate pipes for communicating with the program. */
385 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
386 packet_disconnect("Could not create pipes: %.100s",
388 #else /* USE_PIPES */
389 int inout[2], err[2];
390 /* Uses socket pairs to communicate with the program. */
391 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
392 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
393 packet_disconnect("Could not create socket pairs: %.100s",
395 #endif /* USE_PIPES */
397 fatal("do_exec_no_pty: no session");
399 session_proctitle(s);
402 if (options.use_pam && !use_privsep)
406 /* Fork the child. */
407 if ((pid = fork()) == 0) {
410 /* Child. Reinitialize the log since the pid has changed. */
411 log_init(__progname, options.log_level, options.log_facility, log_stderr);
414 * Create a new session and process group since the 4.4BSD
415 * setlogin() affects the entire process group.
418 error("setsid failed: %.100s", strerror(errno));
422 * Redirect stdin. We close the parent side of the socket
423 * pair, and make the child side the standard input.
426 if (dup2(pin[0], 0) < 0)
427 perror("dup2 stdin");
430 /* Redirect stdout. */
432 if (dup2(pout[1], 1) < 0)
433 perror("dup2 stdout");
436 /* Redirect stderr. */
438 if (dup2(perr[1], 2) < 0)
439 perror("dup2 stderr");
441 #else /* USE_PIPES */
443 * Redirect stdin, stdout, and stderr. Stdin and stdout will
444 * use the same socket, as some programs (particularly rdist)
445 * seem to depend on it.
449 if (dup2(inout[0], 0) < 0) /* stdin */
450 perror("dup2 stdin");
451 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
452 perror("dup2 stdout");
453 if (dup2(err[0], 2) < 0) /* stderr */
454 perror("dup2 stderr");
455 #endif /* USE_PIPES */
458 cray_init_job(s->pw); /* set up cray jid and tmpdir */
461 /* Do processing for the child (exec command etc). */
462 do_child(s, command);
466 signal(WJSIGNAL, cray_job_termination_handler);
470 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
473 packet_disconnect("fork failed: %.100s", strerror(errno));
475 /* Set interactive/non-interactive mode. */
476 packet_set_interactive(s->display != NULL);
478 /* We are the parent. Close the child sides of the pipes. */
484 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : 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 * Enter the interactive session. Note: server_loop must be able to
497 * handle the case that fdin and fdout are the same.
500 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
502 server_loop(pid, inout[1], inout[1], err[1]);
503 /* server_loop has closed inout[1] and err[1]. */
505 #endif /* USE_PIPES */
509 * This is called to fork and execute a command when we have a tty. This
510 * will call do_child from the child, and server_loop from the parent after
511 * setting up file descriptors, controlling tty, updating wtmp, utmp,
512 * lastlog, and other such operations.
515 do_exec_pty(Session *s, const char *command)
517 int fdout, ptyfd, ttyfd, ptymaster;
521 fatal("do_exec_pty: no session");
526 if (options.use_pam) {
527 do_pam_set_tty(s->tty);
533 /* Fork the child. */
534 if ((pid = fork()) == 0) {
537 /* Child. Reinitialize the log because the pid has changed. */
538 log_init(__progname, options.log_level, options.log_facility, log_stderr);
539 /* Close the master side of the pseudo tty. */
542 /* Make the pseudo tty our controlling tty. */
543 pty_make_controlling_tty(&ttyfd, s->tty);
545 /* Redirect stdin/stdout/stderr from the pseudo tty. */
546 if (dup2(ttyfd, 0) < 0)
547 error("dup2 stdin: %s", strerror(errno));
548 if (dup2(ttyfd, 1) < 0)
549 error("dup2 stdout: %s", strerror(errno));
550 if (dup2(ttyfd, 2) < 0)
551 error("dup2 stderr: %s", strerror(errno));
553 /* Close the extra descriptor for the pseudo tty. */
556 /* record login, etc. similar to login(1) */
558 if (!(options.use_login && command == NULL)) {
560 cray_init_job(s->pw); /* set up cray jid and tmpdir */
562 do_login(s, command);
564 # ifdef LOGIN_NEEDS_UTMPX
570 /* Do common processing for the child, such as execing the command. */
571 do_child(s, command);
575 signal(WJSIGNAL, cray_job_termination_handler);
579 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
582 packet_disconnect("fork failed: %.100s", strerror(errno));
585 /* Parent. Close the slave side of the pseudo tty. */
589 * Create another descriptor of the pty master side for use as the
590 * standard input. We could use the original descriptor, but this
591 * simplifies code in server_loop. The descriptor is bidirectional.
595 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
597 /* we keep a reference to the pty master */
598 ptymaster = dup(ptyfd);
600 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
601 s->ptymaster = ptymaster;
603 /* Enter interactive session. */
604 packet_set_interactive(1);
606 session_set_fds(s, ptyfd, fdout, -1);
608 server_loop(pid, ptyfd, fdout, -1);
609 /* server_loop _has_ closed ptyfd and fdout. */
613 #ifdef LOGIN_NEEDS_UTMPX
615 do_pre_login(Session *s)
618 struct sockaddr_storage from;
619 pid_t pid = getpid();
622 * Get IP address of client. If the connection is not a socket, let
623 * the address be 0.0.0.0.
625 memset(&from, 0, sizeof(from));
626 fromlen = sizeof(from);
627 if (packet_connection_is_on_socket()) {
628 if (getpeername(packet_get_connection_in(),
629 (struct sockaddr *) & from, &fromlen) < 0) {
630 debug("getpeername: %.100s", strerror(errno));
635 record_utmp_only(pid, s->tty, s->pw->pw_name,
636 get_remote_name_or_ip(utmp_len, options.use_dns),
637 (struct sockaddr *)&from, fromlen);
642 * This is called to fork and execute a command. If another command is
643 * to be forced, execute that instead.
646 do_exec(Session *s, const char *command)
648 if (forced_command) {
649 original_command = command;
650 command = forced_command;
651 debug("Forced command '%.900s'", command);
655 if (options.gss_authentication) {
656 temporarily_use_uid(s->pw);
657 ssh_gssapi_storecreds();
663 do_exec_pty(s, command);
665 do_exec_no_pty(s, command);
667 original_command = NULL;
671 /* administrative, login(1)-like work */
673 do_login(Session *s, const char *command)
677 struct sockaddr_storage from;
678 struct passwd * pw = s->pw;
679 pid_t pid = getpid();
682 * Get IP address of client. If the connection is not a socket, let
683 * the address be 0.0.0.0.
685 memset(&from, 0, sizeof(from));
686 fromlen = sizeof(from);
687 if (packet_connection_is_on_socket()) {
688 if (getpeername(packet_get_connection_in(),
689 (struct sockaddr *) & from, &fromlen) < 0) {
690 debug("getpeername: %.100s", strerror(errno));
695 /* Record that there was a login on that tty from the remote host. */
697 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
698 get_remote_name_or_ip(utmp_len,
700 (struct sockaddr *)&from, fromlen);
704 * If password change is needed, do it now.
705 * This needs to occur before the ~/.hushlogin check.
707 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
710 s->authctxt->force_pwchange = 0;
711 /* XXX - signal [net] parent to enable forwardings */
715 if (check_quietlogin(s, command))
720 #ifndef NO_SSH_LASTLOG
721 if (options.print_lastlog && s->last_login_time != 0) {
722 time_string = ctime(&s->last_login_time);
723 if (strchr(time_string, '\n'))
724 *strchr(time_string, '\n') = 0;
725 if (strcmp(s->hostname, "") == 0)
726 printf("Last login: %s\r\n", time_string);
728 printf("Last login: %s from %s\r\n", time_string,
731 #endif /* NO_SSH_LASTLOG */
737 * Display the message of the day.
744 #ifdef HAVE_LOGIN_CAP
748 #ifdef HAVE_LOGIN_CAP
749 fname = login_getcapstr(lc, "copyright", NULL, NULL);
750 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
751 while (fgets(buf, sizeof(buf), f) != NULL)
755 #endif /* HAVE_LOGIN_CAP */
756 (void)printf("%s\n\t%s %s\n",
757 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
758 "The Regents of the University of California. ",
759 "All rights reserved.");
763 if (options.print_motd) {
764 #ifdef HAVE_LOGIN_CAP
765 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
768 f = fopen("/etc/motd", "r");
771 while (fgets(buf, sizeof(buf), f))
780 * Check for quiet login, either .hushlogin or command given.
783 check_quietlogin(Session *s, const char *command)
786 struct passwd *pw = s->pw;
789 /* Return 1 if .hushlogin exists or a command given. */
792 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
793 #ifdef HAVE_LOGIN_CAP
794 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
797 if (stat(buf, &st) >= 0)
804 * Sets the value of the given variable in the environment. If the variable
805 * already exists, its value is overriden.
808 child_set_env(char ***envp, u_int *envsizep, const char *name,
816 * If we're passed an uninitialized list, allocate a single null
817 * entry before continuing.
819 if (*envp == NULL && *envsizep == 0) {
820 *envp = xmalloc(sizeof(char *));
826 * Find the slot where the value should be stored. If the variable
827 * already exists, we reuse the slot; otherwise we append a new slot
828 * at the end of the array, expanding if necessary.
831 namelen = strlen(name);
832 for (i = 0; env[i]; i++)
833 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
836 /* Reuse the slot. */
839 /* New variable. Expand if necessary. */
841 if (i >= envsize - 1) {
843 fatal("child_set_env: too many env vars");
845 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
848 /* Need to set the NULL pointer at end of array beyond the new slot. */
852 /* Allocate space and format the variable in the appropriate slot. */
853 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
854 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
858 * Reads environment variables from the given file and adds/overrides them
859 * into the environment. If the file does not exist, this does nothing.
860 * Otherwise, it must consist of empty lines, comments (line starts with '#')
861 * and assignments of the form name=value. No other forms are allowed.
864 read_environment_file(char ***env, u_int *envsize,
865 const char *filename)
872 f = fopen(filename, "r");
876 while (fgets(buf, sizeof(buf), f)) {
878 fatal("Too many lines in environment file %s", filename);
879 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
881 if (!*cp || *cp == '#' || *cp == '\n')
883 if (strchr(cp, '\n'))
884 *strchr(cp, '\n') = '\0';
885 value = strchr(cp, '=');
887 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
892 * Replace the equals sign by nul, and advance value to
897 child_set_env(env, envsize, cp, value);
902 #ifdef HAVE_ETC_DEFAULT_LOGIN
904 * Return named variable from specified environment, or NULL if not present.
907 child_get_env(char **env, const char *name)
913 for (i=0; env[i] != NULL; i++)
914 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
915 return(env[i] + len + 1);
920 * Read /etc/default/login.
921 * We pick up the PATH (or SUPATH for root) and UMASK.
924 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
926 char **tmpenv = NULL, *var;
927 u_int i, tmpenvsize = 0;
931 * We don't want to copy the whole file to the child's environment,
932 * so we use a temporary environment and copy the variables we're
935 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
941 var = child_get_env(tmpenv, "SUPATH");
943 var = child_get_env(tmpenv, "PATH");
945 child_set_env(env, envsize, "PATH", var);
947 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
948 if (sscanf(var, "%5lo", &mask) == 1)
951 for (i = 0; tmpenv[i] != NULL; i++)
955 #endif /* HAVE_ETC_DEFAULT_LOGIN */
957 void copy_environment(char **source, char ***env, u_int *envsize)
959 char *var_name, *var_val;
965 for(i = 0; source[i] != NULL; i++) {
966 var_name = xstrdup(source[i]);
967 if ((var_val = strstr(var_name, "=")) == NULL) {
973 debug3("Copy environment: %s=%s", var_name, var_val);
974 child_set_env(env, envsize, var_name, var_val);
981 do_setup_env(Session *s, const char *shell)
985 char **env, *laddr, *path = NULL;
986 #ifdef HAVE_LOGIN_CAP
987 extern char **environ;
990 struct passwd *pw = s->pw;
992 /* Initialize the environment. */
994 env = xmalloc(envsize * sizeof(char *));
999 * The Windows environment contains some setting which are
1000 * important for a running system. They must not be dropped.
1002 copy_environment(environ, &env, &envsize);
1006 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1009 /* Allow any GSSAPI methods that we've used to alter
1010 * the childs environment as they see fit
1012 ssh_gssapi_do_child(&env, &envsize);
1015 if (!options.use_login) {
1016 /* Set basic environment. */
1017 child_set_env(&env, &envsize, "USER", pw->pw_name);
1018 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1020 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1022 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1023 snprintf(buf, sizeof buf, "%.200s/%.50s",
1024 _PATH_MAILDIR, pw->pw_name);
1025 child_set_env(&env, &envsize, "MAIL", buf);
1026 #ifdef HAVE_LOGIN_CAP
1027 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1028 child_set_env(&env, &envsize, "TERM", "su");
1030 environ = xmalloc(sizeof(char *));
1032 (void) setusercontext(lc, pw, pw->pw_uid,
1033 LOGIN_SETENV|LOGIN_SETPATH);
1034 copy_environment(environ, &env, &envsize);
1035 for (var = environ; *var != NULL; ++var)
1039 #else /* HAVE_LOGIN_CAP */
1040 # ifndef HAVE_CYGWIN
1042 * There's no standard path on Windows. The path contains
1043 * important components pointing to the system directories,
1044 * needed for loading shared libraries. So the path better
1045 * remains intact here.
1047 # ifdef HAVE_ETC_DEFAULT_LOGIN
1048 read_etc_default_login(&env, &envsize, pw->pw_uid);
1049 path = child_get_env(env, "PATH");
1050 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1051 if (path == NULL || *path == '\0') {
1052 child_set_env(&env, &envsize, "PATH",
1053 s->pw->pw_uid == 0 ?
1054 SUPERUSER_PATH : _PATH_STDPATH);
1056 # endif /* HAVE_CYGWIN */
1057 #endif /* HAVE_LOGIN_CAP */
1059 /* Normal systems set SHELL by default. */
1060 child_set_env(&env, &envsize, "SHELL", shell);
1063 /* Set custom environment options from RSA authentication. */
1064 if (!options.use_login) {
1065 while (custom_environment) {
1066 struct envstring *ce = custom_environment;
1069 for (i = 0; str[i] != '=' && str[i]; i++)
1071 if (str[i] == '=') {
1073 child_set_env(&env, &envsize, str, str + i + 1);
1075 custom_environment = ce->next;
1081 /* SSH_CLIENT deprecated */
1082 snprintf(buf, sizeof buf, "%.50s %d %d",
1083 get_remote_ipaddr(), get_remote_port(), get_local_port());
1084 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1086 laddr = get_local_ipaddr(packet_get_connection_in());
1087 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1088 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1090 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1093 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1095 child_set_env(&env, &envsize, "TERM", s->term);
1097 child_set_env(&env, &envsize, "DISPLAY", s->display);
1098 if (original_command)
1099 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1103 if (cray_tmpdir[0] != '\0')
1104 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1105 #endif /* _UNICOS */
1111 if ((cp = getenv("AUTHSTATE")) != NULL)
1112 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1113 if ((cp = getenv("KRB5CCNAME")) != NULL)
1114 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1115 read_environment_file(&env, &envsize, "/etc/environment");
1119 if (s->authctxt->krb5_ticket_file)
1120 child_set_env(&env, &envsize, "KRB5CCNAME",
1121 s->authctxt->krb5_ticket_file);
1125 * Pull in any environment variables that may have
1128 if (options.use_pam) {
1131 p = fetch_pam_child_environment();
1132 copy_environment(p, &env, &envsize);
1133 free_pam_environment(p);
1135 p = fetch_pam_environment();
1136 copy_environment(p, &env, &envsize);
1137 free_pam_environment(p);
1139 #endif /* USE_PAM */
1141 if (auth_sock_name != NULL)
1142 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1145 /* read $HOME/.ssh/environment. */
1146 if (options.permit_user_env && !options.use_login) {
1147 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1148 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1149 read_environment_file(&env, &envsize, buf);
1152 /* dump the environment */
1153 fprintf(stderr, "Environment:\n");
1154 for (i = 0; env[i]; i++)
1155 fprintf(stderr, " %.200s\n", env[i]);
1161 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1162 * first in this order).
1165 do_rc_files(Session *s, const char *shell)
1173 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1175 /* ignore _PATH_SSH_USER_RC for subsystems */
1176 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1177 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1178 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1180 fprintf(stderr, "Running %s\n", cmd);
1181 f = popen(cmd, "w");
1184 fprintf(f, "%s %s\n", s->auth_proto,
1188 fprintf(stderr, "Could not run %s\n",
1190 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1192 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1193 _PATH_SSH_SYSTEM_RC);
1194 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1197 fprintf(f, "%s %s\n", s->auth_proto,
1201 fprintf(stderr, "Could not run %s\n",
1202 _PATH_SSH_SYSTEM_RC);
1203 } else if (do_xauth && options.xauth_location != NULL) {
1204 /* Add authority data to .Xauthority if appropriate. */
1207 "Running %.500s remove %.100s\n",
1208 options.xauth_location, s->auth_display);
1210 "%.500s add %.100s %.100s %.100s\n",
1211 options.xauth_location, s->auth_display,
1212 s->auth_proto, s->auth_data);
1214 snprintf(cmd, sizeof cmd, "%s -q -",
1215 options.xauth_location);
1216 f = popen(cmd, "w");
1218 fprintf(f, "remove %s\n",
1220 fprintf(f, "add %s %s %s\n",
1221 s->auth_display, s->auth_proto,
1225 fprintf(stderr, "Could not run %s\n",
1232 do_nologin(struct passwd *pw)
1237 #ifdef HAVE_LOGIN_CAP
1238 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1239 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1240 _PATH_NOLOGIN), "r");
1243 f = fopen(_PATH_NOLOGIN, "r");
1246 /* /etc/nologin exists. Print its contents and exit. */
1247 logit("User %.100s not allowed because %s exists",
1248 pw->pw_name, _PATH_NOLOGIN);
1249 while (fgets(buf, sizeof(buf), f))
1257 /* Set login name, uid, gid, and groups. */
1259 do_setusercontext(struct passwd *pw)
1262 if (getuid() == 0 || geteuid() == 0)
1263 #endif /* HAVE_CYGWIN */
1266 #ifdef HAVE_SETPCRED
1267 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1268 fatal("Failed to set process credentials");
1269 #endif /* HAVE_SETPCRED */
1270 #ifdef HAVE_LOGIN_CAP
1275 if (options.use_pam) {
1279 # endif /* USE_PAM */
1280 if (setusercontext(lc, pw, pw->pw_uid,
1281 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1282 perror("unable to set user context");
1286 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1287 /* Sets login uid for accounting */
1288 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1289 error("setluid: %s", strerror(errno));
1290 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1292 if (setlogin(pw->pw_name) < 0)
1293 error("setlogin failed: %s", strerror(errno));
1294 if (setgid(pw->pw_gid) < 0) {
1298 /* Initialize the group list. */
1299 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1300 perror("initgroups");
1306 * PAM credentials may take the form of supplementary groups.
1307 * These will have been wiped by the above initgroups() call.
1308 * Reestablish them here.
1310 if (options.use_pam) {
1314 # endif /* USE_PAM */
1315 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1316 irix_setusercontext(pw);
1317 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1321 /* Permanently switch to the desired uid. */
1322 permanently_set_uid(pw);
1329 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1330 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1334 do_pwchange(Session *s)
1336 fprintf(stderr, "WARNING: Your password has expired.\n");
1337 if (s->ttyfd != -1) {
1339 "You must change your password now and login again!\n");
1340 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1344 "Password change required but no TTY available.\n");
1350 launch_login(struct passwd *pw, const char *hostname)
1352 /* Launch login(1). */
1354 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1355 #ifdef xxxLOGIN_NEEDS_TERM
1356 (s->term ? s->term : "unknown"),
1357 #endif /* LOGIN_NEEDS_TERM */
1358 #ifdef LOGIN_NO_ENDOPT
1359 "-p", "-f", pw->pw_name, (char *)NULL);
1361 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1364 /* Login couldn't be executed, die. */
1371 child_close_fds(void)
1375 if (packet_get_connection_in() == packet_get_connection_out())
1376 close(packet_get_connection_in());
1378 close(packet_get_connection_in());
1379 close(packet_get_connection_out());
1382 * Close all descriptors related to channels. They will still remain
1383 * open in the parent.
1385 /* XXX better use close-on-exec? -markus */
1386 channel_close_all();
1389 * Close any extra file descriptors. Note that there may still be
1390 * descriptors left by system functions. They will be closed later.
1395 * Close any extra open file descriptors so that we don\'t have them
1396 * hanging around in clients. Note that we want to do this after
1397 * initgroups, because at least on Solaris 2.3 it leaves file
1400 for (i = 3; i < 64; i++)
1405 * Performs common processing for the child, such as setting up the
1406 * environment, closing extra file descriptors, setting the user and group
1407 * ids, and executing the command or shell.
1410 do_child(Session *s, const char *command)
1412 extern char **environ;
1415 const char *shell, *shell0, *hostname = NULL;
1416 struct passwd *pw = s->pw;
1417 #ifdef HAVE_LOGIN_CAP
1421 /* remove hostkey from the child's memory */
1422 destroy_sensitive_data();
1424 /* Force a password change */
1425 if (s->authctxt->force_pwchange) {
1426 do_setusercontext(pw);
1432 /* login(1) is only called if we execute the login shell */
1433 if (options.use_login && command != NULL)
1434 options.use_login = 0;
1437 cray_setup(pw->pw_uid, pw->pw_name, command);
1438 #endif /* _UNICOS */
1441 * Login(1) does this as well, and it needs uid 0 for the "-h"
1442 * switch, so we let login(1) to this for us.
1444 if (!options.use_login) {
1446 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1447 if (!check_quietlogin(s, command))
1449 #else /* HAVE_OSF_SIA */
1451 do_setusercontext(pw);
1452 #endif /* HAVE_OSF_SIA */
1456 * Get the shell from the password data. An empty shell field is
1457 * legal, and means /bin/sh.
1459 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1462 * Make sure $SHELL points to the shell from the password file,
1463 * even if shell is overridden from login.conf
1465 env = do_setup_env(s, shell);
1467 #ifdef HAVE_LOGIN_CAP
1468 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1471 /* we have to stash the hostname before we close our socket. */
1472 if (options.use_login)
1473 hostname = get_remote_name_or_ip(utmp_len,
1476 * Close the connection descriptors; note that this is the child, and
1477 * the server will still have the socket open, and it is important
1478 * that we do not shutdown it. Note that the descriptors cannot be
1479 * closed before building the environment, as we call
1480 * get_remote_ipaddr there.
1485 * Must take new environment into use so that .ssh/rc,
1486 * /etc/ssh/sshrc and xauth are run in the proper environment.
1490 #ifdef HAVE_LOGIN_CAP
1491 lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1494 #if defined(KRB5) && defined(USE_AFS)
1496 * At this point, we check to see if AFS is active and if we have
1497 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1498 * if we can (and need to) extend the ticket into an AFS token. If
1499 * we don't do this, we run into potential problems if the user's
1500 * home directory is in AFS and it's not world-readable.
1503 if (options.kerberos_get_afs_token && k_hasafs() &&
1504 (s->authctxt->krb5_ctx != NULL)) {
1507 debug("Getting AFS token");
1511 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1512 krb5_afslog(s->authctxt->krb5_ctx,
1513 s->authctxt->krb5_fwd_ccache, cell, NULL);
1515 krb5_afslog_home(s->authctxt->krb5_ctx,
1516 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1520 /* Change current directory to the user\'s home directory. */
1521 if (chdir(pw->pw_dir) < 0) {
1522 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1523 pw->pw_dir, strerror(errno));
1524 #ifdef HAVE_LOGIN_CAP
1530 if (!options.use_login)
1531 do_rc_files(s, shell);
1533 /* restore SIGPIPE for child */
1534 signal(SIGPIPE, SIG_DFL);
1536 if (options.use_login) {
1537 launch_login(pw, hostname);
1541 /* Get the last component of the shell name. */
1542 if ((shell0 = strrchr(shell, '/')) != NULL)
1548 * If we have no command, execute the shell. In this case, the shell
1549 * name to be passed in argv[0] is preceded by '-' to indicate that
1550 * this is a login shell.
1555 /* Start the shell. Set initial character to '-'. */
1558 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1559 >= sizeof(argv0) - 1) {
1565 /* Execute the shell. */
1568 execve(shell, argv, env);
1570 /* Executing the shell failed. */
1575 * Execute the command using the user's shell. This uses the -c
1576 * option to execute the command.
1578 argv[0] = (char *) shell0;
1580 argv[2] = (char *) command;
1582 execve(shell, argv, env);
1591 static int did_init = 0;
1593 debug("session_new: init");
1594 for (i = 0; i < MAX_SESSIONS; i++) {
1595 sessions[i].used = 0;
1599 for (i = 0; i < MAX_SESSIONS; i++) {
1600 Session *s = &sessions[i];
1602 memset(s, 0, sizeof(*s));
1608 debug("session_new: session %d", i);
1619 for (i = 0; i < MAX_SESSIONS; i++) {
1620 Session *s = &sessions[i];
1621 debug("dump: used %d session %d %p channel %d pid %ld",
1631 session_open(Authctxt *authctxt, int chanid)
1633 Session *s = session_new();
1634 debug("session_open: channel %d", chanid);
1636 error("no more sessions");
1639 s->authctxt = authctxt;
1640 s->pw = authctxt->pw;
1641 if (s->pw == NULL || !authctxt->valid)
1642 fatal("no user for session %d", s->self);
1643 debug("session_open: session %d: link with channel %d", s->self, chanid);
1649 session_by_tty(char *tty)
1652 for (i = 0; i < MAX_SESSIONS; i++) {
1653 Session *s = &sessions[i];
1654 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1655 debug("session_by_tty: session %d tty %s", i, tty);
1659 debug("session_by_tty: unknown tty %.100s", tty);
1665 session_by_channel(int id)
1668 for (i = 0; i < MAX_SESSIONS; i++) {
1669 Session *s = &sessions[i];
1670 if (s->used && s->chanid == id) {
1671 debug("session_by_channel: session %d channel %d", i, id);
1675 debug("session_by_channel: unknown channel %d", id);
1681 session_by_pid(pid_t pid)
1684 debug("session_by_pid: pid %ld", (long)pid);
1685 for (i = 0; i < MAX_SESSIONS; i++) {
1686 Session *s = &sessions[i];
1687 if (s->used && s->pid == pid)
1690 error("session_by_pid: unknown pid %ld", (long)pid);
1696 session_window_change_req(Session *s)
1698 s->col = packet_get_int();
1699 s->row = packet_get_int();
1700 s->xpixel = packet_get_int();
1701 s->ypixel = packet_get_int();
1703 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1708 session_pty_req(Session *s)
1714 debug("Allocating a pty not permitted for this authentication.");
1717 if (s->ttyfd != -1) {
1718 packet_disconnect("Protocol error: you already have a pty.");
1721 /* Get the time and hostname when the user last logged in. */
1722 if (options.print_lastlog) {
1723 s->hostname[0] = '\0';
1724 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1725 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1728 s->term = packet_get_string(&len);
1731 s->col = packet_get_int();
1732 s->row = packet_get_int();
1734 s->row = packet_get_int();
1735 s->col = packet_get_int();
1737 s->xpixel = packet_get_int();
1738 s->ypixel = packet_get_int();
1740 if (strcmp(s->term, "") == 0) {
1745 /* Allocate a pty and open it. */
1746 debug("Allocating pty.");
1747 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1753 error("session_pty_req: session %d alloc failed", s->self);
1756 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1758 /* for SSH1 the tty modes length is not given */
1760 n_bytes = packet_remaining();
1761 tty_parse_modes(s->ttyfd, &n_bytes);
1764 pty_setowner(s->pw, s->tty);
1766 /* Set window size from the packet. */
1767 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1770 session_proctitle(s);
1775 session_subsystem_req(Session *s)
1780 char *cmd, *subsys = packet_get_string(&len);
1784 logit("subsystem request for %.100s", subsys);
1786 for (i = 0; i < options.num_subsystems; i++) {
1787 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1788 cmd = options.subsystem_command[i];
1789 if (stat(cmd, &st) < 0) {
1790 error("subsystem: cannot stat %s: %s", cmd,
1794 debug("subsystem: exec() %s", cmd);
1795 s->is_subsystem = 1;
1803 logit("subsystem request for %.100s failed, subsystem not found",
1811 session_x11_req(Session *s)
1815 s->single_connection = packet_get_char();
1816 s->auth_proto = packet_get_string(NULL);
1817 s->auth_data = packet_get_string(NULL);
1818 s->screen = packet_get_int();
1821 success = session_setup_x11fwd(s);
1823 xfree(s->auth_proto);
1824 xfree(s->auth_data);
1825 s->auth_proto = NULL;
1826 s->auth_data = NULL;
1832 session_shell_req(Session *s)
1840 session_exec_req(Session *s)
1843 char *command = packet_get_string(&len);
1845 do_exec(s, command);
1851 session_break_req(Session *s)
1855 break_length = packet_get_int(); /* ignored */
1858 if (s->ttyfd == -1 ||
1859 tcsendbreak(s->ttyfd, 0) < 0)
1865 session_auth_agent_req(Session *s)
1867 static int called = 0;
1869 if (no_agent_forwarding_flag) {
1870 debug("session_auth_agent_req: no_agent_forwarding_flag");
1877 return auth_input_request_forwarding(s->pw);
1882 session_input_channel_req(Channel *c, const char *rtype)
1887 if ((s = session_by_channel(c->self)) == NULL) {
1888 logit("session_input_channel_req: no session %d req %.100s",
1892 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1895 * a session is in LARVAL state until a shell, a command
1896 * or a subsystem is executed
1898 if (c->type == SSH_CHANNEL_LARVAL) {
1899 if (strcmp(rtype, "shell") == 0) {
1900 success = session_shell_req(s);
1901 } else if (strcmp(rtype, "exec") == 0) {
1902 success = session_exec_req(s);
1903 } else if (strcmp(rtype, "pty-req") == 0) {
1904 success = session_pty_req(s);
1905 } else if (strcmp(rtype, "x11-req") == 0) {
1906 success = session_x11_req(s);
1907 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1908 success = session_auth_agent_req(s);
1909 } else if (strcmp(rtype, "subsystem") == 0) {
1910 success = session_subsystem_req(s);
1911 } else if (strcmp(rtype, "break") == 0) {
1912 success = session_break_req(s);
1915 if (strcmp(rtype, "window-change") == 0) {
1916 success = session_window_change_req(s);
1922 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1925 fatal("session_set_fds: called for proto != 2.0");
1927 * now that have a child and a pipe to the child,
1928 * we can activate our channel and register the fd's
1930 if (s->chanid == -1)
1931 fatal("no channel for session %d", s->self);
1932 channel_set_fds(s->chanid,
1934 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1936 CHAN_SES_WINDOW_DEFAULT);
1940 * Function to perform pty cleanup. Also called if we get aborted abnormally
1941 * (e.g., due to a dropped connection).
1944 session_pty_cleanup2(Session *s)
1947 error("session_pty_cleanup: no session");
1953 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1955 /* Record that the user has logged out. */
1957 record_logout(s->pid, s->tty, s->pw->pw_name);
1959 /* Release the pseudo-tty. */
1961 pty_release(s->tty);
1964 * Close the server side of the socket pairs. We must do this after
1965 * the pty cleanup, so that another process doesn't get this pty
1966 * while we're still cleaning up.
1968 if (close(s->ptymaster) < 0)
1969 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1971 /* unlink pty from session */
1976 session_pty_cleanup(Session *s)
1978 PRIVSEP(session_pty_cleanup2(s));
1984 #define SSH_SIG(x) if (sig == SIG ## x) return #x
1999 return "SIG@openssh.com";
2003 session_exit_message(Session *s, int status)
2007 if ((c = channel_lookup(s->chanid)) == NULL)
2008 fatal("session_exit_message: session %d: no channel %d",
2009 s->self, s->chanid);
2010 debug("session_exit_message: session %d channel %d pid %ld",
2011 s->self, s->chanid, (long)s->pid);
2013 if (WIFEXITED(status)) {
2014 channel_request_start(s->chanid, "exit-status", 0);
2015 packet_put_int(WEXITSTATUS(status));
2017 } else if (WIFSIGNALED(status)) {
2018 channel_request_start(s->chanid, "exit-signal", 0);
2019 packet_put_cstring(sig2name(WTERMSIG(status)));
2021 packet_put_char(WCOREDUMP(status));
2022 #else /* WCOREDUMP */
2024 #endif /* WCOREDUMP */
2025 packet_put_cstring("");
2026 packet_put_cstring("");
2029 /* Some weird exit cause. Just exit. */
2030 packet_disconnect("wait returned status %04x.", status);
2033 /* disconnect channel */
2034 debug("session_exit_message: release channel %d", s->chanid);
2035 channel_cancel_cleanup(s->chanid);
2037 * emulate a write failure with 'chan_write_failed', nobody will be
2038 * interested in data we write.
2039 * Note that we must not call 'chan_read_failed', since there could
2040 * be some more data waiting in the pipe.
2042 if (c->ostate != CHAN_OUTPUT_CLOSED)
2043 chan_write_failed(c);
2048 session_close(Session *s)
2050 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2052 session_pty_cleanup(s);
2057 if (s->auth_display)
2058 xfree(s->auth_display);
2060 xfree(s->auth_data);
2062 xfree(s->auth_proto);
2064 session_proctitle(s);
2068 session_close_by_pid(pid_t pid, int status)
2070 Session *s = session_by_pid(pid);
2072 debug("session_close_by_pid: no session for pid %ld",
2076 if (s->chanid != -1)
2077 session_exit_message(s, status);
2082 * this is called when a channel dies before
2083 * the session 'child' itself dies
2086 session_close_by_channel(int id, void *arg)
2088 Session *s = session_by_channel(id);
2090 debug("session_close_by_channel: no session for id %d", id);
2093 debug("session_close_by_channel: channel %d child %ld",
2096 debug("session_close_by_channel: channel %d: has child", id);
2098 * delay detach of session, but release pty, since
2099 * the fd's to the child are already closed
2102 session_pty_cleanup(s);
2105 /* detach by removing callback */
2106 channel_cancel_cleanup(s->chanid);
2112 session_destroy_all(void (*closefunc)(Session *))
2115 for (i = 0; i < MAX_SESSIONS; i++) {
2116 Session *s = &sessions[i];
2118 if (closefunc != NULL)
2127 session_tty_list(void)
2129 static char buf[1024];
2134 for (i = 0; i < MAX_SESSIONS; i++) {
2135 Session *s = &sessions[i];
2136 if (s->used && s->ttyfd != -1) {
2138 if (strncmp(s->tty, "/dev/", 5) != 0) {
2139 cp = strrchr(s->tty, '/');
2140 cp = (cp == NULL) ? s->tty : cp + 1;
2145 strlcat(buf, ",", sizeof buf);
2146 strlcat(buf, cp, sizeof buf);
2150 strlcpy(buf, "notty", sizeof buf);
2155 session_proctitle(Session *s)
2158 error("no user for session %d", s->self);
2160 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2164 session_setup_x11fwd(Session *s)
2167 char display[512], auth_display[512];
2168 char hostname[MAXHOSTNAMELEN];
2170 if (no_x11_forwarding_flag) {
2171 packet_send_debug("X11 forwarding disabled in user configuration file.");
2174 if (!options.x11_forwarding) {
2175 debug("X11 forwarding disabled in server configuration file.");
2178 if (!options.xauth_location ||
2179 (stat(options.xauth_location, &st) == -1)) {
2180 packet_send_debug("No xauth program; cannot forward with spoofing.");
2183 if (options.use_login) {
2184 packet_send_debug("X11 forwarding disabled; "
2185 "not compatible with UseLogin=yes.");
2188 if (s->display != NULL) {
2189 debug("X11 display already set.");
2192 if (x11_create_display_inet(options.x11_display_offset,
2193 options.x11_use_localhost, s->single_connection,
2194 &s->display_number) == -1) {
2195 debug("x11_create_display_inet failed.");
2199 /* Set up a suitable value for the DISPLAY variable. */
2200 if (gethostname(hostname, sizeof(hostname)) < 0)
2201 fatal("gethostname: %.100s", strerror(errno));
2203 * auth_display must be used as the displayname when the
2204 * authorization entry is added with xauth(1). This will be
2205 * different than the DISPLAY string for localhost displays.
2207 if (options.x11_use_localhost) {
2208 snprintf(display, sizeof display, "localhost:%u.%u",
2209 s->display_number, s->screen);
2210 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2211 s->display_number, s->screen);
2212 s->display = xstrdup(display);
2213 s->auth_display = xstrdup(auth_display);
2215 #ifdef IPADDR_IN_DISPLAY
2217 struct in_addr my_addr;
2219 he = gethostbyname(hostname);
2221 error("Can't get IP address for X11 DISPLAY.");
2222 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2225 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2226 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2227 s->display_number, s->screen);
2229 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2230 s->display_number, s->screen);
2232 s->display = xstrdup(display);
2233 s->auth_display = xstrdup(display);
2240 do_authenticated2(Authctxt *authctxt)
2242 server_loop2(authctxt);
2246 do_cleanup(Authctxt *authctxt)
2248 static int called = 0;
2250 debug("do_cleanup");
2252 /* no cleanup if we're in the child for login shell */
2256 /* avoid double cleanup */
2261 if (authctxt == NULL)
2264 if (options.kerberos_ticket_cleanup &&
2266 krb5_cleanup_proc(authctxt);
2270 if (compat20 && options.gss_cleanup_creds)
2271 ssh_gssapi_cleanup_creds();
2275 if (options.use_pam) {
2277 sshpam_thread_cleanup();
2281 /* remove agent socket */
2282 auth_sock_cleanup_proc(authctxt->pw);
2285 * Cleanup ptys/utmp only if privsep is disabled,
2286 * or if running in monitor.
2288 if (!use_privsep || mm_is_monitor())
2289 session_destroy_all(session_pty_cleanup2);