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.150 2002/09/16 19:55:33 stevesk Exp $");
37 RCSID("$FreeBSD: src/crypto/openssh/session.c,v 1.4.2.17 2003/02/03 17:31:07 des Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
60 #include "monitor_wrap.h"
64 #include <sys/cygwin.h>
65 #define is_winnt (GetVersion() < 0x80000000)
70 Session *session_new(void);
71 void session_set_fds(Session *, int, int, int);
72 void session_pty_cleanup(void *);
73 void session_proctitle(Session *);
74 int session_setup_x11fwd(Session *);
75 void do_exec_pty(Session *, const char *);
76 void do_exec_no_pty(Session *, const char *);
77 void do_exec(Session *, const char *);
78 void do_login(Session *, const char *);
79 #ifdef LOGIN_NEEDS_UTMPX
80 static void do_pre_login(Session *s);
82 void do_child(Session *, const char *);
84 int check_quietlogin(Session *, const char *);
86 static void do_authenticated1(Authctxt *);
87 static void do_authenticated2(Authctxt *);
89 static int session_pty_req(Session *);
92 extern ServerOptions options;
93 extern char *__progname;
94 extern int log_stderr;
95 extern int debug_flag;
96 extern u_int utmp_len;
97 extern int startup_pipe;
98 extern void destroy_sensitive_data(void);
100 /* original command from peer. */
101 const char *original_command = NULL;
104 #define MAX_SESSIONS 10
105 Session sessions[MAX_SESSIONS];
107 #ifdef WITH_AIXAUTHENTICATE
109 #endif /* WITH_AIXAUTHENTICATE */
111 #ifdef HAVE_LOGIN_CAP
115 /* Name and directory of socket for authentication agent forwarding. */
116 static char *auth_sock_name = NULL;
117 static char *auth_sock_dir = NULL;
119 /* removes the agent forwarding socket */
122 auth_sock_cleanup_proc(void *_pw)
124 struct passwd *pw = _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-XXXXXXXX", 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 /* delete agent socket on fatal() */
170 fatal_add_cleanup(auth_sock_cleanup_proc, pw);
172 /* Create the socket. */
173 sock = socket(AF_UNIX, SOCK_STREAM, 0);
175 packet_disconnect("socket: %.100s", strerror(errno));
177 /* Bind it to the name. */
178 memset(&sunaddr, 0, sizeof(sunaddr));
179 sunaddr.sun_family = AF_UNIX;
180 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
182 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
183 packet_disconnect("bind: %.100s", strerror(errno));
185 /* Restore the privileged uid. */
188 /* Start listening on the socket. */
189 if (listen(sock, 5) < 0)
190 packet_disconnect("listen: %.100s", strerror(errno));
192 /* Allocate a channel for the authentication agent socket. */
193 nc = channel_new("auth socket",
194 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
195 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
196 0, xstrdup("auth socket"), 1);
197 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
203 do_authenticated(Authctxt *authctxt)
206 * Cancel the alarm we set to limit the time taken for
210 if (startup_pipe != -1) {
215 /* setup the channel layer */
216 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
217 channel_permit_all_opens();
220 do_authenticated2(authctxt);
222 do_authenticated1(authctxt);
224 /* remove agent socket */
225 if (auth_sock_name != NULL)
226 auth_sock_cleanup_proc(authctxt->pw);
228 if (options.kerberos_ticket_cleanup)
229 krb4_cleanup_proc(authctxt);
232 if (options.kerberos_ticket_cleanup)
233 krb5_cleanup_proc(authctxt);
238 * Prepares for an interactive session. This is called after the user has
239 * been successfully authenticated. During this message exchange, pseudo
240 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
241 * are requested, etc.
244 do_authenticated1(Authctxt *authctxt)
248 int success, type, screen_flag;
249 int enable_compression_after_reply = 0;
250 u_int proto_len, data_len, dlen, compression_level = 0;
253 s->authctxt = authctxt;
254 s->pw = authctxt->pw;
257 * We stay in this loop until the client requests to execute a shell
263 /* Get a packet from the client. */
264 type = packet_read();
266 /* Process the packet. */
268 case SSH_CMSG_REQUEST_COMPRESSION:
269 compression_level = packet_get_int();
271 if (compression_level < 1 || compression_level > 9) {
272 packet_send_debug("Received illegal compression level %d.",
276 if (!options.compression) {
277 debug2("compression disabled");
280 /* Enable compression after we have responded with SUCCESS. */
281 enable_compression_after_reply = 1;
285 case SSH_CMSG_REQUEST_PTY:
286 success = session_pty_req(s);
289 case SSH_CMSG_X11_REQUEST_FORWARDING:
290 s->auth_proto = packet_get_string(&proto_len);
291 s->auth_data = packet_get_string(&data_len);
293 screen_flag = packet_get_protocol_flags() &
294 SSH_PROTOFLAG_SCREEN_NUMBER;
295 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
297 if (packet_remaining() == 4) {
299 debug2("Buggy client: "
300 "X11 screen flag missing");
301 s->screen = packet_get_int();
306 success = session_setup_x11fwd(s);
308 xfree(s->auth_proto);
310 s->auth_proto = NULL;
315 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
316 if (no_agent_forwarding_flag || compat13) {
317 debug("Authentication agent forwarding not permitted for this authentication.");
320 debug("Received authentication agent forwarding request.");
321 success = auth_input_request_forwarding(s->pw);
324 case SSH_CMSG_PORT_FORWARD_REQUEST:
325 if (no_port_forwarding_flag) {
326 debug("Port forwarding not permitted for this authentication.");
329 if (!options.allow_tcp_forwarding) {
330 debug("Port forwarding not permitted.");
333 debug("Received TCP/IP port forwarding request.");
334 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
338 case SSH_CMSG_MAX_PACKET_SIZE:
339 if (packet_set_maxsize(packet_get_int()) > 0)
343 #if defined(AFS) || defined(KRB5)
344 case SSH_CMSG_HAVE_KERBEROS_TGT:
345 if (!options.kerberos_tgt_passing) {
346 verbose("Kerberos TGT passing disabled.");
348 char *kdata = packet_get_string(&dlen);
351 /* XXX - 0x41, see creds_to_radix version */
352 if (kdata[0] != 0x41) {
358 if (auth_krb5_tgt(s->authctxt, &tgt))
361 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
365 if (auth_krb4_tgt(s->authctxt, kdata))
368 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
374 #endif /* AFS || KRB5 */
377 case SSH_CMSG_HAVE_AFS_TOKEN:
378 if (!options.afs_token_passing || !k_hasafs()) {
379 verbose("AFS token passing disabled.");
381 /* Accept AFS token. */
382 char *token = packet_get_string(&dlen);
385 if (auth_afs_token(s->authctxt, token))
388 verbose("AFS token refused for %.100s",
395 case SSH_CMSG_EXEC_SHELL:
396 case SSH_CMSG_EXEC_CMD:
397 if (type == SSH_CMSG_EXEC_CMD) {
398 command = packet_get_string(&dlen);
399 debug("Exec command '%.500s'", command);
411 * Any unknown messages in this phase are ignored,
412 * and a failure message is returned.
414 log("Unknown packet type received after authentication: %d", type);
416 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
420 /* Enable compression now that we have replied if appropriate. */
421 if (enable_compression_after_reply) {
422 enable_compression_after_reply = 0;
423 packet_start_compression(compression_level);
429 * This is called to fork and execute a command when we have no tty. This
430 * will call do_child from the child, and server_loop from the parent after
431 * setting up file descriptors and such.
434 do_exec_no_pty(Session *s, const char *command)
439 int pin[2], pout[2], perr[2];
440 /* Allocate pipes for communicating with the program. */
441 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
442 packet_disconnect("Could not create pipes: %.100s",
444 #else /* USE_PIPES */
445 int inout[2], err[2];
446 /* Uses socket pairs to communicate with the program. */
447 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
448 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
449 packet_disconnect("Could not create socket pairs: %.100s",
451 #endif /* USE_PIPES */
453 fatal("do_exec_no_pty: no session");
455 session_proctitle(s);
458 do_pam_session(s->pw->pw_name, NULL);
460 if (is_pam_password_change_required())
461 packet_disconnect("Password change required but no "
465 /* Fork the child. */
466 if ((pid = fork()) == 0) {
467 fatal_remove_all_cleanups();
469 /* Child. Reinitialize the log since the pid has changed. */
470 log_init(__progname, options.log_level, options.log_facility, log_stderr);
473 * Create a new session and process group since the 4.4BSD
474 * setlogin() affects the entire process group.
477 error("setsid failed: %.100s", strerror(errno));
481 * Redirect stdin. We close the parent side of the socket
482 * pair, and make the child side the standard input.
485 if (dup2(pin[0], 0) < 0)
486 perror("dup2 stdin");
489 /* Redirect stdout. */
491 if (dup2(pout[1], 1) < 0)
492 perror("dup2 stdout");
495 /* Redirect stderr. */
497 if (dup2(perr[1], 2) < 0)
498 perror("dup2 stderr");
500 #else /* USE_PIPES */
502 * Redirect stdin, stdout, and stderr. Stdin and stdout will
503 * use the same socket, as some programs (particularly rdist)
504 * seem to depend on it.
508 if (dup2(inout[0], 0) < 0) /* stdin */
509 perror("dup2 stdin");
510 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
511 perror("dup2 stdout");
512 if (dup2(err[0], 2) < 0) /* stderr */
513 perror("dup2 stderr");
514 #endif /* USE_PIPES */
517 cray_init_job(s->pw); /* set up cray jid and tmpdir */
520 /* Do processing for the child (exec command etc). */
521 do_child(s, command);
525 signal(WJSIGNAL, cray_job_termination_handler);
529 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
532 packet_disconnect("fork failed: %.100s", strerror(errno));
534 /* Set interactive/non-interactive mode. */
535 packet_set_interactive(s->display != NULL);
537 /* We are the parent. Close the child sides of the pipes. */
543 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
545 /* Enter the interactive session. */
546 server_loop(pid, pin[1], pout[0], perr[0]);
547 /* server_loop has closed pin[1], pout[0], and perr[0]. */
549 #else /* USE_PIPES */
550 /* We are the parent. Close the child sides of the socket pairs. */
555 * Enter the interactive session. Note: server_loop must be able to
556 * handle the case that fdin and fdout are the same.
559 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
561 server_loop(pid, inout[1], inout[1], err[1]);
562 /* server_loop has closed inout[1] and err[1]. */
564 #endif /* USE_PIPES */
568 * This is called to fork and execute a command when we have a tty. This
569 * will call do_child from the child, and server_loop from the parent after
570 * setting up file descriptors, controlling tty, updating wtmp, utmp,
571 * lastlog, and other such operations.
574 do_exec_pty(Session *s, const char *command)
576 int fdout, ptyfd, ttyfd, ptymaster;
580 fatal("do_exec_pty: no session");
585 do_pam_session(s->pw->pw_name, s->tty);
589 /* Fork the child. */
590 if ((pid = fork()) == 0) {
591 fatal_remove_all_cleanups();
593 /* Child. Reinitialize the log because the pid has changed. */
594 log_init(__progname, options.log_level, options.log_facility, log_stderr);
595 /* Close the master side of the pseudo tty. */
598 /* Make the pseudo tty our controlling tty. */
599 pty_make_controlling_tty(&ttyfd, s->tty);
601 /* Redirect stdin/stdout/stderr from the pseudo tty. */
602 if (dup2(ttyfd, 0) < 0)
603 error("dup2 stdin: %s", strerror(errno));
604 if (dup2(ttyfd, 1) < 0)
605 error("dup2 stdout: %s", strerror(errno));
606 if (dup2(ttyfd, 2) < 0)
607 error("dup2 stderr: %s", strerror(errno));
609 /* Close the extra descriptor for the pseudo tty. */
612 /* record login, etc. similar to login(1) */
614 if (!(options.use_login && command == NULL)) {
616 cray_init_job(s->pw); /* set up cray jid and tmpdir */
618 do_login(s, command);
620 # ifdef LOGIN_NEEDS_UTMPX
626 /* Do common processing for the child, such as execing the command. */
627 do_child(s, command);
631 signal(WJSIGNAL, cray_job_termination_handler);
635 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
638 packet_disconnect("fork failed: %.100s", strerror(errno));
641 /* Parent. Close the slave side of the pseudo tty. */
645 * Create another descriptor of the pty master side for use as the
646 * standard input. We could use the original descriptor, but this
647 * simplifies code in server_loop. The descriptor is bidirectional.
651 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
653 /* we keep a reference to the pty master */
654 ptymaster = dup(ptyfd);
656 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
657 s->ptymaster = ptymaster;
659 /* Enter interactive session. */
660 packet_set_interactive(1);
662 session_set_fds(s, ptyfd, fdout, -1);
664 server_loop(pid, ptyfd, fdout, -1);
665 /* server_loop _has_ closed ptyfd and fdout. */
669 #ifdef LOGIN_NEEDS_UTMPX
671 do_pre_login(Session *s)
674 struct sockaddr_storage from;
675 pid_t pid = getpid();
678 * Get IP address of client. If the connection is not a socket, let
679 * the address be 0.0.0.0.
681 memset(&from, 0, sizeof(from));
682 fromlen = sizeof(from);
683 if (packet_connection_is_on_socket()) {
684 if (getpeername(packet_get_connection_in(),
685 (struct sockaddr *) & from, &fromlen) < 0) {
686 debug("getpeername: %.100s", strerror(errno));
691 record_utmp_only(pid, s->tty, s->pw->pw_name,
692 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
693 (struct sockaddr *)&from, fromlen);
698 * This is called to fork and execute a command. If another command is
699 * to be forced, execute that instead.
702 do_exec(Session *s, const char *command)
704 if (forced_command) {
705 original_command = command;
706 command = forced_command;
707 debug("Forced command '%.900s'", command);
711 do_exec_pty(s, command);
713 do_exec_no_pty(s, command);
715 original_command = NULL;
719 /* administrative, login(1)-like work */
721 do_login(Session *s, const char *command)
725 struct sockaddr_storage from;
726 struct passwd * pw = s->pw;
727 pid_t pid = getpid();
730 * Get IP address of client. If the connection is not a socket, let
731 * the address be 0.0.0.0.
733 memset(&from, 0, sizeof(from));
734 fromlen = sizeof(from);
735 if (packet_connection_is_on_socket()) {
736 if (getpeername(packet_get_connection_in(),
737 (struct sockaddr *) & from, &fromlen) < 0) {
738 debug("getpeername: %.100s", strerror(errno));
743 /* Record that there was a login on that tty from the remote host. */
745 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
746 get_remote_name_or_ip(utmp_len,
747 options.verify_reverse_mapping),
748 (struct sockaddr *)&from, fromlen);
752 * If password change is needed, do it now.
753 * This needs to occur before the ~/.hushlogin check.
755 if (is_pam_password_change_required()) {
756 print_pam_messages();
761 if (check_quietlogin(s, command))
765 if (!is_pam_password_change_required())
766 print_pam_messages();
768 #ifdef WITH_AIXAUTHENTICATE
769 if (aixloginmsg && *aixloginmsg)
770 printf("%s\n", aixloginmsg);
771 #endif /* WITH_AIXAUTHENTICATE */
773 #ifndef NO_SSH_LASTLOG
774 if (options.print_lastlog && s->last_login_time != 0) {
775 time_string = ctime(&s->last_login_time);
776 if (strchr(time_string, '\n'))
777 *strchr(time_string, '\n') = 0;
778 if (strcmp(s->hostname, "") == 0)
779 printf("Last login: %s\r\n", time_string);
781 printf("Last login: %s from %s\r\n", time_string,
784 #endif /* NO_SSH_LASTLOG */
790 * Display the message of the day.
797 #ifdef HAVE_LOGIN_CAP
801 #ifdef HAVE_LOGIN_CAP
802 fname = login_getcapstr(lc, "copyright", NULL, NULL);
803 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
804 while (fgets(buf, sizeof(buf), f) != NULL)
808 #endif /* HAVE_LOGIN_CAP */
809 (void)printf("%s\n\t%s %s\n",
810 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
811 "The Regents of the University of California. ",
812 "All rights reserved.");
816 if (options.print_motd) {
817 #ifdef HAVE_LOGIN_CAP
818 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
821 f = fopen("/etc/motd", "r");
824 while (fgets(buf, sizeof(buf), f))
833 * Check for quiet login, either .hushlogin or command given.
836 check_quietlogin(Session *s, const char *command)
839 struct passwd *pw = s->pw;
842 /* Return 1 if .hushlogin exists or a command given. */
845 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
846 #ifdef HAVE_LOGIN_CAP
847 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
850 if (stat(buf, &st) >= 0)
857 * Sets the value of the given variable in the environment. If the variable
858 * already exists, its value is overriden.
861 child_set_env(char ***envp, u_int *envsizep, const char *name,
868 * Find the slot where the value should be stored. If the variable
869 * already exists, we reuse the slot; otherwise we append a new slot
870 * at the end of the array, expanding if necessary.
873 namelen = strlen(name);
874 for (i = 0; env[i]; i++)
875 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
878 /* Reuse the slot. */
881 /* New variable. Expand if necessary. */
882 if (i >= (*envsizep) - 1) {
883 if (*envsizep >= 1000)
884 fatal("child_set_env: too many env vars,"
885 " skipping: %.100s", name);
887 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
889 /* Need to set the NULL pointer at end of array beyond the new slot. */
893 /* Allocate space and format the variable in the appropriate slot. */
894 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
895 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
899 * Reads environment variables from the given file and adds/overrides them
900 * into the environment. If the file does not exist, this does nothing.
901 * Otherwise, it must consist of empty lines, comments (line starts with '#')
902 * and assignments of the form name=value. No other forms are allowed.
905 read_environment_file(char ***env, u_int *envsize,
906 const char *filename)
913 f = fopen(filename, "r");
917 while (fgets(buf, sizeof(buf), f)) {
919 fatal("Too many lines in environment file %s", filename);
920 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
922 if (!*cp || *cp == '#' || *cp == '\n')
924 if (strchr(cp, '\n'))
925 *strchr(cp, '\n') = '\0';
926 value = strchr(cp, '=');
928 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
933 * Replace the equals sign by nul, and advance value to
938 child_set_env(env, envsize, cp, value);
943 void copy_environment(char **source, char ***env, u_int *envsize)
945 char *var_name, *var_val;
951 for(i = 0; source[i] != NULL; i++) {
952 var_name = xstrdup(source[i]);
953 if ((var_val = strstr(var_name, "=")) == NULL) {
959 debug3("Copy environment: %s=%s", var_name, var_val);
960 child_set_env(env, envsize, var_name, var_val);
967 do_setup_env(Session *s, const char *shell)
972 #ifdef HAVE_LOGIN_CAP
973 extern char **environ;
976 struct passwd *pw = s->pw;
978 /* Initialize the environment. */
980 env = xmalloc(envsize * sizeof(char *));
985 * The Windows environment contains some setting which are
986 * important for a running system. They must not be dropped.
988 copy_environment(environ, &env, &envsize);
992 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
993 if (!options.use_login) {
994 /* Set basic environment. */
995 child_set_env(&env, &envsize, "USER", pw->pw_name);
996 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
997 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
998 snprintf(buf, sizeof buf, "%.200s/%.50s",
999 _PATH_MAILDIR, pw->pw_name);
1000 child_set_env(&env, &envsize, "MAIL", buf);
1001 #ifdef HAVE_LOGIN_CAP
1002 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1003 child_set_env(&env, &envsize, "TERM", "su");
1005 environ = xmalloc(sizeof(char *));
1007 (void) setusercontext(lc, pw, pw->pw_uid,
1008 LOGIN_SETENV|LOGIN_SETPATH);
1009 copy_environment(environ, &env, &envsize);
1010 for (var = environ; *var != NULL; ++var)
1014 #else /* HAVE_LOGIN_CAP */
1015 # ifndef HAVE_CYGWIN
1017 * There's no standard path on Windows. The path contains
1018 * important components pointing to the system directories,
1019 * needed for loading shared libraries. So the path better
1020 * remains intact here.
1022 # ifdef SUPERUSER_PATH
1023 child_set_env(&env, &envsize, "PATH",
1024 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1026 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1027 # endif /* SUPERUSER_PATH */
1028 # endif /* HAVE_CYGWIN */
1029 #endif /* HAVE_LOGIN_CAP */
1031 /* Normal systems set SHELL by default. */
1032 child_set_env(&env, &envsize, "SHELL", shell);
1035 /* Set custom environment options from RSA authentication. */
1036 if (!options.use_login) {
1037 while (custom_environment) {
1038 struct envstring *ce = custom_environment;
1041 for (i = 0; str[i] != '=' && str[i]; i++)
1043 if (str[i] == '=') {
1045 child_set_env(&env, &envsize, str, str + i + 1);
1047 custom_environment = ce->next;
1053 /* SSH_CLIENT deprecated */
1054 snprintf(buf, sizeof buf, "%.50s %d %d",
1055 get_remote_ipaddr(), get_remote_port(), get_local_port());
1056 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1058 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1059 get_remote_ipaddr(), get_remote_port(),
1060 get_local_ipaddr(packet_get_connection_in()), get_local_port());
1061 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1064 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1066 child_set_env(&env, &envsize, "TERM", s->term);
1068 child_set_env(&env, &envsize, "DISPLAY", s->display);
1069 if (original_command)
1070 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1074 if (cray_tmpdir[0] != '\0')
1075 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1076 #endif /* _UNICOS */
1082 if ((cp = getenv("AUTHSTATE")) != NULL)
1083 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1084 if ((cp = getenv("KRB5CCNAME")) != NULL)
1085 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1086 read_environment_file(&env, &envsize, "/etc/environment");
1090 if (s->authctxt->krb4_ticket_file)
1091 child_set_env(&env, &envsize, "KRBTKFILE",
1092 s->authctxt->krb4_ticket_file);
1095 if (s->authctxt->krb5_ticket_file)
1096 child_set_env(&env, &envsize, "KRB5CCNAME",
1097 s->authctxt->krb5_ticket_file);
1101 * Pull in any environment variables that may have
1107 p = fetch_pam_environment();
1108 copy_environment(p, &env, &envsize);
1109 free_pam_environment(p);
1111 #endif /* USE_PAM */
1113 if (auth_sock_name != NULL)
1114 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1117 /* read $HOME/.ssh/environment. */
1118 if (options.permit_user_env && !options.use_login) {
1119 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1120 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1121 read_environment_file(&env, &envsize, buf);
1124 /* dump the environment */
1125 fprintf(stderr, "Environment:\n");
1126 for (i = 0; env[i]; i++)
1127 fprintf(stderr, " %.200s\n", env[i]);
1133 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1134 * first in this order).
1137 do_rc_files(Session *s, const char *shell)
1145 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1147 /* ignore _PATH_SSH_USER_RC for subsystems */
1148 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1149 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1150 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1152 fprintf(stderr, "Running %s\n", cmd);
1153 f = popen(cmd, "w");
1156 fprintf(f, "%s %s\n", s->auth_proto,
1160 fprintf(stderr, "Could not run %s\n",
1162 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1164 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1165 _PATH_SSH_SYSTEM_RC);
1166 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1169 fprintf(f, "%s %s\n", s->auth_proto,
1173 fprintf(stderr, "Could not run %s\n",
1174 _PATH_SSH_SYSTEM_RC);
1175 } else if (do_xauth && options.xauth_location != NULL) {
1176 /* Add authority data to .Xauthority if appropriate. */
1179 "Running %.500s add "
1180 "%.100s %.100s %.100s\n",
1181 options.xauth_location, s->auth_display,
1182 s->auth_proto, s->auth_data);
1184 snprintf(cmd, sizeof cmd, "%s -q -",
1185 options.xauth_location);
1186 f = popen(cmd, "w");
1188 fprintf(f, "add %s %s %s\n",
1189 s->auth_display, s->auth_proto,
1193 fprintf(stderr, "Could not run %s\n",
1200 do_nologin(struct passwd *pw)
1205 #ifdef HAVE_LOGIN_CAP
1206 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1207 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1208 _PATH_NOLOGIN), "r");
1211 f = fopen(_PATH_NOLOGIN, "r");
1214 /* /etc/nologin exists. Print its contents and exit. */
1215 log("User %.100s not allowed because %s exists",
1216 pw->pw_name, _PATH_NOLOGIN);
1217 while (fgets(buf, sizeof(buf), f))
1224 /* Set login name, uid, gid, and groups. */
1226 do_setusercontext(struct passwd *pw)
1230 #else /* HAVE_CYGWIN */
1231 if (getuid() == 0 || geteuid() == 0) {
1232 #endif /* HAVE_CYGWIN */
1233 #ifdef HAVE_SETPCRED
1234 setpcred(pw->pw_name);
1235 #endif /* HAVE_SETPCRED */
1236 #ifdef HAVE_LOGIN_CAP
1240 if (setusercontext(lc, pw, pw->pw_uid,
1241 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1242 perror("unable to set user context");
1246 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1247 /* Sets login uid for accounting */
1248 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1249 error("setluid: %s", strerror(errno));
1250 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1252 if (setlogin(pw->pw_name) < 0)
1253 error("setlogin failed: %s", strerror(errno));
1254 if (setgid(pw->pw_gid) < 0) {
1258 /* Initialize the group list. */
1259 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1260 perror("initgroups");
1266 * PAM credentials may take the form of supplementary groups.
1267 * These will have been wiped by the above initgroups() call.
1268 * Reestablish them here.
1271 # endif /* USE_PAM */
1272 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1273 irix_setusercontext(pw);
1274 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1278 /* Permanently switch to the desired uid. */
1279 permanently_set_uid(pw);
1282 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1283 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1287 launch_login(struct passwd *pw, const char *hostname)
1289 /* Launch login(1). */
1291 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1292 #ifdef xxxLOGIN_NEEDS_TERM
1293 (s->term ? s->term : "unknown"),
1294 #endif /* LOGIN_NEEDS_TERM */
1295 #ifdef LOGIN_NO_ENDOPT
1296 "-p", "-f", pw->pw_name, (char *)NULL);
1298 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1301 /* Login couldn't be executed, die. */
1308 * Performs common processing for the child, such as setting up the
1309 * environment, closing extra file descriptors, setting the user and group
1310 * ids, and executing the command or shell.
1313 do_child(Session *s, const char *command)
1315 extern char **environ;
1318 const char *shell, *shell0, *hostname = NULL;
1319 struct passwd *pw = s->pw;
1321 #ifdef HAVE_LOGIN_CAP
1325 /* remove hostkey from the child's memory */
1326 destroy_sensitive_data();
1328 /* login(1) is only called if we execute the login shell */
1329 if (options.use_login && command != NULL)
1330 options.use_login = 0;
1333 cray_setup(pw->pw_uid, pw->pw_name, command);
1334 #endif /* _UNICOS */
1337 * Login(1) does this as well, and it needs uid 0 for the "-h"
1338 * switch, so we let login(1) to this for us.
1340 if (!options.use_login) {
1342 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1343 if (!check_quietlogin(s, command))
1345 #else /* HAVE_OSF_SIA */
1347 do_setusercontext(pw);
1348 #endif /* HAVE_OSF_SIA */
1352 * Get the shell from the password data. An empty shell field is
1353 * legal, and means /bin/sh.
1355 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1356 #ifdef HAVE_LOGIN_CAP
1357 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1360 env = do_setup_env(s, shell);
1362 /* we have to stash the hostname before we close our socket. */
1363 if (options.use_login)
1364 hostname = get_remote_name_or_ip(utmp_len,
1365 options.verify_reverse_mapping);
1367 * Close the connection descriptors; note that this is the child, and
1368 * the server will still have the socket open, and it is important
1369 * that we do not shutdown it. Note that the descriptors cannot be
1370 * closed before building the environment, as we call
1371 * get_remote_ipaddr there.
1373 if (packet_get_connection_in() == packet_get_connection_out())
1374 close(packet_get_connection_in());
1376 close(packet_get_connection_in());
1377 close(packet_get_connection_out());
1380 * Close all descriptors related to channels. They will still remain
1381 * open in the parent.
1383 /* XXX better use close-on-exec? -markus */
1384 channel_close_all();
1386 #ifdef HAVE_LOGIN_CAP
1387 lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1391 * Close any extra file descriptors. Note that there may still be
1392 * descriptors left by system functions. They will be closed later.
1397 * Close any extra open file descriptors so that we don\'t have them
1398 * hanging around in clients. Note that we want to do this after
1399 * initgroups, because at least on Solaris 2.3 it leaves file
1402 for (i = 3; i < 64; i++)
1406 * Must take new environment into use so that .ssh/rc,
1407 * /etc/ssh/sshrc and xauth are run in the proper environment.
1412 /* Try to get AFS tokens for the local cell. */
1416 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1417 krb_afslog(cell, 0);
1423 /* Change current directory to the user\'s home directory. */
1424 if (chdir(pw->pw_dir) < 0) {
1425 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1426 pw->pw_dir, strerror(errno));
1427 #ifdef HAVE_LOGIN_CAP
1433 if (!options.use_login)
1434 do_rc_files(s, shell);
1436 /* restore SIGPIPE for child */
1437 signal(SIGPIPE, SIG_DFL);
1439 if (options.use_login) {
1440 launch_login(pw, hostname);
1444 /* Get the last component of the shell name. */
1445 if ((shell0 = strrchr(shell, '/')) != NULL)
1451 * If we have no command, execute the shell. In this case, the shell
1452 * name to be passed in argv[0] is preceded by '-' to indicate that
1453 * this is a login shell.
1458 /* Start the shell. Set initial character to '-'. */
1461 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1462 >= sizeof(argv0) - 1) {
1468 /* Execute the shell. */
1471 execve(shell, argv, env);
1473 /* Executing the shell failed. */
1478 * Execute the command using the user's shell. This uses the -c
1479 * option to execute the command.
1481 argv[0] = (char *) shell0;
1483 argv[2] = (char *) command;
1485 execve(shell, argv, env);
1494 static int did_init = 0;
1496 debug("session_new: init");
1497 for (i = 0; i < MAX_SESSIONS; i++) {
1498 sessions[i].used = 0;
1502 for (i = 0; i < MAX_SESSIONS; i++) {
1503 Session *s = &sessions[i];
1505 memset(s, 0, sizeof(*s));
1511 debug("session_new: session %d", i);
1522 for (i = 0; i < MAX_SESSIONS; i++) {
1523 Session *s = &sessions[i];
1524 debug("dump: used %d session %d %p channel %d pid %ld",
1534 session_open(Authctxt *authctxt, int chanid)
1536 Session *s = session_new();
1537 debug("session_open: channel %d", chanid);
1539 error("no more sessions");
1542 s->authctxt = authctxt;
1543 s->pw = authctxt->pw;
1545 fatal("no user for session %d", s->self);
1546 debug("session_open: session %d: link with channel %d", s->self, chanid);
1552 session_by_tty(char *tty)
1555 for (i = 0; i < MAX_SESSIONS; i++) {
1556 Session *s = &sessions[i];
1557 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1558 debug("session_by_tty: session %d tty %s", i, tty);
1562 debug("session_by_tty: unknown tty %.100s", tty);
1568 session_by_channel(int id)
1571 for (i = 0; i < MAX_SESSIONS; i++) {
1572 Session *s = &sessions[i];
1573 if (s->used && s->chanid == id) {
1574 debug("session_by_channel: session %d channel %d", i, id);
1578 debug("session_by_channel: unknown channel %d", id);
1584 session_by_pid(pid_t pid)
1587 debug("session_by_pid: pid %ld", (long)pid);
1588 for (i = 0; i < MAX_SESSIONS; i++) {
1589 Session *s = &sessions[i];
1590 if (s->used && s->pid == pid)
1593 error("session_by_pid: unknown pid %ld", (long)pid);
1599 session_window_change_req(Session *s)
1601 s->col = packet_get_int();
1602 s->row = packet_get_int();
1603 s->xpixel = packet_get_int();
1604 s->ypixel = packet_get_int();
1606 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1611 session_pty_req(Session *s)
1617 debug("Allocating a pty not permitted for this authentication.");
1620 if (s->ttyfd != -1) {
1621 packet_disconnect("Protocol error: you already have a pty.");
1624 /* Get the time and hostname when the user last logged in. */
1625 if (options.print_lastlog) {
1626 s->hostname[0] = '\0';
1627 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1628 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1631 s->term = packet_get_string(&len);
1634 s->col = packet_get_int();
1635 s->row = packet_get_int();
1637 s->row = packet_get_int();
1638 s->col = packet_get_int();
1640 s->xpixel = packet_get_int();
1641 s->ypixel = packet_get_int();
1643 if (strcmp(s->term, "") == 0) {
1648 /* Allocate a pty and open it. */
1649 debug("Allocating pty.");
1650 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1656 error("session_pty_req: session %d alloc failed", s->self);
1659 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1661 /* for SSH1 the tty modes length is not given */
1663 n_bytes = packet_remaining();
1664 tty_parse_modes(s->ttyfd, &n_bytes);
1667 * Add a cleanup function to clear the utmp entry and record logout
1668 * time in case we call fatal() (e.g., the connection gets closed).
1670 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1672 pty_setowner(s->pw, s->tty);
1674 /* Set window size from the packet. */
1675 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1678 session_proctitle(s);
1683 session_subsystem_req(Session *s)
1688 char *cmd, *subsys = packet_get_string(&len);
1692 log("subsystem request for %.100s", subsys);
1694 for (i = 0; i < options.num_subsystems; i++) {
1695 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1696 cmd = options.subsystem_command[i];
1697 if (stat(cmd, &st) < 0) {
1698 error("subsystem: cannot stat %s: %s", cmd,
1702 debug("subsystem: exec() %s", cmd);
1703 s->is_subsystem = 1;
1711 log("subsystem request for %.100s failed, subsystem not found",
1719 session_x11_req(Session *s)
1723 s->single_connection = packet_get_char();
1724 s->auth_proto = packet_get_string(NULL);
1725 s->auth_data = packet_get_string(NULL);
1726 s->screen = packet_get_int();
1729 success = session_setup_x11fwd(s);
1731 xfree(s->auth_proto);
1732 xfree(s->auth_data);
1733 s->auth_proto = NULL;
1734 s->auth_data = NULL;
1740 session_shell_req(Session *s)
1748 session_exec_req(Session *s)
1751 char *command = packet_get_string(&len);
1753 do_exec(s, command);
1759 session_auth_agent_req(Session *s)
1761 static int called = 0;
1763 if (no_agent_forwarding_flag) {
1764 debug("session_auth_agent_req: no_agent_forwarding_flag");
1771 return auth_input_request_forwarding(s->pw);
1776 session_input_channel_req(Channel *c, const char *rtype)
1781 if ((s = session_by_channel(c->self)) == NULL) {
1782 log("session_input_channel_req: no session %d req %.100s",
1786 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1789 * a session is in LARVAL state until a shell, a command
1790 * or a subsystem is executed
1792 if (c->type == SSH_CHANNEL_LARVAL) {
1793 if (strcmp(rtype, "shell") == 0) {
1794 success = session_shell_req(s);
1795 } else if (strcmp(rtype, "exec") == 0) {
1796 success = session_exec_req(s);
1797 } else if (strcmp(rtype, "pty-req") == 0) {
1798 success = session_pty_req(s);
1799 } else if (strcmp(rtype, "x11-req") == 0) {
1800 success = session_x11_req(s);
1801 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1802 success = session_auth_agent_req(s);
1803 } else if (strcmp(rtype, "subsystem") == 0) {
1804 success = session_subsystem_req(s);
1807 if (strcmp(rtype, "window-change") == 0) {
1808 success = session_window_change_req(s);
1814 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1817 fatal("session_set_fds: called for proto != 2.0");
1819 * now that have a child and a pipe to the child,
1820 * we can activate our channel and register the fd's
1822 if (s->chanid == -1)
1823 fatal("no channel for session %d", s->self);
1824 channel_set_fds(s->chanid,
1826 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1828 CHAN_SES_WINDOW_DEFAULT);
1832 * Function to perform pty cleanup. Also called if we get aborted abnormally
1833 * (e.g., due to a dropped connection).
1836 session_pty_cleanup2(void *session)
1838 Session *s = session;
1841 error("session_pty_cleanup: no session");
1847 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1849 /* Record that the user has logged out. */
1851 record_logout(s->pid, s->tty, s->pw->pw_name);
1853 /* Release the pseudo-tty. */
1855 pty_release(s->tty);
1858 * Close the server side of the socket pairs. We must do this after
1859 * the pty cleanup, so that another process doesn't get this pty
1860 * while we're still cleaning up.
1862 if (close(s->ptymaster) < 0)
1863 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1865 /* unlink pty from session */
1870 session_pty_cleanup(void *session)
1872 PRIVSEP(session_pty_cleanup2(session));
1878 #define SSH_SIG(x) if (sig == SIG ## x) return #x
1893 return "SIG@openssh.com";
1897 session_exit_message(Session *s, int status)
1901 if ((c = channel_lookup(s->chanid)) == NULL)
1902 fatal("session_exit_message: session %d: no channel %d",
1903 s->self, s->chanid);
1904 debug("session_exit_message: session %d channel %d pid %ld",
1905 s->self, s->chanid, (long)s->pid);
1907 if (WIFEXITED(status)) {
1908 channel_request_start(s->chanid, "exit-status", 0);
1909 packet_put_int(WEXITSTATUS(status));
1911 } else if (WIFSIGNALED(status)) {
1912 channel_request_start(s->chanid, "exit-signal", 0);
1913 packet_put_cstring(sig2name(WTERMSIG(status)));
1915 packet_put_char(WCOREDUMP(status));
1916 #else /* WCOREDUMP */
1918 #endif /* WCOREDUMP */
1919 packet_put_cstring("");
1920 packet_put_cstring("");
1923 /* Some weird exit cause. Just exit. */
1924 packet_disconnect("wait returned status %04x.", status);
1927 /* disconnect channel */
1928 debug("session_exit_message: release channel %d", s->chanid);
1929 channel_cancel_cleanup(s->chanid);
1931 * emulate a write failure with 'chan_write_failed', nobody will be
1932 * interested in data we write.
1933 * Note that we must not call 'chan_read_failed', since there could
1934 * be some more data waiting in the pipe.
1936 if (c->ostate != CHAN_OUTPUT_CLOSED)
1937 chan_write_failed(c);
1942 session_close(Session *s)
1944 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1945 if (s->ttyfd != -1) {
1946 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1947 session_pty_cleanup(s);
1953 if (s->auth_display)
1954 xfree(s->auth_display);
1956 xfree(s->auth_data);
1958 xfree(s->auth_proto);
1960 session_proctitle(s);
1964 session_close_by_pid(pid_t pid, int status)
1966 Session *s = session_by_pid(pid);
1968 debug("session_close_by_pid: no session for pid %ld",
1972 if (s->chanid != -1)
1973 session_exit_message(s, status);
1978 * this is called when a channel dies before
1979 * the session 'child' itself dies
1982 session_close_by_channel(int id, void *arg)
1984 Session *s = session_by_channel(id);
1986 debug("session_close_by_channel: no session for id %d", id);
1989 debug("session_close_by_channel: channel %d child %ld",
1992 debug("session_close_by_channel: channel %d: has child", id);
1994 * delay detach of session, but release pty, since
1995 * the fd's to the child are already closed
1997 if (s->ttyfd != -1) {
1998 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1999 session_pty_cleanup(s);
2003 /* detach by removing callback */
2004 channel_cancel_cleanup(s->chanid);
2010 session_destroy_all(void (*closefunc)(Session *))
2013 for (i = 0; i < MAX_SESSIONS; i++) {
2014 Session *s = &sessions[i];
2016 if (closefunc != NULL)
2025 session_tty_list(void)
2027 static char buf[1024];
2030 for (i = 0; i < MAX_SESSIONS; i++) {
2031 Session *s = &sessions[i];
2032 if (s->used && s->ttyfd != -1) {
2034 strlcat(buf, ",", sizeof buf);
2035 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2039 strlcpy(buf, "notty", sizeof buf);
2044 session_proctitle(Session *s)
2047 error("no user for session %d", s->self);
2049 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2053 session_setup_x11fwd(Session *s)
2056 char display[512], auth_display[512];
2057 char hostname[MAXHOSTNAMELEN];
2059 if (no_x11_forwarding_flag) {
2060 packet_send_debug("X11 forwarding disabled in user configuration file.");
2063 if (!options.x11_forwarding) {
2064 debug("X11 forwarding disabled in server configuration file.");
2067 if (!options.xauth_location ||
2068 (stat(options.xauth_location, &st) == -1)) {
2069 packet_send_debug("No xauth program; cannot forward with spoofing.");
2072 if (options.use_login) {
2073 packet_send_debug("X11 forwarding disabled; "
2074 "not compatible with UseLogin=yes.");
2077 if (s->display != NULL) {
2078 debug("X11 display already set.");
2081 if (x11_create_display_inet(options.x11_display_offset,
2082 options.x11_use_localhost, s->single_connection,
2083 &s->display_number) == -1) {
2084 debug("x11_create_display_inet failed.");
2088 /* Set up a suitable value for the DISPLAY variable. */
2089 if (gethostname(hostname, sizeof(hostname)) < 0)
2090 fatal("gethostname: %.100s", strerror(errno));
2092 * auth_display must be used as the displayname when the
2093 * authorization entry is added with xauth(1). This will be
2094 * different than the DISPLAY string for localhost displays.
2096 if (options.x11_use_localhost) {
2097 snprintf(display, sizeof display, "localhost:%u.%u",
2098 s->display_number, s->screen);
2099 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2100 s->display_number, s->screen);
2101 s->display = xstrdup(display);
2102 s->auth_display = xstrdup(auth_display);
2104 #ifdef IPADDR_IN_DISPLAY
2106 struct in_addr my_addr;
2108 he = gethostbyname(hostname);
2110 error("Can't get IP address for X11 DISPLAY.");
2111 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2114 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2115 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2116 s->display_number, s->screen);
2118 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2119 s->display_number, s->screen);
2121 s->display = xstrdup(display);
2122 s->auth_display = xstrdup(display);
2129 do_authenticated2(Authctxt *authctxt)
2131 server_loop2(authctxt);