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.154 2003/03/05 22:33:43 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
59 #include "monitor_wrap.h"
67 #include <sys/cygwin.h>
68 #define is_winnt (GetVersion() < 0x80000000)
73 Session *session_new(void);
74 void session_set_fds(Session *, int, int, int);
75 void session_pty_cleanup(void *);
76 void session_proctitle(Session *);
77 int session_setup_x11fwd(Session *);
78 void do_exec_pty(Session *, const char *);
79 void do_exec_no_pty(Session *, const char *);
80 void do_exec(Session *, const char *);
81 void do_login(Session *, const char *);
82 #ifdef LOGIN_NEEDS_UTMPX
83 static void do_pre_login(Session *s);
85 void do_child(Session *, const char *);
87 int check_quietlogin(Session *, const char *);
89 static void do_authenticated1(Authctxt *);
90 static void do_authenticated2(Authctxt *);
92 static int session_pty_req(Session *);
95 static void execute_session_hook(char* prog, Authctxt *authctxt,
96 int startup, int save);
100 extern ServerOptions options;
101 extern char *__progname;
102 extern int log_stderr;
103 extern int debug_flag;
104 extern u_int utmp_len;
105 extern int startup_pipe;
106 extern void destroy_sensitive_data(void);
108 /* original command from peer. */
109 const char *original_command = NULL;
112 #define MAX_SESSIONS 10
113 Session sessions[MAX_SESSIONS];
115 #ifdef WITH_AIXAUTHENTICATE
117 #endif /* WITH_AIXAUTHENTICATE */
119 #ifdef HAVE_LOGIN_CAP
123 /* Name and directory of socket for authentication agent forwarding. */
124 static char *auth_sock_name = NULL;
125 static char *auth_sock_dir = NULL;
127 /* removes the agent forwarding socket */
130 auth_sock_cleanup_proc(void *_pw)
132 struct passwd *pw = _pw;
134 if (auth_sock_name != NULL) {
135 temporarily_use_uid(pw);
136 unlink(auth_sock_name);
137 rmdir(auth_sock_dir);
138 auth_sock_name = NULL;
144 auth_input_request_forwarding(struct passwd * pw)
148 struct sockaddr_un sunaddr;
150 if (auth_sock_name != NULL) {
151 error("authentication forwarding requested twice.");
155 /* Temporarily drop privileged uid for mkdir/bind. */
156 temporarily_use_uid(pw);
158 /* Allocate a buffer for the socket name, and format the name. */
159 auth_sock_name = xmalloc(MAXPATHLEN);
160 auth_sock_dir = xmalloc(MAXPATHLEN);
161 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
163 /* Create private directory for socket */
164 if (mkdtemp(auth_sock_dir) == NULL) {
165 packet_send_debug("Agent forwarding disabled: "
166 "mkdtemp() failed: %.100s", strerror(errno));
168 xfree(auth_sock_name);
169 xfree(auth_sock_dir);
170 auth_sock_name = NULL;
171 auth_sock_dir = NULL;
174 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
175 auth_sock_dir, (long) getpid());
177 /* delete agent socket on fatal() */
178 fatal_add_cleanup(auth_sock_cleanup_proc, pw);
180 /* Create the socket. */
181 sock = socket(AF_UNIX, SOCK_STREAM, 0);
183 packet_disconnect("socket: %.100s", strerror(errno));
185 /* Bind it to the name. */
186 memset(&sunaddr, 0, sizeof(sunaddr));
187 sunaddr.sun_family = AF_UNIX;
188 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
190 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
191 packet_disconnect("bind: %.100s", strerror(errno));
193 /* Restore the privileged uid. */
196 /* Start listening on the socket. */
197 if (listen(sock, 5) < 0)
198 packet_disconnect("listen: %.100s", strerror(errno));
200 /* Allocate a channel for the authentication agent socket. */
201 nc = channel_new("auth socket",
202 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
203 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
204 0, xstrdup("auth socket"), 1);
205 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
211 do_authenticated(Authctxt *authctxt)
213 setproctitle("%s", authctxt->pw->pw_name);
216 * Cancel the alarm we set to limit the time taken for
220 if (startup_pipe != -1) {
225 /* setup the channel layer */
226 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
227 channel_permit_all_opens();
230 do_authenticated2(authctxt);
232 do_authenticated1(authctxt);
234 /* remove agent socket */
235 if (auth_sock_name != NULL)
236 auth_sock_cleanup_proc(authctxt->pw);
239 if (options.session_hooks_allow &&
240 options.session_hooks_shutdown_cmd)
242 execute_session_hook(options.session_hooks_shutdown_cmd,
244 /* startup = */ 0, /* save = */ 0);
246 if (authctxt->session_env_file)
248 free(authctxt->session_env_file);
253 if (options.kerberos_ticket_cleanup)
254 krb4_cleanup_proc(authctxt);
257 if (options.kerberos_ticket_cleanup)
258 krb5_cleanup_proc(authctxt);
263 * Prepares for an interactive session. This is called after the user has
264 * been successfully authenticated. During this message exchange, pseudo
265 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
266 * are requested, etc.
269 do_authenticated1(Authctxt *authctxt)
273 int success, type, screen_flag;
274 int enable_compression_after_reply = 0;
275 u_int proto_len, data_len, dlen, compression_level = 0;
278 s->authctxt = authctxt;
279 s->pw = authctxt->pw;
282 * We stay in this loop until the client requests to execute a shell
288 /* Get a packet from the client. */
289 type = packet_read();
291 /* Process the packet. */
293 case SSH_CMSG_REQUEST_COMPRESSION:
294 compression_level = packet_get_int();
296 if (compression_level < 1 || compression_level > 9) {
297 packet_send_debug("Received illegal compression level %d.",
301 if (!options.compression) {
302 debug2("compression disabled");
305 /* Enable compression after we have responded with SUCCESS. */
306 enable_compression_after_reply = 1;
310 case SSH_CMSG_REQUEST_PTY:
311 success = session_pty_req(s);
314 case SSH_CMSG_X11_REQUEST_FORWARDING:
315 s->auth_proto = packet_get_string(&proto_len);
316 s->auth_data = packet_get_string(&data_len);
318 screen_flag = packet_get_protocol_flags() &
319 SSH_PROTOFLAG_SCREEN_NUMBER;
320 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
322 if (packet_remaining() == 4) {
324 debug2("Buggy client: "
325 "X11 screen flag missing");
326 s->screen = packet_get_int();
331 success = session_setup_x11fwd(s);
333 xfree(s->auth_proto);
335 s->auth_proto = NULL;
340 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
341 if (no_agent_forwarding_flag || compat13) {
342 debug("Authentication agent forwarding not permitted for this authentication.");
345 debug("Received authentication agent forwarding request.");
346 success = auth_input_request_forwarding(s->pw);
349 case SSH_CMSG_PORT_FORWARD_REQUEST:
350 if (no_port_forwarding_flag) {
351 debug("Port forwarding not permitted for this authentication.");
354 if (!options.allow_tcp_forwarding) {
355 debug("Port forwarding not permitted.");
358 debug("Received TCP/IP port forwarding request.");
359 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
363 case SSH_CMSG_MAX_PACKET_SIZE:
364 if (packet_set_maxsize(packet_get_int()) > 0)
368 #if defined(AFS) || defined(KRB5)
369 case SSH_CMSG_HAVE_KERBEROS_TGT:
370 if (!options.kerberos_tgt_passing) {
371 verbose("Kerberos TGT passing disabled.");
373 char *kdata = packet_get_string(&dlen);
376 /* XXX - 0x41, see creds_to_radix version */
377 if (kdata[0] != 0x41) {
383 if (auth_krb5_tgt(s->authctxt, &tgt))
386 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
390 if (auth_krb4_tgt(s->authctxt, kdata))
393 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
399 #endif /* AFS || KRB5 */
402 case SSH_CMSG_HAVE_AFS_TOKEN:
403 if (!options.afs_token_passing || !k_hasafs()) {
404 verbose("AFS token passing disabled.");
406 /* Accept AFS token. */
407 char *token = packet_get_string(&dlen);
410 if (auth_afs_token(s->authctxt, token))
413 verbose("AFS token refused for %.100s",
420 case SSH_CMSG_EXEC_SHELL:
421 case SSH_CMSG_EXEC_CMD:
422 if (type == SSH_CMSG_EXEC_CMD) {
423 command = packet_get_string(&dlen);
424 debug("Exec command '%.500s'", command);
436 * Any unknown messages in this phase are ignored,
437 * and a failure message is returned.
439 log("Unknown packet type received after authentication: %d", type);
441 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
445 /* Enable compression now that we have replied if appropriate. */
446 if (enable_compression_after_reply) {
447 enable_compression_after_reply = 0;
448 packet_start_compression(compression_level);
454 * This is called to fork and execute a command when we have no tty. This
455 * will call do_child from the child, and server_loop from the parent after
456 * setting up file descriptors and such.
459 do_exec_no_pty(Session *s, const char *command)
464 int pin[2], pout[2], perr[2];
465 /* Allocate pipes for communicating with the program. */
466 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
467 packet_disconnect("Could not create pipes: %.100s",
469 #else /* USE_PIPES */
470 int inout[2], err[2];
471 /* Uses socket pairs to communicate with the program. */
472 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
473 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
474 packet_disconnect("Could not create socket pairs: %.100s",
476 #endif /* USE_PIPES */
478 fatal("do_exec_no_pty: no session");
480 session_proctitle(s);
483 temporarily_use_uid(s->pw);
484 ssh_gssapi_storecreds();
489 do_pam_session(s->pw->pw_name, NULL);
491 if (is_pam_password_change_required())
492 packet_disconnect("Password change required but no "
496 /* Fork the child. */
497 if ((pid = fork()) == 0) {
498 fatal_remove_all_cleanups();
500 /* Child. Reinitialize the log since the pid has changed. */
501 log_init(__progname, options.log_level, options.log_facility, log_stderr);
504 * Create a new session and process group since the 4.4BSD
505 * setlogin() affects the entire process group.
508 error("setsid failed: %.100s", strerror(errno));
512 * Redirect stdin. We close the parent side of the socket
513 * pair, and make the child side the standard input.
516 if (dup2(pin[0], 0) < 0)
517 perror("dup2 stdin");
520 /* Redirect stdout. */
522 if (dup2(pout[1], 1) < 0)
523 perror("dup2 stdout");
526 /* Redirect stderr. */
528 if (dup2(perr[1], 2) < 0)
529 perror("dup2 stderr");
531 #else /* USE_PIPES */
533 * Redirect stdin, stdout, and stderr. Stdin and stdout will
534 * use the same socket, as some programs (particularly rdist)
535 * seem to depend on it.
539 if (dup2(inout[0], 0) < 0) /* stdin */
540 perror("dup2 stdin");
541 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
542 perror("dup2 stdout");
543 if (dup2(err[0], 2) < 0) /* stderr */
544 perror("dup2 stderr");
545 #endif /* USE_PIPES */
548 cray_init_job(s->pw); /* set up cray jid and tmpdir */
551 /* Do processing for the child (exec command etc). */
552 do_child(s, command);
556 signal(WJSIGNAL, cray_job_termination_handler);
560 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
563 packet_disconnect("fork failed: %.100s", strerror(errno));
565 /* Set interactive/non-interactive mode. */
566 packet_set_interactive(s->display != NULL);
568 /* We are the parent. Close the child sides of the pipes. */
574 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
576 /* Enter the interactive session. */
577 server_loop(pid, pin[1], pout[0], perr[0]);
578 /* server_loop has closed pin[1], pout[0], and perr[0]. */
580 #else /* USE_PIPES */
581 /* We are the parent. Close the child sides of the socket pairs. */
586 * Enter the interactive session. Note: server_loop must be able to
587 * handle the case that fdin and fdout are the same.
590 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
592 server_loop(pid, inout[1], inout[1], err[1]);
593 /* server_loop has closed inout[1] and err[1]. */
595 #endif /* USE_PIPES */
599 * This is called to fork and execute a command when we have a tty. This
600 * will call do_child from the child, and server_loop from the parent after
601 * setting up file descriptors, controlling tty, updating wtmp, utmp,
602 * lastlog, and other such operations.
605 do_exec_pty(Session *s, const char *command)
607 int fdout, ptyfd, ttyfd, ptymaster;
611 fatal("do_exec_pty: no session");
616 temporarily_use_uid(s->pw);
617 ssh_gssapi_storecreds();
622 do_pam_session(s->pw->pw_name, s->tty);
626 /* Fork the child. */
627 if ((pid = fork()) == 0) {
628 fatal_remove_all_cleanups();
630 /* Child. Reinitialize the log because the pid has changed. */
631 log_init(__progname, options.log_level, options.log_facility, log_stderr);
632 /* Close the master side of the pseudo tty. */
635 /* Make the pseudo tty our controlling tty. */
636 pty_make_controlling_tty(&ttyfd, s->tty);
638 /* Redirect stdin/stdout/stderr from the pseudo tty. */
639 if (dup2(ttyfd, 0) < 0)
640 error("dup2 stdin: %s", strerror(errno));
641 if (dup2(ttyfd, 1) < 0)
642 error("dup2 stdout: %s", strerror(errno));
643 if (dup2(ttyfd, 2) < 0)
644 error("dup2 stderr: %s", strerror(errno));
646 /* Close the extra descriptor for the pseudo tty. */
649 /* record login, etc. similar to login(1) */
651 if (!(options.use_login && command == NULL)) {
653 cray_init_job(s->pw); /* set up cray jid and tmpdir */
655 do_login(s, command);
657 # ifdef LOGIN_NEEDS_UTMPX
663 /* Do common processing for the child, such as execing the command. */
664 do_child(s, command);
668 signal(WJSIGNAL, cray_job_termination_handler);
672 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
675 packet_disconnect("fork failed: %.100s", strerror(errno));
678 /* Parent. Close the slave side of the pseudo tty. */
682 * Create another descriptor of the pty master side for use as the
683 * standard input. We could use the original descriptor, but this
684 * simplifies code in server_loop. The descriptor is bidirectional.
688 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
690 /* we keep a reference to the pty master */
691 ptymaster = dup(ptyfd);
693 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
694 s->ptymaster = ptymaster;
696 /* Enter interactive session. */
697 packet_set_interactive(1);
699 session_set_fds(s, ptyfd, fdout, -1);
701 server_loop(pid, ptyfd, fdout, -1);
702 /* server_loop _has_ closed ptyfd and fdout. */
706 #ifdef LOGIN_NEEDS_UTMPX
708 do_pre_login(Session *s)
711 struct sockaddr_storage from;
712 pid_t pid = getpid();
715 * Get IP address of client. If the connection is not a socket, let
716 * the address be 0.0.0.0.
718 memset(&from, 0, sizeof(from));
719 fromlen = sizeof(from);
720 if (packet_connection_is_on_socket()) {
721 if (getpeername(packet_get_connection_in(),
722 (struct sockaddr *) & from, &fromlen) < 0) {
723 debug("getpeername: %.100s", strerror(errno));
728 record_utmp_only(pid, s->tty, s->pw->pw_name,
729 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
730 (struct sockaddr *)&from, fromlen);
735 * This is called to fork and execute a command. If another command is
736 * to be forced, execute that instead.
739 do_exec(Session *s, const char *command)
741 #if defined(SESSION_HOOKS)
742 if (options.session_hooks_allow &&
743 (options.session_hooks_startup_cmd ||
744 options.session_hooks_shutdown_cmd))
752 "/tmp/ssh_env_%d%d%d",
756 } while (stat(env_file, &st)==0);
757 s->authctxt->session_env_file = strdup(env_file);
760 if (forced_command) {
761 original_command = command;
762 command = forced_command;
763 debug("Forced command '%.900s'", command);
767 do_exec_pty(s, command);
769 do_exec_no_pty(s, command);
771 original_command = NULL;
775 /* administrative, login(1)-like work */
777 do_login(Session *s, const char *command)
781 struct sockaddr_storage from;
782 struct passwd * pw = s->pw;
783 pid_t pid = getpid();
786 * Get IP address of client. If the connection is not a socket, let
787 * the address be 0.0.0.0.
789 memset(&from, 0, sizeof(from));
790 fromlen = sizeof(from);
791 if (packet_connection_is_on_socket()) {
792 if (getpeername(packet_get_connection_in(),
793 (struct sockaddr *) & from, &fromlen) < 0) {
794 debug("getpeername: %.100s", strerror(errno));
799 /* Record that there was a login on that tty from the remote host. */
801 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
802 get_remote_name_or_ip(utmp_len,
803 options.verify_reverse_mapping),
804 (struct sockaddr *)&from, fromlen);
808 * If password change is needed, do it now.
809 * This needs to occur before the ~/.hushlogin check.
811 if (is_pam_password_change_required()) {
812 print_pam_messages();
817 if (check_quietlogin(s, command))
821 if (!is_pam_password_change_required())
822 print_pam_messages();
824 #ifdef WITH_AIXAUTHENTICATE
825 if (aixloginmsg && *aixloginmsg)
826 printf("%s\n", aixloginmsg);
827 #endif /* WITH_AIXAUTHENTICATE */
829 #ifndef NO_SSH_LASTLOG
830 if (options.print_lastlog && s->last_login_time != 0) {
831 time_string = ctime(&s->last_login_time);
832 if (strchr(time_string, '\n'))
833 *strchr(time_string, '\n') = 0;
834 if (strcmp(s->hostname, "") == 0)
835 printf("Last login: %s\r\n", time_string);
837 printf("Last login: %s from %s\r\n", time_string,
840 #endif /* NO_SSH_LASTLOG */
846 * Display the message of the day.
854 if (options.print_motd) {
855 #ifdef HAVE_LOGIN_CAP
856 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
859 f = fopen("/etc/motd", "r");
862 while (fgets(buf, sizeof(buf), f))
871 * Check for quiet login, either .hushlogin or command given.
874 check_quietlogin(Session *s, const char *command)
877 struct passwd *pw = s->pw;
880 /* Return 1 if .hushlogin exists or a command given. */
883 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
884 #ifdef HAVE_LOGIN_CAP
885 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
888 if (stat(buf, &st) >= 0)
895 * Sets the value of the given variable in the environment. If the variable
896 * already exists, its value is overriden.
899 child_set_env(char ***envp, u_int *envsizep, const char *name,
906 * Find the slot where the value should be stored. If the variable
907 * already exists, we reuse the slot; otherwise we append a new slot
908 * at the end of the array, expanding if necessary.
911 namelen = strlen(name);
912 for (i = 0; env[i]; i++)
913 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
916 /* Reuse the slot. */
919 /* New variable. Expand if necessary. */
920 if (i >= (*envsizep) - 1) {
921 if (*envsizep >= 1000)
922 fatal("child_set_env: too many env vars,"
923 " skipping: %.100s", name);
925 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
927 /* Need to set the NULL pointer at end of array beyond the new slot. */
931 /* Allocate space and format the variable in the appropriate slot. */
932 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
933 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
937 * Reads environment variables from the given file and adds/overrides them
938 * into the environment. If the file does not exist, this does nothing.
939 * Otherwise, it must consist of empty lines, comments (line starts with '#')
940 * and assignments of the form name=value. No other forms are allowed.
943 read_environment_file(char ***env, u_int *envsize,
944 const char *filename)
951 f = fopen(filename, "r");
955 while (fgets(buf, sizeof(buf), f)) {
957 fatal("Too many lines in environment file %s", filename);
958 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
960 if (!*cp || *cp == '#' || *cp == '\n')
962 if (strchr(cp, '\n'))
963 *strchr(cp, '\n') = '\0';
964 value = strchr(cp, '=');
966 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
971 * Replace the equals sign by nul, and advance value to
976 child_set_env(env, envsize, cp, value);
982 #define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
984 typedef enum { no_op, execute, clear_env, restore_env,
985 read_env, save_or_rm_env } session_action_t;
987 static session_action_t action_order[2][5] = {
988 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
989 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
993 void execute_session_hook(char* prog, Authctxt *authctxt,
994 int startup, int save)
996 extern char **environ;
999 char **saved_env, **tmpenv;
1000 char *env_file = authctxt->session_env_file;
1005 switch (action_order[startup][i])
1018 authctxt->pw->pw_shell,
1021 debug("executing session hook: [%s]", buf);
1022 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
1024 /* flusing is recommended in the popen(3) man page, to avoid
1025 intermingling of output */
1028 if ((fp=popen(buf, "w")) == NULL)
1030 perror("Unable to run session hook");
1033 status = pclose(fp);
1034 debug2("session hook executed, status=%d", status);
1035 unsetenv(SSH_SESSION_ENV_FILE);
1040 saved_env = environ;
1041 tmpenv = (char**) malloc(sizeof(char*));
1047 environ = saved_env;
1052 if (status==0 && stat(env_file, &st)==0)
1056 debug("reading environment from %s", env_file);
1057 while (environ[envsize++]) ;
1058 read_environment_file(&environ, &envsize, env_file);
1062 case save_or_rm_env:
1063 if (status==0 && save)
1068 debug2("saving environment to %s", env_file);
1069 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1071 perror("Unable to save session hook info");
1073 while (environ[envcount])
1075 fprintf(fp, "%s\n", environ[envcount++]);
1080 else if (stat(env_file, &st)==0)
1082 debug2("removing environment file %s", env_file);
1092 void copy_environment(char **source, char ***env, u_int *envsize)
1094 char *var_name, *var_val;
1100 for(i = 0; source[i] != NULL; i++) {
1101 var_name = xstrdup(source[i]);
1102 if ((var_val = strstr(var_name, "=")) == NULL) {
1108 debug3("Copy environment: %s=%s", var_name, var_val);
1109 child_set_env(env, envsize, var_name, var_val);
1116 do_setup_env(Session *s, const char *shell)
1121 struct passwd *pw = s->pw;
1123 /* Initialize the environment. */
1125 env = xmalloc(envsize * sizeof(char *));
1130 * The Windows environment contains some setting which are
1131 * important for a running system. They must not be dropped.
1133 copy_environment(environ, &env, &envsize);
1137 /* Allow any GSSAPI methods that we've used to alter
1138 * the childs environment as they see fit
1140 ssh_gssapi_do_child(&env,&envsize);
1143 if (!options.use_login) {
1144 /* Set basic environment. */
1145 child_set_env(&env, &envsize, "USER", pw->pw_name);
1146 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1148 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1150 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1151 #ifdef HAVE_LOGIN_CAP
1152 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1153 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1155 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1156 #else /* HAVE_LOGIN_CAP */
1157 # ifndef HAVE_CYGWIN
1159 * There's no standard path on Windows. The path contains
1160 * important components pointing to the system directories,
1161 * needed for loading shared libraries. So the path better
1162 * remains intact here.
1164 # ifdef SUPERUSER_PATH
1165 child_set_env(&env, &envsize, "PATH",
1166 s->pw->pw_uid == 0 ? SUPERUSER_PATH :
1167 _PATH_STDPATH_WITH_SCP);
1169 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH_WITH_SCP);
1170 # endif /* SUPERUSER_PATH */
1171 if (getenv("LD_LIBRARY_PATH"))
1172 child_set_env(&env, &envsize, "LD_LIBRARY_PATH",
1173 getenv("LD_LIBRARY_PATH"));
1174 # endif /* HAVE_CYGWIN */
1175 #endif /* HAVE_LOGIN_CAP */
1177 snprintf(buf, sizeof buf, "%.200s/%.50s",
1178 _PATH_MAILDIR, pw->pw_name);
1179 child_set_env(&env, &envsize, "MAIL", buf);
1181 /* Normal systems set SHELL by default. */
1182 child_set_env(&env, &envsize, "SHELL", shell);
1185 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1188 if (getenv("GLOBUS_LOCATION"))
1189 child_set_env(&env, &envsize, "GLOBUS_LOCATION",
1190 getenv("GLOBUS_LOCATION"));
1193 /* Set custom environment options from RSA authentication. */
1194 if (!options.use_login) {
1195 while (custom_environment) {
1196 struct envstring *ce = custom_environment;
1199 for (i = 0; str[i] != '=' && str[i]; i++)
1201 if (str[i] == '=') {
1203 child_set_env(&env, &envsize, str, str + i + 1);
1205 custom_environment = ce->next;
1211 /* SSH_CLIENT deprecated */
1212 snprintf(buf, sizeof buf, "%.50s %d %d",
1213 get_remote_ipaddr(), get_remote_port(), get_local_port());
1214 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1216 laddr = get_local_ipaddr(packet_get_connection_in());
1217 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1218 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1220 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1223 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1225 child_set_env(&env, &envsize, "TERM", s->term);
1227 child_set_env(&env, &envsize, "DISPLAY", s->display);
1228 if (original_command)
1229 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1233 if (cray_tmpdir[0] != '\0')
1234 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1235 #endif /* _UNICOS */
1241 if ((cp = getenv("AUTHSTATE")) != NULL)
1242 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1243 if ((cp = getenv("KRB5CCNAME")) != NULL)
1244 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1245 read_environment_file(&env, &envsize, "/etc/environment");
1249 if (s->authctxt->krb4_ticket_file)
1250 child_set_env(&env, &envsize, "KRBTKFILE",
1251 s->authctxt->krb4_ticket_file);
1254 if (s->authctxt->krb5_ticket_file)
1255 child_set_env(&env, &envsize, "KRB5CCNAME",
1256 s->authctxt->krb5_ticket_file);
1260 * Pull in any environment variables that may have
1266 p = fetch_pam_environment();
1267 copy_environment(p, &env, &envsize);
1268 free_pam_environment(p);
1270 #endif /* USE_PAM */
1272 if (auth_sock_name != NULL)
1273 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1276 /* read $HOME/.ssh/environment. */
1277 if (options.permit_user_env && !options.use_login) {
1278 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1279 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1280 read_environment_file(&env, &envsize, buf);
1283 /* dump the environment */
1284 fprintf(stderr, "Environment:\n");
1285 for (i = 0; env[i]; i++)
1286 fprintf(stderr, " %.200s\n", env[i]);
1292 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1293 * first in this order).
1296 do_rc_files(Session *s, const char *shell)
1304 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1306 /* ignore _PATH_SSH_USER_RC for subsystems */
1307 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1308 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1309 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1311 fprintf(stderr, "Running %s\n", cmd);
1312 f = popen(cmd, "w");
1315 fprintf(f, "%s %s\n", s->auth_proto,
1319 fprintf(stderr, "Could not run %s\n",
1321 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1322 snprintf(cmd, sizeof cmd, "%s %s", _PATH_BSHELL,
1323 _PATH_SSH_SYSTEM_RC);
1325 fprintf(stderr, "Running %s\n", cmd);
1326 f = popen(cmd, "w");
1329 fprintf(f, "%s %s\n", s->auth_proto,
1333 fprintf(stderr, "Could not run %s\n",
1334 _PATH_SSH_SYSTEM_RC);
1335 } else if (do_xauth && options.xauth_location != NULL) {
1336 /* Add authority data to .Xauthority if appropriate. */
1339 "Running %.500s remove %.100s\n",
1340 options.xauth_location, s->auth_display);
1342 "%.500s add %.100s %.100s %.100s\n",
1343 options.xauth_location, s->auth_display,
1344 s->auth_proto, s->auth_data);
1346 snprintf(cmd, sizeof cmd, "%s -q -",
1347 options.xauth_location);
1348 f = popen(cmd, "w");
1350 fprintf(f, "remove %s\n",
1352 fprintf(f, "add %s %s %s\n",
1353 s->auth_display, s->auth_proto,
1357 fprintf(stderr, "Could not run %s\n",
1364 do_nologin(struct passwd *pw)
1369 #ifdef HAVE_LOGIN_CAP
1370 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1371 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1372 _PATH_NOLOGIN), "r");
1375 f = fopen(_PATH_NOLOGIN, "r");
1378 /* /etc/nologin exists. Print its contents and exit. */
1379 log("User %.100s not allowed because %s exists",
1380 pw->pw_name, _PATH_NOLOGIN);
1381 while (fgets(buf, sizeof(buf), f))
1389 /* Set login name, uid, gid, and groups. */
1391 do_setusercontext(struct passwd *pw)
1394 if (getuid() == 0 || geteuid() == 0)
1395 #endif /* HAVE_CYGWIN */
1398 #ifdef HAVE_SETPCRED
1399 setpcred(pw->pw_name);
1400 #endif /* HAVE_SETPCRED */
1401 #ifdef HAVE_LOGIN_CAP
1405 if (setusercontext(lc, pw, pw->pw_uid,
1406 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1407 perror("unable to set user context");
1411 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1412 /* Sets login uid for accounting */
1413 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1414 error("setluid: %s", strerror(errno));
1415 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1417 if (setlogin(pw->pw_name) < 0)
1418 error("setlogin failed: %s", strerror(errno));
1419 if (setgid(pw->pw_gid) < 0) {
1423 /* Initialize the group list. */
1424 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1425 perror("initgroups");
1431 * PAM credentials may take the form of supplementary groups.
1432 * These will have been wiped by the above initgroups() call.
1433 * Reestablish them here.
1436 # endif /* USE_PAM */
1437 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1438 irix_setusercontext(pw);
1439 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1443 /* Permanently switch to the desired uid. */
1444 permanently_set_uid(pw);
1451 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1452 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1456 launch_login(struct passwd *pw, const char *hostname)
1458 /* Launch login(1). */
1460 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1461 #ifdef xxxLOGIN_NEEDS_TERM
1462 (s->term ? s->term : "unknown"),
1463 #endif /* LOGIN_NEEDS_TERM */
1464 #ifdef LOGIN_NO_ENDOPT
1465 "-p", "-f", pw->pw_name, (char *)NULL);
1467 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1470 /* Login couldn't be executed, die. */
1477 * Performs common processing for the child, such as setting up the
1478 * environment, closing extra file descriptors, setting the user and group
1479 * ids, and executing the command or shell.
1482 do_child(Session *s, const char *command)
1484 extern char **environ;
1487 const char *shell, *shell0, *hostname = NULL;
1488 struct passwd *pw = s->pw;
1492 /* Default place to look for aklog. */
1494 #define KPROGDIR AKLOG_PATH
1496 #define KPROGDIR "/usr/bin/aklog"
1497 #endif /* AKLOG_PATH */
1501 #endif /* AFS_KRB5 */
1503 /* remove hostkey from the child's memory */
1504 destroy_sensitive_data();
1506 /* login(1) is only called if we execute the login shell */
1507 if (options.use_login && command != NULL)
1508 options.use_login = 0;
1511 cray_setup(pw->pw_uid, pw->pw_name, command);
1512 #endif /* _UNICOS */
1515 * Login(1) does this as well, and it needs uid 0 for the "-h"
1516 * switch, so we let login(1) to this for us.
1518 if (!options.use_login) {
1520 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1521 if (!check_quietlogin(s, command))
1523 #else /* HAVE_OSF_SIA */
1525 do_setusercontext(pw);
1526 #endif /* HAVE_OSF_SIA */
1530 * Get the shell from the password data. An empty shell field is
1531 * legal, and means /bin/sh.
1533 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1536 * Make sure $SHELL points to the shell from the password file,
1537 * even if shell is overridden from login.conf
1539 env = do_setup_env(s, shell);
1541 #ifdef HAVE_LOGIN_CAP
1542 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1545 /* we have to stash the hostname before we close our socket. */
1546 if (options.use_login)
1547 hostname = get_remote_name_or_ip(utmp_len,
1548 options.verify_reverse_mapping);
1550 * Close the connection descriptors; note that this is the child, and
1551 * the server will still have the socket open, and it is important
1552 * that we do not shutdown it. Note that the descriptors cannot be
1553 * closed before building the environment, as we call
1554 * get_remote_ipaddr there.
1556 if (packet_get_connection_in() == packet_get_connection_out())
1557 close(packet_get_connection_in());
1559 close(packet_get_connection_in());
1560 close(packet_get_connection_out());
1563 * Close all descriptors related to channels. They will still remain
1564 * open in the parent.
1566 /* XXX better use close-on-exec? -markus */
1567 channel_close_all();
1570 * Close any extra file descriptors. Note that there may still be
1571 * descriptors left by system functions. They will be closed later.
1576 * Close any extra open file descriptors so that we don\'t have them
1577 * hanging around in clients. Note that we want to do this after
1578 * initgroups, because at least on Solaris 2.3 it leaves file
1581 for (i = 3; i < 64; i++)
1585 * Must take new environment into use so that .ssh/rc,
1586 * /etc/ssh/sshrc and xauth are run in the proper environment.
1592 /* User has authenticated, and if a ticket was going to be
1593 * passed we would have it. KRB5CCNAME should already be set.
1594 * Now try to get an AFS token using aklog.
1596 if (k_hasafs()) { /* Do we have AFS? */
1598 aklog_path = xstrdup(KPROGDIR);
1601 * Make sure it exists before we try to run it
1603 if (stat(aklog_path, &st) == 0) {
1604 debug("Running %s to get afs token.",aklog_path);
1607 debug("%s does not exist.",aklog_path);
1612 #endif /* AFS_KRB5 */
1614 #ifdef SESSION_HOOKS
1615 if (options.session_hooks_allow &&
1616 options.session_hooks_startup_cmd)
1618 execute_session_hook(options.session_hooks_startup_cmd,
1621 options.session_hooks_shutdown_cmd != NULL);
1625 /* Try to get AFS tokens for the local cell. */
1629 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1630 krb_afslog(cell, 0);
1636 /* Change current directory to the user\'s home directory. */
1637 if (chdir(pw->pw_dir) < 0) {
1638 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1639 pw->pw_dir, strerror(errno));
1640 #ifdef HAVE_LOGIN_CAP
1641 if (login_getcapbool(lc, "requirehome", 0))
1646 if (!options.use_login)
1647 do_rc_files(s, shell);
1649 /* restore SIGPIPE for child */
1650 signal(SIGPIPE, SIG_DFL);
1652 if (options.use_login) {
1653 launch_login(pw, hostname);
1657 /* Get the last component of the shell name. */
1658 if ((shell0 = strrchr(shell, '/')) != NULL)
1664 * If we have no command, execute the shell. In this case, the shell
1665 * name to be passed in argv[0] is preceded by '-' to indicate that
1666 * this is a login shell.
1671 /* Start the shell. Set initial character to '-'. */
1674 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1675 >= sizeof(argv0) - 1) {
1681 /* Execute the shell. */
1684 execve(shell, argv, environ);
1686 /* Executing the shell failed. */
1691 * Execute the command using the user's shell. This uses the -c
1692 * option to execute the command.
1694 argv[0] = (char *) shell0;
1696 argv[2] = (char *) command;
1698 execve(shell, argv, environ);
1707 static int did_init = 0;
1709 debug("session_new: init");
1710 for (i = 0; i < MAX_SESSIONS; i++) {
1711 sessions[i].used = 0;
1715 for (i = 0; i < MAX_SESSIONS; i++) {
1716 Session *s = &sessions[i];
1718 memset(s, 0, sizeof(*s));
1724 debug("session_new: session %d", i);
1735 for (i = 0; i < MAX_SESSIONS; i++) {
1736 Session *s = &sessions[i];
1737 debug("dump: used %d session %d %p channel %d pid %ld",
1747 session_open(Authctxt *authctxt, int chanid)
1749 Session *s = session_new();
1750 debug("session_open: channel %d", chanid);
1752 error("no more sessions");
1755 s->authctxt = authctxt;
1756 s->pw = authctxt->pw;
1758 fatal("no user for session %d", s->self);
1759 debug("session_open: session %d: link with channel %d", s->self, chanid);
1765 session_by_tty(char *tty)
1768 for (i = 0; i < MAX_SESSIONS; i++) {
1769 Session *s = &sessions[i];
1770 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1771 debug("session_by_tty: session %d tty %s", i, tty);
1775 debug("session_by_tty: unknown tty %.100s", tty);
1781 session_by_channel(int id)
1784 for (i = 0; i < MAX_SESSIONS; i++) {
1785 Session *s = &sessions[i];
1786 if (s->used && s->chanid == id) {
1787 debug("session_by_channel: session %d channel %d", i, id);
1791 debug("session_by_channel: unknown channel %d", id);
1797 session_by_pid(pid_t pid)
1800 debug("session_by_pid: pid %ld", (long)pid);
1801 for (i = 0; i < MAX_SESSIONS; i++) {
1802 Session *s = &sessions[i];
1803 if (s->used && s->pid == pid)
1806 error("session_by_pid: unknown pid %ld", (long)pid);
1812 session_window_change_req(Session *s)
1814 s->col = packet_get_int();
1815 s->row = packet_get_int();
1816 s->xpixel = packet_get_int();
1817 s->ypixel = packet_get_int();
1819 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1824 session_pty_req(Session *s)
1830 debug("Allocating a pty not permitted for this authentication.");
1833 if (s->ttyfd != -1) {
1834 packet_disconnect("Protocol error: you already have a pty.");
1837 /* Get the time and hostname when the user last logged in. */
1838 if (options.print_lastlog) {
1839 s->hostname[0] = '\0';
1840 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1841 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1844 s->term = packet_get_string(&len);
1847 s->col = packet_get_int();
1848 s->row = packet_get_int();
1850 s->row = packet_get_int();
1851 s->col = packet_get_int();
1853 s->xpixel = packet_get_int();
1854 s->ypixel = packet_get_int();
1856 if (strcmp(s->term, "") == 0) {
1861 /* Allocate a pty and open it. */
1862 debug("Allocating pty.");
1863 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1869 error("session_pty_req: session %d alloc failed", s->self);
1872 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1874 /* for SSH1 the tty modes length is not given */
1876 n_bytes = packet_remaining();
1877 tty_parse_modes(s->ttyfd, &n_bytes);
1880 * Add a cleanup function to clear the utmp entry and record logout
1881 * time in case we call fatal() (e.g., the connection gets closed).
1883 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1885 pty_setowner(s->pw, s->tty);
1887 /* Set window size from the packet. */
1888 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1891 session_proctitle(s);
1896 session_subsystem_req(Session *s)
1901 char *cmd, *subsys = packet_get_string(&len);
1905 log("subsystem request for %.100s", subsys);
1907 for (i = 0; i < options.num_subsystems; i++) {
1908 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1909 cmd = options.subsystem_command[i];
1910 if (stat(cmd, &st) < 0) {
1911 error("subsystem: cannot stat %s: %s", cmd,
1915 debug("subsystem: exec() %s", cmd);
1916 s->is_subsystem = 1;
1924 log("subsystem request for %.100s failed, subsystem not found",
1932 session_x11_req(Session *s)
1936 s->single_connection = packet_get_char();
1937 s->auth_proto = packet_get_string(NULL);
1938 s->auth_data = packet_get_string(NULL);
1939 s->screen = packet_get_int();
1942 success = session_setup_x11fwd(s);
1944 xfree(s->auth_proto);
1945 xfree(s->auth_data);
1946 s->auth_proto = NULL;
1947 s->auth_data = NULL;
1953 session_shell_req(Session *s)
1961 session_exec_req(Session *s)
1964 char *command = packet_get_string(&len);
1966 do_exec(s, command);
1972 session_auth_agent_req(Session *s)
1974 static int called = 0;
1976 if (no_agent_forwarding_flag) {
1977 debug("session_auth_agent_req: no_agent_forwarding_flag");
1984 return auth_input_request_forwarding(s->pw);
1989 session_input_channel_req(Channel *c, const char *rtype)
1994 if ((s = session_by_channel(c->self)) == NULL) {
1995 log("session_input_channel_req: no session %d req %.100s",
1999 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2002 * a session is in LARVAL state until a shell, a command
2003 * or a subsystem is executed
2005 if (c->type == SSH_CHANNEL_LARVAL) {
2006 if (strcmp(rtype, "shell") == 0) {
2007 success = session_shell_req(s);
2008 } else if (strcmp(rtype, "exec") == 0) {
2009 success = session_exec_req(s);
2010 } else if (strcmp(rtype, "pty-req") == 0) {
2011 success = session_pty_req(s);
2012 } else if (strcmp(rtype, "x11-req") == 0) {
2013 success = session_x11_req(s);
2014 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2015 success = session_auth_agent_req(s);
2016 } else if (strcmp(rtype, "subsystem") == 0) {
2017 success = session_subsystem_req(s);
2020 if (strcmp(rtype, "window-change") == 0) {
2021 success = session_window_change_req(s);
2027 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2030 fatal("session_set_fds: called for proto != 2.0");
2032 * now that have a child and a pipe to the child,
2033 * we can activate our channel and register the fd's
2035 if (s->chanid == -1)
2036 fatal("no channel for session %d", s->self);
2037 channel_set_fds(s->chanid,
2039 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2041 CHAN_SES_WINDOW_DEFAULT);
2045 * Function to perform pty cleanup. Also called if we get aborted abnormally
2046 * (e.g., due to a dropped connection).
2049 session_pty_cleanup2(void *session)
2051 Session *s = session;
2054 error("session_pty_cleanup: no session");
2060 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2062 /* Record that the user has logged out. */
2064 record_logout(s->pid, s->tty, s->pw->pw_name);
2066 /* Release the pseudo-tty. */
2068 pty_release(s->tty);
2071 * Close the server side of the socket pairs. We must do this after
2072 * the pty cleanup, so that another process doesn't get this pty
2073 * while we're still cleaning up.
2075 if (close(s->ptymaster) < 0)
2076 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2078 /* unlink pty from session */
2083 session_pty_cleanup(void *session)
2085 PRIVSEP(session_pty_cleanup2(session));
2091 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2106 return "SIG@openssh.com";
2110 session_exit_message(Session *s, int status)
2114 if ((c = channel_lookup(s->chanid)) == NULL)
2115 fatal("session_exit_message: session %d: no channel %d",
2116 s->self, s->chanid);
2117 debug("session_exit_message: session %d channel %d pid %ld",
2118 s->self, s->chanid, (long)s->pid);
2120 if (WIFEXITED(status)) {
2121 channel_request_start(s->chanid, "exit-status", 0);
2122 packet_put_int(WEXITSTATUS(status));
2124 } else if (WIFSIGNALED(status)) {
2125 channel_request_start(s->chanid, "exit-signal", 0);
2126 packet_put_cstring(sig2name(WTERMSIG(status)));
2128 packet_put_char(WCOREDUMP(status));
2129 #else /* WCOREDUMP */
2131 #endif /* WCOREDUMP */
2132 packet_put_cstring("");
2133 packet_put_cstring("");
2136 /* Some weird exit cause. Just exit. */
2137 packet_disconnect("wait returned status %04x.", status);
2140 /* disconnect channel */
2141 debug("session_exit_message: release channel %d", s->chanid);
2142 channel_cancel_cleanup(s->chanid);
2144 * emulate a write failure with 'chan_write_failed', nobody will be
2145 * interested in data we write.
2146 * Note that we must not call 'chan_read_failed', since there could
2147 * be some more data waiting in the pipe.
2149 if (c->ostate != CHAN_OUTPUT_CLOSED)
2150 chan_write_failed(c);
2155 session_close(Session *s)
2157 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2158 if (s->ttyfd != -1) {
2159 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2160 session_pty_cleanup(s);
2166 if (s->auth_display)
2167 xfree(s->auth_display);
2169 xfree(s->auth_data);
2171 xfree(s->auth_proto);
2173 session_proctitle(s);
2177 session_close_by_pid(pid_t pid, int status)
2179 Session *s = session_by_pid(pid);
2181 debug("session_close_by_pid: no session for pid %ld",
2185 if (s->chanid != -1)
2186 session_exit_message(s, status);
2191 * this is called when a channel dies before
2192 * the session 'child' itself dies
2195 session_close_by_channel(int id, void *arg)
2197 Session *s = session_by_channel(id);
2199 debug("session_close_by_channel: no session for id %d", id);
2202 debug("session_close_by_channel: channel %d child %ld",
2205 debug("session_close_by_channel: channel %d: has child", id);
2207 * delay detach of session, but release pty, since
2208 * the fd's to the child are already closed
2210 if (s->ttyfd != -1) {
2211 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2212 session_pty_cleanup(s);
2216 /* detach by removing callback */
2217 channel_cancel_cleanup(s->chanid);
2223 session_destroy_all(void (*closefunc)(Session *))
2226 for (i = 0; i < MAX_SESSIONS; i++) {
2227 Session *s = &sessions[i];
2229 if (closefunc != NULL)
2238 session_tty_list(void)
2240 static char buf[1024];
2245 for (i = 0; i < MAX_SESSIONS; i++) {
2246 Session *s = &sessions[i];
2247 if (s->used && s->ttyfd != -1) {
2249 if (strncmp(s->tty, "/dev/", 5) != 0) {
2250 cp = strrchr(s->tty, '/');
2251 cp = (cp == NULL) ? s->tty : cp + 1;
2256 strlcat(buf, ",", sizeof buf);
2257 strlcat(buf, cp, sizeof buf);
2261 strlcpy(buf, "notty", sizeof buf);
2266 session_proctitle(Session *s)
2269 error("no user for session %d", s->self);
2271 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2275 session_setup_x11fwd(Session *s)
2278 char display[512], auth_display[512];
2279 char hostname[MAXHOSTNAMELEN];
2281 if (no_x11_forwarding_flag) {
2282 packet_send_debug("X11 forwarding disabled in user configuration file.");
2285 if (!options.x11_forwarding) {
2286 debug("X11 forwarding disabled in server configuration file.");
2289 if (!options.xauth_location ||
2290 (stat(options.xauth_location, &st) == -1)) {
2291 packet_send_debug("No xauth program; cannot forward with spoofing.");
2294 if (options.use_login) {
2295 packet_send_debug("X11 forwarding disabled; "
2296 "not compatible with UseLogin=yes.");
2299 if (s->display != NULL) {
2300 debug("X11 display already set.");
2303 if (x11_create_display_inet(options.x11_display_offset,
2304 options.x11_use_localhost, s->single_connection,
2305 &s->display_number) == -1) {
2306 debug("x11_create_display_inet failed.");
2310 /* Set up a suitable value for the DISPLAY variable. */
2311 if (gethostname(hostname, sizeof(hostname)) < 0)
2312 fatal("gethostname: %.100s", strerror(errno));
2314 * auth_display must be used as the displayname when the
2315 * authorization entry is added with xauth(1). This will be
2316 * different than the DISPLAY string for localhost displays.
2318 if (options.x11_use_localhost) {
2319 snprintf(display, sizeof display, "localhost:%u.%u",
2320 s->display_number, s->screen);
2321 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2322 s->display_number, s->screen);
2323 s->display = xstrdup(display);
2324 s->auth_display = xstrdup(auth_display);
2326 #ifdef IPADDR_IN_DISPLAY
2328 struct in_addr my_addr;
2330 he = gethostbyname(hostname);
2332 error("Can't get IP address for X11 DISPLAY.");
2333 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2336 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2337 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2338 s->display_number, s->screen);
2340 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2341 s->display_number, s->screen);
2343 s->display = xstrdup(display);
2344 s->auth_display = xstrdup(display);
2351 do_authenticated2(Authctxt *authctxt)
2353 server_loop2(authctxt);
2355 ssh_gssapi_cleanup_creds(NULL);