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.164 2003/09/18 08:49:45 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
59 #include "monitor_wrap.h"
67 Session *session_new(void);
68 void session_set_fds(Session *, int, int, int);
69 void session_pty_cleanup(void *);
70 void session_proctitle(Session *);
71 int session_setup_x11fwd(Session *);
72 void do_exec_pty(Session *, const char *);
73 void do_exec_no_pty(Session *, const char *);
74 void do_exec(Session *, const char *);
75 void do_login(Session *, const char *);
76 #ifdef LOGIN_NEEDS_UTMPX
77 static void do_pre_login(Session *s);
79 void do_child(Session *, const char *);
81 int check_quietlogin(Session *, const char *);
83 static void do_authenticated1(Authctxt *);
84 static void do_authenticated2(Authctxt *);
86 static int session_pty_req(Session *);
89 static void execute_session_hook(char* prog, Authctxt *authctxt,
90 int startup, int save);
94 extern ServerOptions options;
95 extern char *__progname;
96 extern int log_stderr;
97 extern int debug_flag;
98 extern u_int utmp_len;
99 extern int startup_pipe;
100 extern void destroy_sensitive_data(void);
101 extern Buffer loginmsg;
103 /* original command from peer. */
104 const char *original_command = NULL;
107 #define MAX_SESSIONS 10
108 Session sessions[MAX_SESSIONS];
110 #ifdef HAVE_LOGIN_CAP
114 /* Name and directory of socket for authentication agent forwarding. */
115 static char *auth_sock_name = NULL;
116 static char *auth_sock_dir = NULL;
118 /* removes the agent forwarding socket */
121 auth_sock_cleanup_proc(void *_pw)
123 struct passwd *pw = _pw;
125 if (auth_sock_name != NULL) {
126 temporarily_use_uid(pw);
127 unlink(auth_sock_name);
128 rmdir(auth_sock_dir);
129 auth_sock_name = NULL;
135 auth_input_request_forwarding(struct passwd * pw)
139 struct sockaddr_un sunaddr;
141 if (auth_sock_name != NULL) {
142 error("authentication forwarding requested twice.");
146 /* Temporarily drop privileged uid for mkdir/bind. */
147 temporarily_use_uid(pw);
149 /* Allocate a buffer for the socket name, and format the name. */
150 auth_sock_name = xmalloc(MAXPATHLEN);
151 auth_sock_dir = xmalloc(MAXPATHLEN);
152 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
154 /* Create private directory for socket */
155 if (mkdtemp(auth_sock_dir) == NULL) {
156 packet_send_debug("Agent forwarding disabled: "
157 "mkdtemp() failed: %.100s", strerror(errno));
159 xfree(auth_sock_name);
160 xfree(auth_sock_dir);
161 auth_sock_name = NULL;
162 auth_sock_dir = NULL;
165 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
166 auth_sock_dir, (long) getpid());
168 /* delete agent socket on fatal() */
169 fatal_add_cleanup(auth_sock_cleanup_proc, pw);
171 /* Create the socket. */
172 sock = socket(AF_UNIX, SOCK_STREAM, 0);
174 packet_disconnect("socket: %.100s", strerror(errno));
176 /* Bind it to the name. */
177 memset(&sunaddr, 0, sizeof(sunaddr));
178 sunaddr.sun_family = AF_UNIX;
179 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
181 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
182 packet_disconnect("bind: %.100s", strerror(errno));
184 /* Restore the privileged uid. */
187 /* Start listening on the socket. */
188 if (listen(sock, 5) < 0)
189 packet_disconnect("listen: %.100s", strerror(errno));
191 /* Allocate a channel for the authentication agent socket. */
192 nc = channel_new("auth socket",
193 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
194 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
195 0, "auth socket", 1);
196 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
202 do_authenticated(Authctxt *authctxt)
204 setproctitle("%s", authctxt->pw->pw_name);
207 * Cancel the alarm we set to limit the time taken for
211 if (startup_pipe != -1) {
216 /* setup the channel layer */
217 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
218 channel_permit_all_opens();
221 do_authenticated2(authctxt);
223 do_authenticated1(authctxt);
225 /* remove agent socket */
226 if (auth_sock_name != NULL)
227 auth_sock_cleanup_proc(authctxt->pw);
229 if (options.session_hooks_allow &&
230 options.session_hooks_shutdown_cmd)
232 execute_session_hook(options.session_hooks_shutdown_cmd,
234 /* startup = */ 0, /* save = */ 0);
236 if (authctxt->session_env_file)
238 free(authctxt->session_env_file);
243 if (options.kerberos_ticket_cleanup)
244 krb5_cleanup_proc(authctxt);
249 * Prepares for an interactive session. This is called after the user has
250 * been successfully authenticated. During this message exchange, pseudo
251 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
252 * are requested, etc.
255 do_authenticated1(Authctxt *authctxt)
259 int success, type, screen_flag;
260 int enable_compression_after_reply = 0;
261 u_int proto_len, data_len, dlen, compression_level = 0;
264 s->authctxt = authctxt;
265 s->pw = authctxt->pw;
268 * We stay in this loop until the client requests to execute a shell
274 /* Get a packet from the client. */
275 type = packet_read();
277 /* Process the packet. */
279 case SSH_CMSG_REQUEST_COMPRESSION:
280 compression_level = packet_get_int();
282 if (compression_level < 1 || compression_level > 9) {
283 packet_send_debug("Received illegal compression level %d.",
287 if (!options.compression) {
288 debug2("compression disabled");
291 /* Enable compression after we have responded with SUCCESS. */
292 enable_compression_after_reply = 1;
296 case SSH_CMSG_REQUEST_PTY:
297 success = session_pty_req(s);
300 case SSH_CMSG_X11_REQUEST_FORWARDING:
301 s->auth_proto = packet_get_string(&proto_len);
302 s->auth_data = packet_get_string(&data_len);
304 screen_flag = packet_get_protocol_flags() &
305 SSH_PROTOFLAG_SCREEN_NUMBER;
306 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
308 if (packet_remaining() == 4) {
310 debug2("Buggy client: "
311 "X11 screen flag missing");
312 s->screen = packet_get_int();
317 success = session_setup_x11fwd(s);
319 xfree(s->auth_proto);
321 s->auth_proto = NULL;
326 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
327 if (no_agent_forwarding_flag || compat13) {
328 debug("Authentication agent forwarding not permitted for this authentication.");
331 debug("Received authentication agent forwarding request.");
332 success = auth_input_request_forwarding(s->pw);
335 case SSH_CMSG_PORT_FORWARD_REQUEST:
336 if (no_port_forwarding_flag) {
337 debug("Port forwarding not permitted for this authentication.");
340 if (!options.allow_tcp_forwarding) {
341 debug("Port forwarding not permitted.");
344 debug("Received TCP/IP port forwarding request.");
345 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
349 case SSH_CMSG_MAX_PACKET_SIZE:
350 if (packet_set_maxsize(packet_get_int()) > 0)
354 case SSH_CMSG_EXEC_SHELL:
355 case SSH_CMSG_EXEC_CMD:
356 if (type == SSH_CMSG_EXEC_CMD) {
357 command = packet_get_string(&dlen);
358 debug("Exec command '%.500s'", command);
367 if (options.gss_cleanup_creds)
368 ssh_gssapi_cleanup_creds(NULL);
374 * Any unknown messages in this phase are ignored,
375 * and a failure message is returned.
377 logit("Unknown packet type received after authentication: %d", type);
379 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
383 /* Enable compression now that we have replied if appropriate. */
384 if (enable_compression_after_reply) {
385 enable_compression_after_reply = 0;
386 packet_start_compression(compression_level);
392 * This is called to fork and execute a command when we have no tty. This
393 * will call do_child from the child, and server_loop from the parent after
394 * setting up file descriptors and such.
397 do_exec_no_pty(Session *s, const char *command)
402 int pin[2], pout[2], perr[2];
403 /* Allocate pipes for communicating with the program. */
404 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
405 packet_disconnect("Could not create pipes: %.100s",
407 #else /* USE_PIPES */
408 int inout[2], err[2];
409 /* Uses socket pairs to communicate with the program. */
410 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
411 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
412 packet_disconnect("Could not create socket pairs: %.100s",
414 #endif /* USE_PIPES */
416 fatal("do_exec_no_pty: no session");
418 session_proctitle(s);
421 if (options.use_pam) {
423 if (is_pam_password_change_required())
424 packet_disconnect("Password change required but no "
429 /* Fork the child. */
430 if ((pid = fork()) == 0) {
431 fatal_remove_all_cleanups();
433 /* Child. Reinitialize the log since the pid has changed. */
434 log_init(__progname, options.log_level, options.log_facility, log_stderr);
437 * Create a new session and process group since the 4.4BSD
438 * setlogin() affects the entire process group.
441 error("setsid failed: %.100s", strerror(errno));
445 * Redirect stdin. We close the parent side of the socket
446 * pair, and make the child side the standard input.
449 if (dup2(pin[0], 0) < 0)
450 perror("dup2 stdin");
453 /* Redirect stdout. */
455 if (dup2(pout[1], 1) < 0)
456 perror("dup2 stdout");
459 /* Redirect stderr. */
461 if (dup2(perr[1], 2) < 0)
462 perror("dup2 stderr");
464 #else /* USE_PIPES */
466 * Redirect stdin, stdout, and stderr. Stdin and stdout will
467 * use the same socket, as some programs (particularly rdist)
468 * seem to depend on it.
472 if (dup2(inout[0], 0) < 0) /* stdin */
473 perror("dup2 stdin");
474 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
475 perror("dup2 stdout");
476 if (dup2(err[0], 2) < 0) /* stderr */
477 perror("dup2 stderr");
478 #endif /* USE_PIPES */
481 cray_init_job(s->pw); /* set up cray jid and tmpdir */
484 /* Do processing for the child (exec command etc). */
485 do_child(s, command);
489 signal(WJSIGNAL, cray_job_termination_handler);
493 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
496 packet_disconnect("fork failed: %.100s", strerror(errno));
498 /* Set interactive/non-interactive mode. */
499 packet_set_interactive(s->display != NULL);
501 /* We are the parent. Close the child sides of the pipes. */
507 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
509 /* Enter the interactive session. */
510 server_loop(pid, pin[1], pout[0], perr[0]);
511 /* server_loop has closed pin[1], pout[0], and perr[0]. */
513 #else /* USE_PIPES */
514 /* We are the parent. Close the child sides of the socket pairs. */
519 * Enter the interactive session. Note: server_loop must be able to
520 * handle the case that fdin and fdout are the same.
523 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
525 server_loop(pid, inout[1], inout[1], err[1]);
526 /* server_loop has closed inout[1] and err[1]. */
528 #endif /* USE_PIPES */
532 * This is called to fork and execute a command when we have a tty. This
533 * will call do_child from the child, and server_loop from the parent after
534 * setting up file descriptors, controlling tty, updating wtmp, utmp,
535 * lastlog, and other such operations.
538 do_exec_pty(Session *s, const char *command)
540 int fdout, ptyfd, ttyfd, ptymaster;
544 fatal("do_exec_pty: no session");
549 if (options.use_pam) {
550 do_pam_set_tty(s->tty);
555 /* Fork the child. */
556 if ((pid = fork()) == 0) {
557 fatal_remove_all_cleanups();
559 /* Child. Reinitialize the log because the pid has changed. */
560 log_init(__progname, options.log_level, options.log_facility, log_stderr);
561 /* Close the master side of the pseudo tty. */
564 /* Make the pseudo tty our controlling tty. */
565 pty_make_controlling_tty(&ttyfd, s->tty);
567 /* Redirect stdin/stdout/stderr from the pseudo tty. */
568 if (dup2(ttyfd, 0) < 0)
569 error("dup2 stdin: %s", strerror(errno));
570 if (dup2(ttyfd, 1) < 0)
571 error("dup2 stdout: %s", strerror(errno));
572 if (dup2(ttyfd, 2) < 0)
573 error("dup2 stderr: %s", strerror(errno));
575 /* Close the extra descriptor for the pseudo tty. */
578 /* record login, etc. similar to login(1) */
580 if (!(options.use_login && command == NULL)) {
582 cray_init_job(s->pw); /* set up cray jid and tmpdir */
584 do_login(s, command);
586 # ifdef LOGIN_NEEDS_UTMPX
592 /* Do common processing for the child, such as execing the command. */
593 do_child(s, command);
597 signal(WJSIGNAL, cray_job_termination_handler);
601 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
604 packet_disconnect("fork failed: %.100s", strerror(errno));
607 /* Parent. Close the slave side of the pseudo tty. */
611 * Create another descriptor of the pty master side for use as the
612 * standard input. We could use the original descriptor, but this
613 * simplifies code in server_loop. The descriptor is bidirectional.
617 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
619 /* we keep a reference to the pty master */
620 ptymaster = dup(ptyfd);
622 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
623 s->ptymaster = ptymaster;
625 /* Enter interactive session. */
626 packet_set_interactive(1);
628 session_set_fds(s, ptyfd, fdout, -1);
630 server_loop(pid, ptyfd, fdout, -1);
631 /* server_loop _has_ closed ptyfd and fdout. */
635 #ifdef LOGIN_NEEDS_UTMPX
637 do_pre_login(Session *s)
640 struct sockaddr_storage from;
641 pid_t pid = getpid();
644 * Get IP address of client. If the connection is not a socket, let
645 * the address be 0.0.0.0.
647 memset(&from, 0, sizeof(from));
648 fromlen = sizeof(from);
649 if (packet_connection_is_on_socket()) {
650 if (getpeername(packet_get_connection_in(),
651 (struct sockaddr *) & from, &fromlen) < 0) {
652 debug("getpeername: %.100s", strerror(errno));
657 record_utmp_only(pid, s->tty, s->pw->pw_name,
658 get_remote_name_or_ip(utmp_len, options.use_dns),
659 (struct sockaddr *)&from, fromlen);
664 * This is called to fork and execute a command. If another command is
665 * to be forced, execute that instead.
668 do_exec(Session *s, const char *command)
670 if (forced_command) {
671 original_command = command;
672 command = forced_command;
673 debug("Forced command '%.900s'", command);
676 #if defined(SESSION_HOOKS)
677 if (options.session_hooks_allow &&
678 (options.session_hooks_startup_cmd ||
679 options.session_hooks_shutdown_cmd))
687 "/tmp/ssh_env_%d%d%d",
691 } while (stat(env_file, &st)==0);
692 s->authctxt->session_env_file = strdup(env_file);
697 if (options.gss_authentication) {
698 temporarily_use_uid(s->pw);
699 ssh_gssapi_storecreds();
705 do_exec_pty(s, command);
707 do_exec_no_pty(s, command);
709 original_command = NULL;
713 /* administrative, login(1)-like work */
715 do_login(Session *s, const char *command)
719 struct sockaddr_storage from;
720 struct passwd * pw = s->pw;
721 pid_t pid = getpid();
724 * Get IP address of client. If the connection is not a socket, let
725 * the address be 0.0.0.0.
727 memset(&from, 0, sizeof(from));
728 fromlen = sizeof(from);
729 if (packet_connection_is_on_socket()) {
730 if (getpeername(packet_get_connection_in(),
731 (struct sockaddr *) & from, &fromlen) < 0) {
732 debug("getpeername: %.100s", strerror(errno));
737 /* Record that there was a login on that tty from the remote host. */
739 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
740 get_remote_name_or_ip(utmp_len,
742 (struct sockaddr *)&from, fromlen);
746 * If password change is needed, do it now.
747 * This needs to occur before the ~/.hushlogin check.
749 if (options.use_pam && is_pam_password_change_required()) {
750 print_pam_messages();
752 /* XXX - signal [net] parent to enable forwardings */
756 if (check_quietlogin(s, command))
760 if (options.use_pam && !is_pam_password_change_required())
761 print_pam_messages();
764 /* display post-login message */
765 if (buffer_len(&loginmsg) > 0) {
766 buffer_append(&loginmsg, "\0", 1);
767 printf("%s\n", (char *)buffer_ptr(&loginmsg));
769 buffer_free(&loginmsg);
771 #ifndef NO_SSH_LASTLOG
772 if (options.print_lastlog && s->last_login_time != 0) {
773 time_string = ctime(&s->last_login_time);
774 if (strchr(time_string, '\n'))
775 *strchr(time_string, '\n') = 0;
776 if (strcmp(s->hostname, "") == 0)
777 printf("Last login: %s\r\n", time_string);
779 printf("Last login: %s from %s\r\n", time_string,
782 #endif /* NO_SSH_LASTLOG */
788 * Display the message of the day.
796 if (options.print_motd) {
797 #ifdef HAVE_LOGIN_CAP
798 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
801 f = fopen("/etc/motd", "r");
804 while (fgets(buf, sizeof(buf), f))
813 * Check for quiet login, either .hushlogin or command given.
816 check_quietlogin(Session *s, const char *command)
819 struct passwd *pw = s->pw;
822 /* Return 1 if .hushlogin exists or a command given. */
825 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
826 #ifdef HAVE_LOGIN_CAP
827 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
830 if (stat(buf, &st) >= 0)
837 * Sets the value of the given variable in the environment. If the variable
838 * already exists, its value is overriden.
841 child_set_env(char ***envp, u_int *envsizep, const char *name,
849 * If we're passed an uninitialized list, allocate a single null
850 * entry before continuing.
852 if (*envp == NULL && *envsizep == 0) {
853 *envp = xmalloc(sizeof(char *));
859 * Find the slot where the value should be stored. If the variable
860 * already exists, we reuse the slot; otherwise we append a new slot
861 * at the end of the array, expanding if necessary.
864 namelen = strlen(name);
865 for (i = 0; env[i]; i++)
866 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
869 /* Reuse the slot. */
872 /* New variable. Expand if necessary. */
874 if (i >= envsize - 1) {
876 fatal("child_set_env: too many env vars");
878 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
881 /* Need to set the NULL pointer at end of array beyond the new slot. */
885 /* Allocate space and format the variable in the appropriate slot. */
886 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
887 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
891 * Reads environment variables from the given file and adds/overrides them
892 * into the environment. If the file does not exist, this does nothing.
893 * Otherwise, it must consist of empty lines, comments (line starts with '#')
894 * and assignments of the form name=value. No other forms are allowed.
897 read_environment_file(char ***env, u_int *envsize,
898 const char *filename)
905 f = fopen(filename, "r");
909 while (fgets(buf, sizeof(buf), f)) {
911 fatal("Too many lines in environment file %s", filename);
912 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
914 if (!*cp || *cp == '#' || *cp == '\n')
916 if (strchr(cp, '\n'))
917 *strchr(cp, '\n') = '\0';
918 value = strchr(cp, '=');
920 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
925 * Replace the equals sign by nul, and advance value to
930 child_set_env(env, envsize, cp, value);
936 #define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
938 typedef enum { no_op, execute, clear_env, restore_env,
939 read_env, save_or_rm_env } session_action_t;
941 static session_action_t action_order[2][5] = {
942 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
943 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
947 void execute_session_hook(char* prog, Authctxt *authctxt,
948 int startup, int save)
950 extern char **environ;
953 char **saved_env, **tmpenv;
954 char *env_file = authctxt->session_env_file;
959 switch (action_order[startup][i])
972 authctxt->pw->pw_shell,
975 debug("executing session hook: [%s]", buf);
976 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
978 /* flusing is recommended in the popen(3) man page, to avoid
979 intermingling of output */
982 if ((fp=popen(buf, "w")) == NULL)
984 perror("Unable to run session hook");
988 debug2("session hook executed, status=%d", status);
989 unsetenv(SSH_SESSION_ENV_FILE);
995 tmpenv = (char**) malloc(sizeof(char*));
1001 environ = saved_env;
1006 if (status==0 && stat(env_file, &st)==0)
1010 debug("reading environment from %s", env_file);
1011 while (environ[envsize++]) ;
1012 read_environment_file(&environ, &envsize, env_file);
1016 case save_or_rm_env:
1017 if (status==0 && save)
1022 debug2("saving environment to %s", env_file);
1023 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1025 perror("Unable to save session hook info");
1027 while (environ[envcount])
1029 fprintf(fp, "%s\n", environ[envcount++]);
1034 else if (stat(env_file, &st)==0)
1036 debug2("removing environment file %s", env_file);
1046 #ifdef HAVE_ETC_DEFAULT_LOGIN
1048 * Return named variable from specified environment, or NULL if not present.
1051 child_get_env(char **env, const char *name)
1057 for (i=0; env[i] != NULL; i++)
1058 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1059 return(env[i] + len + 1);
1064 * Read /etc/default/login.
1065 * We pick up the PATH (or SUPATH for root) and UMASK.
1068 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1070 char **tmpenv = NULL, *var;
1071 u_int i, tmpenvsize = 0;
1075 * We don't want to copy the whole file to the child's environment,
1076 * so we use a temporary environment and copy the variables we're
1079 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1085 var = child_get_env(tmpenv, "SUPATH");
1087 var = child_get_env(tmpenv, "PATH");
1089 child_set_env(env, envsize, "PATH", var);
1091 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1092 if (sscanf(var, "%5lo", &mask) == 1)
1095 for (i = 0; tmpenv[i] != NULL; i++)
1099 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1101 void copy_environment(char **source, char ***env, u_int *envsize)
1103 char *var_name, *var_val;
1109 for(i = 0; source[i] != NULL; i++) {
1110 var_name = xstrdup(source[i]);
1111 if ((var_val = strstr(var_name, "=")) == NULL) {
1117 debug3("Copy environment: %s=%s", var_name, var_val);
1118 child_set_env(env, envsize, var_name, var_val);
1125 do_setup_env(Session *s, const char *shell)
1129 char **env, *laddr, *path = NULL;
1130 struct passwd *pw = s->pw;
1132 /* Initialize the environment. */
1134 env = xmalloc(envsize * sizeof(char *));
1139 * The Windows environment contains some setting which are
1140 * important for a running system. They must not be dropped.
1142 copy_environment(environ, &env, &envsize);
1146 /* Allow any GSSAPI methods that we've used to alter
1147 * the childs environment as they see fit
1149 ssh_gssapi_do_child(&env, &envsize);
1152 if (!options.use_login) {
1153 /* Set basic environment. */
1154 child_set_env(&env, &envsize, "USER", pw->pw_name);
1155 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1157 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1159 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1160 #ifdef HAVE_LOGIN_CAP
1161 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1162 child_set_env(&env, &envsize, "PATH",
1163 _PATH_STDPATH_WITH_SCP);
1165 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1166 #else /* HAVE_LOGIN_CAP */
1167 # ifndef HAVE_CYGWIN
1169 * There's no standard path on Windows. The path contains
1170 * important components pointing to the system directories,
1171 * needed for loading shared libraries. So the path better
1172 * remains intact here.
1174 if (getenv("LD_LIBRARY_PATH"))
1175 child_set_env(&env, &envsize, "LD_LIBRARY_PATH",
1176 getenv("LD_LIBRARY_PATH"));
1177 # ifdef HAVE_ETC_DEFAULT_LOGIN
1178 read_etc_default_login(&env, &envsize, pw->pw_uid);
1179 path = child_get_env(env, "PATH");
1180 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1181 if (path == NULL || *path == '\0') {
1182 child_set_env(&env, &envsize, "PATH",
1183 s->pw->pw_uid == 0 ?
1184 SUPERUSER_PATH : _PATH_STDPATH_WITH_SCP);
1186 # endif /* HAVE_CYGWIN */
1187 #endif /* HAVE_LOGIN_CAP */
1189 snprintf(buf, sizeof buf, "%.200s/%.50s",
1190 _PATH_MAILDIR, pw->pw_name);
1191 child_set_env(&env, &envsize, "MAIL", buf);
1193 /* Normal systems set SHELL by default. */
1194 child_set_env(&env, &envsize, "SHELL", shell);
1197 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1200 if (getenv("GLOBUS_LOCATION"))
1201 child_set_env(&env, &envsize, "GLOBUS_LOCATION",
1202 getenv("GLOBUS_LOCATION"));
1205 /* Set custom environment options from RSA authentication. */
1206 if (!options.use_login) {
1207 while (custom_environment) {
1208 struct envstring *ce = custom_environment;
1211 for (i = 0; str[i] != '=' && str[i]; i++)
1213 if (str[i] == '=') {
1215 child_set_env(&env, &envsize, str, str + i + 1);
1217 custom_environment = ce->next;
1223 /* SSH_CLIENT deprecated */
1224 snprintf(buf, sizeof buf, "%.50s %d %d",
1225 get_remote_ipaddr(), get_remote_port(), get_local_port());
1226 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1228 laddr = get_local_ipaddr(packet_get_connection_in());
1229 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1230 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1232 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1235 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1237 child_set_env(&env, &envsize, "TERM", s->term);
1239 child_set_env(&env, &envsize, "DISPLAY", s->display);
1240 if (original_command)
1241 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1245 if (cray_tmpdir[0] != '\0')
1246 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1247 #endif /* _UNICOS */
1253 if ((cp = getenv("AUTHSTATE")) != NULL)
1254 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1255 if ((cp = getenv("KRB5CCNAME")) != NULL)
1256 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1257 read_environment_file(&env, &envsize, "/etc/environment");
1261 if (s->authctxt->krb5_ticket_file)
1262 child_set_env(&env, &envsize, "KRB5CCNAME",
1263 s->authctxt->krb5_ticket_file);
1267 * Pull in any environment variables that may have
1270 if (options.use_pam) {
1271 char **p = fetch_pam_environment();
1273 copy_environment(p, &env, &envsize);
1274 free_pam_environment(p);
1276 #endif /* USE_PAM */
1278 if (auth_sock_name != NULL)
1279 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1282 /* read $HOME/.ssh/environment. */
1283 if (options.permit_user_env && !options.use_login) {
1284 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1285 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1286 read_environment_file(&env, &envsize, buf);
1289 /* dump the environment */
1290 fprintf(stderr, "Environment:\n");
1291 for (i = 0; env[i]; i++)
1292 fprintf(stderr, " %.200s\n", env[i]);
1298 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1299 * first in this order).
1302 do_rc_files(Session *s, const char *shell)
1310 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1312 /* ignore _PATH_SSH_USER_RC for subsystems */
1313 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1314 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1315 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1317 fprintf(stderr, "Running %s\n", cmd);
1318 f = popen(cmd, "w");
1321 fprintf(f, "%s %s\n", s->auth_proto,
1325 fprintf(stderr, "Could not run %s\n",
1327 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1328 snprintf(cmd, sizeof cmd, "%s %s", _PATH_BSHELL,
1329 _PATH_SSH_SYSTEM_RC);
1331 fprintf(stderr, "Running %s\n", cmd);
1332 f = popen(cmd, "w");
1335 fprintf(f, "%s %s\n", s->auth_proto,
1339 fprintf(stderr, "Could not run %s\n",
1340 _PATH_SSH_SYSTEM_RC);
1341 } else if (do_xauth && options.xauth_location != NULL) {
1342 /* Add authority data to .Xauthority if appropriate. */
1345 "Running %.500s remove %.100s\n",
1346 options.xauth_location, s->auth_display);
1348 "%.500s add %.100s %.100s %.100s\n",
1349 options.xauth_location, s->auth_display,
1350 s->auth_proto, s->auth_data);
1352 snprintf(cmd, sizeof cmd, "%s -q -",
1353 options.xauth_location);
1354 f = popen(cmd, "w");
1356 fprintf(f, "remove %s\n",
1358 fprintf(f, "add %s %s %s\n",
1359 s->auth_display, s->auth_proto,
1363 fprintf(stderr, "Could not run %s\n",
1370 do_nologin(struct passwd *pw)
1375 #ifdef HAVE_LOGIN_CAP
1376 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1377 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1378 _PATH_NOLOGIN), "r");
1381 f = fopen(_PATH_NOLOGIN, "r");
1384 /* /etc/nologin exists. Print its contents and exit. */
1385 logit("User %.100s not allowed because %s exists",
1386 pw->pw_name, _PATH_NOLOGIN);
1387 while (fgets(buf, sizeof(buf), f))
1395 /* Set login name, uid, gid, and groups. */
1397 do_setusercontext(struct passwd *pw)
1400 if (getuid() == 0 || geteuid() == 0)
1401 #endif /* HAVE_CYGWIN */
1404 #ifdef HAVE_SETPCRED
1405 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1406 fatal("Failed to set process credentials");
1407 #endif /* HAVE_SETPCRED */
1408 #ifdef HAVE_LOGIN_CAP
1412 if (setusercontext(lc, pw, pw->pw_uid,
1413 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1414 perror("unable to set user context");
1418 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1419 /* Sets login uid for accounting */
1420 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1421 error("setluid: %s", strerror(errno));
1422 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1424 if (setlogin(pw->pw_name) < 0)
1425 error("setlogin failed: %s", strerror(errno));
1426 if (setgid(pw->pw_gid) < 0) {
1430 /* Initialize the group list. */
1431 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1432 perror("initgroups");
1438 * PAM credentials may take the form of supplementary groups.
1439 * These will have been wiped by the above initgroups() call.
1440 * Reestablish them here.
1442 if (options.use_pam) {
1446 # endif /* USE_PAM */
1447 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1448 irix_setusercontext(pw);
1449 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1453 /* Permanently switch to the desired uid. */
1454 permanently_set_uid(pw);
1461 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1462 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1466 launch_login(struct passwd *pw, const char *hostname)
1468 /* Launch login(1). */
1470 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1471 #ifdef xxxLOGIN_NEEDS_TERM
1472 (s->term ? s->term : "unknown"),
1473 #endif /* LOGIN_NEEDS_TERM */
1474 #ifdef LOGIN_NO_ENDOPT
1475 "-p", "-f", pw->pw_name, (char *)NULL);
1477 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1480 /* Login couldn't be executed, die. */
1487 * Performs common processing for the child, such as setting up the
1488 * environment, closing extra file descriptors, setting the user and group
1489 * ids, and executing the command or shell.
1492 do_child(Session *s, const char *command)
1494 extern char **environ;
1497 const char *shell, *shell0, *hostname = NULL;
1498 struct passwd *pw = s->pw;
1502 /* Default place to look for aklog. */
1504 #define KPROGDIR AKLOG_PATH
1506 #define KPROGDIR "/usr/bin/aklog"
1507 #endif /* AKLOG_PATH */
1511 #endif /* AFS_KRB5 */
1513 /* remove hostkey from the child's memory */
1514 destroy_sensitive_data();
1516 /* login(1) is only called if we execute the login shell */
1517 if (options.use_login && command != NULL)
1518 options.use_login = 0;
1521 cray_setup(pw->pw_uid, pw->pw_name, command);
1522 #endif /* _UNICOS */
1525 * Login(1) does this as well, and it needs uid 0 for the "-h"
1526 * switch, so we let login(1) to this for us.
1528 if (!options.use_login) {
1530 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1531 if (!check_quietlogin(s, command))
1533 #else /* HAVE_OSF_SIA */
1535 do_setusercontext(pw);
1536 #endif /* HAVE_OSF_SIA */
1540 * Get the shell from the password data. An empty shell field is
1541 * legal, and means /bin/sh.
1543 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1546 * Make sure $SHELL points to the shell from the password file,
1547 * even if shell is overridden from login.conf
1549 env = do_setup_env(s, shell);
1551 #ifdef HAVE_LOGIN_CAP
1552 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1555 /* we have to stash the hostname before we close our socket. */
1556 if (options.use_login)
1557 hostname = get_remote_name_or_ip(utmp_len,
1560 * Close the connection descriptors; note that this is the child, and
1561 * the server will still have the socket open, and it is important
1562 * that we do not shutdown it. Note that the descriptors cannot be
1563 * closed before building the environment, as we call
1564 * get_remote_ipaddr there.
1566 if (packet_get_connection_in() == packet_get_connection_out())
1567 close(packet_get_connection_in());
1569 close(packet_get_connection_in());
1570 close(packet_get_connection_out());
1573 * Close all descriptors related to channels. They will still remain
1574 * open in the parent.
1576 /* XXX better use close-on-exec? -markus */
1577 channel_close_all();
1580 * Close any extra file descriptors. Note that there may still be
1581 * descriptors left by system functions. They will be closed later.
1586 * Close any extra open file descriptors so that we don\'t have them
1587 * hanging around in clients. Note that we want to do this after
1588 * initgroups, because at least on Solaris 2.3 it leaves file
1591 for (i = 3; i < 64; i++)
1595 * Must take new environment into use so that .ssh/rc,
1596 * /etc/ssh/sshrc and xauth are run in the proper environment.
1602 /* User has authenticated, and if a ticket was going to be
1603 * passed we would have it. KRB5CCNAME should already be set.
1604 * Now try to get an AFS token using aklog.
1606 if (k_hasafs()) { /* Do we have AFS? */
1608 aklog_path = xstrdup(KPROGDIR);
1611 * Make sure it exists before we try to run it
1613 if (stat(aklog_path, &st) == 0) {
1614 debug("Running %s to get afs token.",aklog_path);
1617 debug("%s does not exist.",aklog_path);
1622 #endif /* AFS_KRB5 */
1624 #ifdef SESSION_HOOKS
1625 if (options.session_hooks_allow &&
1626 options.session_hooks_startup_cmd)
1628 execute_session_hook(options.session_hooks_startup_cmd,
1631 options.session_hooks_shutdown_cmd != NULL);
1635 /* Change current directory to the user\'s home directory. */
1636 if (chdir(pw->pw_dir) < 0) {
1637 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1638 pw->pw_dir, strerror(errno));
1639 #ifdef HAVE_LOGIN_CAP
1640 if (login_getcapbool(lc, "requirehome", 0))
1645 if (!options.use_login)
1646 do_rc_files(s, shell);
1648 /* restore SIGPIPE for child */
1649 signal(SIGPIPE, SIG_DFL);
1651 if (options.use_login) {
1652 launch_login(pw, hostname);
1656 /* Get the last component of the shell name. */
1657 if ((shell0 = strrchr(shell, '/')) != NULL)
1663 * If we have no command, execute the shell. In this case, the shell
1664 * name to be passed in argv[0] is preceded by '-' to indicate that
1665 * this is a login shell.
1670 /* Start the shell. Set initial character to '-'. */
1673 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1674 >= sizeof(argv0) - 1) {
1680 /* Execute the shell. */
1683 execve(shell, argv, environ);
1685 /* Executing the shell failed. */
1690 * Execute the command using the user's shell. This uses the -c
1691 * option to execute the command.
1693 argv[0] = (char *) shell0;
1695 argv[2] = (char *) command;
1697 execve(shell, argv, environ);
1706 static int did_init = 0;
1708 debug("session_new: init");
1709 for (i = 0; i < MAX_SESSIONS; i++) {
1710 sessions[i].used = 0;
1714 for (i = 0; i < MAX_SESSIONS; i++) {
1715 Session *s = &sessions[i];
1717 memset(s, 0, sizeof(*s));
1723 debug("session_new: session %d", i);
1734 for (i = 0; i < MAX_SESSIONS; i++) {
1735 Session *s = &sessions[i];
1736 debug("dump: used %d session %d %p channel %d pid %ld",
1746 session_open(Authctxt *authctxt, int chanid)
1748 Session *s = session_new();
1749 debug("session_open: channel %d", chanid);
1751 error("no more sessions");
1754 s->authctxt = authctxt;
1755 s->pw = authctxt->pw;
1757 fatal("no user for session %d", s->self);
1758 debug("session_open: session %d: link with channel %d", s->self, chanid);
1764 session_by_tty(char *tty)
1767 for (i = 0; i < MAX_SESSIONS; i++) {
1768 Session *s = &sessions[i];
1769 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1770 debug("session_by_tty: session %d tty %s", i, tty);
1774 debug("session_by_tty: unknown tty %.100s", tty);
1780 session_by_channel(int id)
1783 for (i = 0; i < MAX_SESSIONS; i++) {
1784 Session *s = &sessions[i];
1785 if (s->used && s->chanid == id) {
1786 debug("session_by_channel: session %d channel %d", i, id);
1790 debug("session_by_channel: unknown channel %d", id);
1796 session_by_pid(pid_t pid)
1799 debug("session_by_pid: pid %ld", (long)pid);
1800 for (i = 0; i < MAX_SESSIONS; i++) {
1801 Session *s = &sessions[i];
1802 if (s->used && s->pid == pid)
1805 error("session_by_pid: unknown pid %ld", (long)pid);
1811 session_window_change_req(Session *s)
1813 s->col = packet_get_int();
1814 s->row = packet_get_int();
1815 s->xpixel = packet_get_int();
1816 s->ypixel = packet_get_int();
1818 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1823 session_pty_req(Session *s)
1829 debug("Allocating a pty not permitted for this authentication.");
1832 if (s->ttyfd != -1) {
1833 packet_disconnect("Protocol error: you already have a pty.");
1836 /* Get the time and hostname when the user last logged in. */
1837 if (options.print_lastlog) {
1838 s->hostname[0] = '\0';
1839 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1840 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1843 s->term = packet_get_string(&len);
1846 s->col = packet_get_int();
1847 s->row = packet_get_int();
1849 s->row = packet_get_int();
1850 s->col = packet_get_int();
1852 s->xpixel = packet_get_int();
1853 s->ypixel = packet_get_int();
1855 if (strcmp(s->term, "") == 0) {
1860 /* Allocate a pty and open it. */
1861 debug("Allocating pty.");
1862 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1868 error("session_pty_req: session %d alloc failed", s->self);
1871 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1873 /* for SSH1 the tty modes length is not given */
1875 n_bytes = packet_remaining();
1876 tty_parse_modes(s->ttyfd, &n_bytes);
1879 * Add a cleanup function to clear the utmp entry and record logout
1880 * time in case we call fatal() (e.g., the connection gets closed).
1882 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1884 pty_setowner(s->pw, s->tty);
1886 /* Set window size from the packet. */
1887 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1890 session_proctitle(s);
1895 session_subsystem_req(Session *s)
1900 char *cmd, *subsys = packet_get_string(&len);
1904 logit("subsystem request for %.100s", subsys);
1906 for (i = 0; i < options.num_subsystems; i++) {
1907 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1908 cmd = options.subsystem_command[i];
1909 if (stat(cmd, &st) < 0) {
1910 error("subsystem: cannot stat %s: %s", cmd,
1914 debug("subsystem: exec() %s", cmd);
1915 s->is_subsystem = 1;
1923 logit("subsystem request for %.100s failed, subsystem not found",
1931 session_x11_req(Session *s)
1935 s->single_connection = packet_get_char();
1936 s->auth_proto = packet_get_string(NULL);
1937 s->auth_data = packet_get_string(NULL);
1938 s->screen = packet_get_int();
1941 success = session_setup_x11fwd(s);
1943 xfree(s->auth_proto);
1944 xfree(s->auth_data);
1945 s->auth_proto = NULL;
1946 s->auth_data = NULL;
1952 session_shell_req(Session *s)
1960 session_exec_req(Session *s)
1963 char *command = packet_get_string(&len);
1965 do_exec(s, command);
1971 session_break_req(Session *s)
1975 break_length = packet_get_int(); /* ignored */
1978 if (s->ttyfd == -1 ||
1979 tcsendbreak(s->ttyfd, 0) < 0)
1985 session_auth_agent_req(Session *s)
1987 static int called = 0;
1989 if (no_agent_forwarding_flag) {
1990 debug("session_auth_agent_req: no_agent_forwarding_flag");
1997 return auth_input_request_forwarding(s->pw);
2002 session_input_channel_req(Channel *c, const char *rtype)
2007 if ((s = session_by_channel(c->self)) == NULL) {
2008 logit("session_input_channel_req: no session %d req %.100s",
2012 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2015 * a session is in LARVAL state until a shell, a command
2016 * or a subsystem is executed
2018 if (c->type == SSH_CHANNEL_LARVAL) {
2019 if (strcmp(rtype, "shell") == 0) {
2020 success = session_shell_req(s);
2021 } else if (strcmp(rtype, "exec") == 0) {
2022 success = session_exec_req(s);
2023 } else if (strcmp(rtype, "pty-req") == 0) {
2024 success = session_pty_req(s);
2025 } else if (strcmp(rtype, "x11-req") == 0) {
2026 success = session_x11_req(s);
2027 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2028 success = session_auth_agent_req(s);
2029 } else if (strcmp(rtype, "subsystem") == 0) {
2030 success = session_subsystem_req(s);
2031 } else if (strcmp(rtype, "break") == 0) {
2032 success = session_break_req(s);
2035 if (strcmp(rtype, "window-change") == 0) {
2036 success = session_window_change_req(s);
2042 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2045 fatal("session_set_fds: called for proto != 2.0");
2047 * now that have a child and a pipe to the child,
2048 * we can activate our channel and register the fd's
2050 if (s->chanid == -1)
2051 fatal("no channel for session %d", s->self);
2052 channel_set_fds(s->chanid,
2054 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2056 CHAN_SES_WINDOW_DEFAULT);
2060 * Function to perform pty cleanup. Also called if we get aborted abnormally
2061 * (e.g., due to a dropped connection).
2064 session_pty_cleanup2(void *session)
2066 Session *s = session;
2069 error("session_pty_cleanup: no session");
2075 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2077 /* Record that the user has logged out. */
2079 record_logout(s->pid, s->tty, s->pw->pw_name);
2081 /* Release the pseudo-tty. */
2083 pty_release(s->tty);
2086 * Close the server side of the socket pairs. We must do this after
2087 * the pty cleanup, so that another process doesn't get this pty
2088 * while we're still cleaning up.
2090 if (close(s->ptymaster) < 0)
2091 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2093 /* unlink pty from session */
2098 session_pty_cleanup(void *session)
2100 PRIVSEP(session_pty_cleanup2(session));
2106 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2121 return "SIG@openssh.com";
2125 session_exit_message(Session *s, int status)
2129 if ((c = channel_lookup(s->chanid)) == NULL)
2130 fatal("session_exit_message: session %d: no channel %d",
2131 s->self, s->chanid);
2132 debug("session_exit_message: session %d channel %d pid %ld",
2133 s->self, s->chanid, (long)s->pid);
2135 if (WIFEXITED(status)) {
2136 channel_request_start(s->chanid, "exit-status", 0);
2137 packet_put_int(WEXITSTATUS(status));
2139 } else if (WIFSIGNALED(status)) {
2140 channel_request_start(s->chanid, "exit-signal", 0);
2141 packet_put_cstring(sig2name(WTERMSIG(status)));
2143 packet_put_char(WCOREDUMP(status));
2144 #else /* WCOREDUMP */
2146 #endif /* WCOREDUMP */
2147 packet_put_cstring("");
2148 packet_put_cstring("");
2151 /* Some weird exit cause. Just exit. */
2152 packet_disconnect("wait returned status %04x.", status);
2155 /* disconnect channel */
2156 debug("session_exit_message: release channel %d", s->chanid);
2157 channel_cancel_cleanup(s->chanid);
2159 * emulate a write failure with 'chan_write_failed', nobody will be
2160 * interested in data we write.
2161 * Note that we must not call 'chan_read_failed', since there could
2162 * be some more data waiting in the pipe.
2164 if (c->ostate != CHAN_OUTPUT_CLOSED)
2165 chan_write_failed(c);
2170 session_close(Session *s)
2172 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2173 if (s->ttyfd != -1) {
2174 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2175 session_pty_cleanup(s);
2181 if (s->auth_display)
2182 xfree(s->auth_display);
2184 xfree(s->auth_data);
2186 xfree(s->auth_proto);
2188 session_proctitle(s);
2192 session_close_by_pid(pid_t pid, int status)
2194 Session *s = session_by_pid(pid);
2196 debug("session_close_by_pid: no session for pid %ld",
2200 if (s->chanid != -1)
2201 session_exit_message(s, status);
2206 * this is called when a channel dies before
2207 * the session 'child' itself dies
2210 session_close_by_channel(int id, void *arg)
2212 Session *s = session_by_channel(id);
2214 debug("session_close_by_channel: no session for id %d", id);
2217 debug("session_close_by_channel: channel %d child %ld",
2220 debug("session_close_by_channel: channel %d: has child", id);
2222 * delay detach of session, but release pty, since
2223 * the fd's to the child are already closed
2225 if (s->ttyfd != -1) {
2226 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2227 session_pty_cleanup(s);
2231 /* detach by removing callback */
2232 channel_cancel_cleanup(s->chanid);
2238 session_destroy_all(void (*closefunc)(Session *))
2241 for (i = 0; i < MAX_SESSIONS; i++) {
2242 Session *s = &sessions[i];
2244 if (closefunc != NULL)
2253 session_tty_list(void)
2255 static char buf[1024];
2260 for (i = 0; i < MAX_SESSIONS; i++) {
2261 Session *s = &sessions[i];
2262 if (s->used && s->ttyfd != -1) {
2264 if (strncmp(s->tty, "/dev/", 5) != 0) {
2265 cp = strrchr(s->tty, '/');
2266 cp = (cp == NULL) ? s->tty : cp + 1;
2271 strlcat(buf, ",", sizeof buf);
2272 strlcat(buf, cp, sizeof buf);
2276 strlcpy(buf, "notty", sizeof buf);
2281 session_proctitle(Session *s)
2284 error("no user for session %d", s->self);
2286 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2290 session_setup_x11fwd(Session *s)
2293 char display[512], auth_display[512];
2294 char hostname[MAXHOSTNAMELEN];
2296 if (no_x11_forwarding_flag) {
2297 packet_send_debug("X11 forwarding disabled in user configuration file.");
2300 if (!options.x11_forwarding) {
2301 debug("X11 forwarding disabled in server configuration file.");
2304 if (!options.xauth_location ||
2305 (stat(options.xauth_location, &st) == -1)) {
2306 packet_send_debug("No xauth program; cannot forward with spoofing.");
2309 if (options.use_login) {
2310 packet_send_debug("X11 forwarding disabled; "
2311 "not compatible with UseLogin=yes.");
2314 if (s->display != NULL) {
2315 debug("X11 display already set.");
2318 if (x11_create_display_inet(options.x11_display_offset,
2319 options.x11_use_localhost, s->single_connection,
2320 &s->display_number) == -1) {
2321 debug("x11_create_display_inet failed.");
2325 /* Set up a suitable value for the DISPLAY variable. */
2326 if (gethostname(hostname, sizeof(hostname)) < 0)
2327 fatal("gethostname: %.100s", strerror(errno));
2329 * auth_display must be used as the displayname when the
2330 * authorization entry is added with xauth(1). This will be
2331 * different than the DISPLAY string for localhost displays.
2333 if (options.x11_use_localhost) {
2334 snprintf(display, sizeof display, "localhost:%u.%u",
2335 s->display_number, s->screen);
2336 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2337 s->display_number, s->screen);
2338 s->display = xstrdup(display);
2339 s->auth_display = xstrdup(auth_display);
2341 #ifdef IPADDR_IN_DISPLAY
2343 struct in_addr my_addr;
2345 he = gethostbyname(hostname);
2347 error("Can't get IP address for X11 DISPLAY.");
2348 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2351 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2352 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2353 s->display_number, s->screen);
2355 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2356 s->display_number, s->screen);
2358 s->display = xstrdup(display);
2359 s->auth_display = xstrdup(display);
2366 do_authenticated2(Authctxt *authctxt)
2368 server_loop2(authctxt);
2370 if (options.gss_cleanup_creds)
2371 ssh_gssapi_cleanup_creds(NULL);