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", _PATH_STDPATH);
1164 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1165 #else /* HAVE_LOGIN_CAP */
1166 # ifndef HAVE_CYGWIN
1168 * There's no standard path on Windows. The path contains
1169 * important components pointing to the system directories,
1170 * needed for loading shared libraries. So the path better
1171 * remains intact here.
1173 if (getenv("LD_LIBRARY_PATH"))
1174 child_set_env(&env, &envsize, "LD_LIBRARY_PATH",
1175 getenv("LD_LIBRARY_PATH"));
1176 # ifdef HAVE_ETC_DEFAULT_LOGIN
1177 read_etc_default_login(&env, &envsize, pw->pw_uid);
1178 path = child_get_env(env, "PATH");
1179 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1180 if (path == NULL || *path == '\0') {
1181 child_set_env(&env, &envsize, "PATH",
1182 s->pw->pw_uid == 0 ?
1183 SUPERUSER_PATH : _PATH_STDPATH);
1185 # endif /* HAVE_CYGWIN */
1186 #endif /* HAVE_LOGIN_CAP */
1188 snprintf(buf, sizeof buf, "%.200s/%.50s",
1189 _PATH_MAILDIR, pw->pw_name);
1190 child_set_env(&env, &envsize, "MAIL", buf);
1192 /* Normal systems set SHELL by default. */
1193 child_set_env(&env, &envsize, "SHELL", shell);
1196 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1198 /* Set custom environment options from RSA authentication. */
1199 if (!options.use_login) {
1200 while (custom_environment) {
1201 struct envstring *ce = custom_environment;
1204 for (i = 0; str[i] != '=' && str[i]; i++)
1206 if (str[i] == '=') {
1208 child_set_env(&env, &envsize, str, str + i + 1);
1210 custom_environment = ce->next;
1216 /* SSH_CLIENT deprecated */
1217 snprintf(buf, sizeof buf, "%.50s %d %d",
1218 get_remote_ipaddr(), get_remote_port(), get_local_port());
1219 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1221 laddr = get_local_ipaddr(packet_get_connection_in());
1222 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1223 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1225 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1228 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1230 child_set_env(&env, &envsize, "TERM", s->term);
1232 child_set_env(&env, &envsize, "DISPLAY", s->display);
1233 if (original_command)
1234 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1238 if (cray_tmpdir[0] != '\0')
1239 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1240 #endif /* _UNICOS */
1246 if ((cp = getenv("AUTHSTATE")) != NULL)
1247 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1248 if ((cp = getenv("KRB5CCNAME")) != NULL)
1249 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1250 read_environment_file(&env, &envsize, "/etc/environment");
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
1263 if (options.use_pam) {
1264 char **p = fetch_pam_environment();
1266 copy_environment(p, &env, &envsize);
1267 free_pam_environment(p);
1269 #endif /* USE_PAM */
1271 if (auth_sock_name != NULL)
1272 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1275 /* read $HOME/.ssh/environment. */
1276 if (options.permit_user_env && !options.use_login) {
1277 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1278 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1279 read_environment_file(&env, &envsize, buf);
1282 /* dump the environment */
1283 fprintf(stderr, "Environment:\n");
1284 for (i = 0; env[i]; i++)
1285 fprintf(stderr, " %.200s\n", env[i]);
1291 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1292 * first in this order).
1295 do_rc_files(Session *s, const char *shell)
1303 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1305 /* ignore _PATH_SSH_USER_RC for subsystems */
1306 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1307 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1308 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1310 fprintf(stderr, "Running %s\n", cmd);
1311 f = popen(cmd, "w");
1314 fprintf(f, "%s %s\n", s->auth_proto,
1318 fprintf(stderr, "Could not run %s\n",
1320 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1322 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1323 _PATH_SSH_SYSTEM_RC);
1324 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1327 fprintf(f, "%s %s\n", s->auth_proto,
1331 fprintf(stderr, "Could not run %s\n",
1332 _PATH_SSH_SYSTEM_RC);
1333 } else if (do_xauth && options.xauth_location != NULL) {
1334 /* Add authority data to .Xauthority if appropriate. */
1337 "Running %.500s remove %.100s\n",
1338 options.xauth_location, s->auth_display);
1340 "%.500s add %.100s %.100s %.100s\n",
1341 options.xauth_location, s->auth_display,
1342 s->auth_proto, s->auth_data);
1344 snprintf(cmd, sizeof cmd, "%s -q -",
1345 options.xauth_location);
1346 f = popen(cmd, "w");
1348 fprintf(f, "remove %s\n",
1350 fprintf(f, "add %s %s %s\n",
1351 s->auth_display, s->auth_proto,
1355 fprintf(stderr, "Could not run %s\n",
1362 do_nologin(struct passwd *pw)
1367 #ifdef HAVE_LOGIN_CAP
1368 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1369 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1370 _PATH_NOLOGIN), "r");
1373 f = fopen(_PATH_NOLOGIN, "r");
1376 /* /etc/nologin exists. Print its contents and exit. */
1377 logit("User %.100s not allowed because %s exists",
1378 pw->pw_name, _PATH_NOLOGIN);
1379 while (fgets(buf, sizeof(buf), f))
1387 /* Set login name, uid, gid, and groups. */
1389 do_setusercontext(struct passwd *pw)
1392 if (getuid() == 0 || geteuid() == 0)
1393 #endif /* HAVE_CYGWIN */
1396 #ifdef HAVE_SETPCRED
1397 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1398 fatal("Failed to set process credentials");
1399 #endif /* HAVE_SETPCRED */
1400 #ifdef HAVE_LOGIN_CAP
1404 if (setusercontext(lc, pw, pw->pw_uid,
1405 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1406 perror("unable to set user context");
1410 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1411 /* Sets login uid for accounting */
1412 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1413 error("setluid: %s", strerror(errno));
1414 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1416 if (setlogin(pw->pw_name) < 0)
1417 error("setlogin failed: %s", strerror(errno));
1418 if (setgid(pw->pw_gid) < 0) {
1422 /* Initialize the group list. */
1423 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1424 perror("initgroups");
1430 * PAM credentials may take the form of supplementary groups.
1431 * These will have been wiped by the above initgroups() call.
1432 * Reestablish them here.
1434 if (options.use_pam) {
1438 # endif /* USE_PAM */
1439 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1440 irix_setusercontext(pw);
1441 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1445 /* Permanently switch to the desired uid. */
1446 permanently_set_uid(pw);
1453 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1454 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1458 launch_login(struct passwd *pw, const char *hostname)
1460 /* Launch login(1). */
1462 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1463 #ifdef xxxLOGIN_NEEDS_TERM
1464 (s->term ? s->term : "unknown"),
1465 #endif /* LOGIN_NEEDS_TERM */
1466 #ifdef LOGIN_NO_ENDOPT
1467 "-p", "-f", pw->pw_name, (char *)NULL);
1469 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1472 /* Login couldn't be executed, die. */
1479 * Performs common processing for the child, such as setting up the
1480 * environment, closing extra file descriptors, setting the user and group
1481 * ids, and executing the command or shell.
1484 do_child(Session *s, const char *command)
1486 extern char **environ;
1489 const char *shell, *shell0, *hostname = NULL;
1490 struct passwd *pw = s->pw;
1494 /* Default place to look for aklog. */
1496 #define KPROGDIR AKLOG_PATH
1498 #define KPROGDIR "/usr/bin/aklog"
1499 #endif /* AKLOG_PATH */
1503 #endif /* AFS_KRB5 */
1505 /* remove hostkey from the child's memory */
1506 destroy_sensitive_data();
1508 /* login(1) is only called if we execute the login shell */
1509 if (options.use_login && command != NULL)
1510 options.use_login = 0;
1513 cray_setup(pw->pw_uid, pw->pw_name, command);
1514 #endif /* _UNICOS */
1517 * Login(1) does this as well, and it needs uid 0 for the "-h"
1518 * switch, so we let login(1) to this for us.
1520 if (!options.use_login) {
1522 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1523 if (!check_quietlogin(s, command))
1525 #else /* HAVE_OSF_SIA */
1527 do_setusercontext(pw);
1528 #endif /* HAVE_OSF_SIA */
1532 * Get the shell from the password data. An empty shell field is
1533 * legal, and means /bin/sh.
1535 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1538 * Make sure $SHELL points to the shell from the password file,
1539 * even if shell is overridden from login.conf
1541 env = do_setup_env(s, shell);
1543 #ifdef HAVE_LOGIN_CAP
1544 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1547 /* we have to stash the hostname before we close our socket. */
1548 if (options.use_login)
1549 hostname = get_remote_name_or_ip(utmp_len,
1552 * Close the connection descriptors; note that this is the child, and
1553 * the server will still have the socket open, and it is important
1554 * that we do not shutdown it. Note that the descriptors cannot be
1555 * closed before building the environment, as we call
1556 * get_remote_ipaddr there.
1558 if (packet_get_connection_in() == packet_get_connection_out())
1559 close(packet_get_connection_in());
1561 close(packet_get_connection_in());
1562 close(packet_get_connection_out());
1565 * Close all descriptors related to channels. They will still remain
1566 * open in the parent.
1568 /* XXX better use close-on-exec? -markus */
1569 channel_close_all();
1572 * Close any extra file descriptors. Note that there may still be
1573 * descriptors left by system functions. They will be closed later.
1578 * Close any extra open file descriptors so that we don\'t have them
1579 * hanging around in clients. Note that we want to do this after
1580 * initgroups, because at least on Solaris 2.3 it leaves file
1583 for (i = 3; i < 64; i++)
1587 * Must take new environment into use so that .ssh/rc,
1588 * /etc/ssh/sshrc and xauth are run in the proper environment.
1594 /* User has authenticated, and if a ticket was going to be
1595 * passed we would have it. KRB5CCNAME should already be set.
1596 * Now try to get an AFS token using aklog.
1598 if (k_hasafs()) { /* Do we have AFS? */
1600 aklog_path = xstrdup(KPROGDIR);
1603 * Make sure it exists before we try to run it
1605 if (stat(aklog_path, &st) == 0) {
1606 debug("Running %s to get afs token.",aklog_path);
1609 debug("%s does not exist.",aklog_path);
1614 #endif /* AFS_KRB5 */
1616 #ifdef SESSION_HOOKS
1617 if (options.session_hooks_allow &&
1618 options.session_hooks_startup_cmd)
1620 execute_session_hook(options.session_hooks_startup_cmd,
1623 options.session_hooks_shutdown_cmd != NULL);
1627 /* Change current directory to the user\'s home directory. */
1628 if (chdir(pw->pw_dir) < 0) {
1629 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1630 pw->pw_dir, strerror(errno));
1631 #ifdef HAVE_LOGIN_CAP
1632 if (login_getcapbool(lc, "requirehome", 0))
1637 if (!options.use_login)
1638 do_rc_files(s, shell);
1640 /* restore SIGPIPE for child */
1641 signal(SIGPIPE, SIG_DFL);
1643 if (options.use_login) {
1644 launch_login(pw, hostname);
1648 /* Get the last component of the shell name. */
1649 if ((shell0 = strrchr(shell, '/')) != NULL)
1655 * If we have no command, execute the shell. In this case, the shell
1656 * name to be passed in argv[0] is preceded by '-' to indicate that
1657 * this is a login shell.
1662 /* Start the shell. Set initial character to '-'. */
1665 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1666 >= sizeof(argv0) - 1) {
1672 /* Execute the shell. */
1675 execve(shell, argv, environ);
1677 /* Executing the shell failed. */
1682 * Execute the command using the user's shell. This uses the -c
1683 * option to execute the command.
1685 argv[0] = (char *) shell0;
1687 argv[2] = (char *) command;
1689 execve(shell, argv, environ);
1698 static int did_init = 0;
1700 debug("session_new: init");
1701 for (i = 0; i < MAX_SESSIONS; i++) {
1702 sessions[i].used = 0;
1706 for (i = 0; i < MAX_SESSIONS; i++) {
1707 Session *s = &sessions[i];
1709 memset(s, 0, sizeof(*s));
1715 debug("session_new: session %d", i);
1726 for (i = 0; i < MAX_SESSIONS; i++) {
1727 Session *s = &sessions[i];
1728 debug("dump: used %d session %d %p channel %d pid %ld",
1738 session_open(Authctxt *authctxt, int chanid)
1740 Session *s = session_new();
1741 debug("session_open: channel %d", chanid);
1743 error("no more sessions");
1746 s->authctxt = authctxt;
1747 s->pw = authctxt->pw;
1749 fatal("no user for session %d", s->self);
1750 debug("session_open: session %d: link with channel %d", s->self, chanid);
1756 session_by_tty(char *tty)
1759 for (i = 0; i < MAX_SESSIONS; i++) {
1760 Session *s = &sessions[i];
1761 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1762 debug("session_by_tty: session %d tty %s", i, tty);
1766 debug("session_by_tty: unknown tty %.100s", tty);
1772 session_by_channel(int id)
1775 for (i = 0; i < MAX_SESSIONS; i++) {
1776 Session *s = &sessions[i];
1777 if (s->used && s->chanid == id) {
1778 debug("session_by_channel: session %d channel %d", i, id);
1782 debug("session_by_channel: unknown channel %d", id);
1788 session_by_pid(pid_t pid)
1791 debug("session_by_pid: pid %ld", (long)pid);
1792 for (i = 0; i < MAX_SESSIONS; i++) {
1793 Session *s = &sessions[i];
1794 if (s->used && s->pid == pid)
1797 error("session_by_pid: unknown pid %ld", (long)pid);
1803 session_window_change_req(Session *s)
1805 s->col = packet_get_int();
1806 s->row = packet_get_int();
1807 s->xpixel = packet_get_int();
1808 s->ypixel = packet_get_int();
1810 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1815 session_pty_req(Session *s)
1821 debug("Allocating a pty not permitted for this authentication.");
1824 if (s->ttyfd != -1) {
1825 packet_disconnect("Protocol error: you already have a pty.");
1828 /* Get the time and hostname when the user last logged in. */
1829 if (options.print_lastlog) {
1830 s->hostname[0] = '\0';
1831 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1832 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1835 s->term = packet_get_string(&len);
1838 s->col = packet_get_int();
1839 s->row = packet_get_int();
1841 s->row = packet_get_int();
1842 s->col = packet_get_int();
1844 s->xpixel = packet_get_int();
1845 s->ypixel = packet_get_int();
1847 if (strcmp(s->term, "") == 0) {
1852 /* Allocate a pty and open it. */
1853 debug("Allocating pty.");
1854 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1860 error("session_pty_req: session %d alloc failed", s->self);
1863 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1865 /* for SSH1 the tty modes length is not given */
1867 n_bytes = packet_remaining();
1868 tty_parse_modes(s->ttyfd, &n_bytes);
1871 * Add a cleanup function to clear the utmp entry and record logout
1872 * time in case we call fatal() (e.g., the connection gets closed).
1874 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1876 pty_setowner(s->pw, s->tty);
1878 /* Set window size from the packet. */
1879 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1882 session_proctitle(s);
1887 session_subsystem_req(Session *s)
1892 char *cmd, *subsys = packet_get_string(&len);
1896 logit("subsystem request for %.100s", subsys);
1898 for (i = 0; i < options.num_subsystems; i++) {
1899 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1900 cmd = options.subsystem_command[i];
1901 if (stat(cmd, &st) < 0) {
1902 error("subsystem: cannot stat %s: %s", cmd,
1906 debug("subsystem: exec() %s", cmd);
1907 s->is_subsystem = 1;
1915 logit("subsystem request for %.100s failed, subsystem not found",
1923 session_x11_req(Session *s)
1927 s->single_connection = packet_get_char();
1928 s->auth_proto = packet_get_string(NULL);
1929 s->auth_data = packet_get_string(NULL);
1930 s->screen = packet_get_int();
1933 success = session_setup_x11fwd(s);
1935 xfree(s->auth_proto);
1936 xfree(s->auth_data);
1937 s->auth_proto = NULL;
1938 s->auth_data = NULL;
1944 session_shell_req(Session *s)
1952 session_exec_req(Session *s)
1955 char *command = packet_get_string(&len);
1957 do_exec(s, command);
1963 session_break_req(Session *s)
1967 break_length = packet_get_int(); /* ignored */
1970 if (s->ttyfd == -1 ||
1971 tcsendbreak(s->ttyfd, 0) < 0)
1977 session_auth_agent_req(Session *s)
1979 static int called = 0;
1981 if (no_agent_forwarding_flag) {
1982 debug("session_auth_agent_req: no_agent_forwarding_flag");
1989 return auth_input_request_forwarding(s->pw);
1994 session_input_channel_req(Channel *c, const char *rtype)
1999 if ((s = session_by_channel(c->self)) == NULL) {
2000 logit("session_input_channel_req: no session %d req %.100s",
2004 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2007 * a session is in LARVAL state until a shell, a command
2008 * or a subsystem is executed
2010 if (c->type == SSH_CHANNEL_LARVAL) {
2011 if (strcmp(rtype, "shell") == 0) {
2012 success = session_shell_req(s);
2013 } else if (strcmp(rtype, "exec") == 0) {
2014 success = session_exec_req(s);
2015 } else if (strcmp(rtype, "pty-req") == 0) {
2016 success = session_pty_req(s);
2017 } else if (strcmp(rtype, "x11-req") == 0) {
2018 success = session_x11_req(s);
2019 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2020 success = session_auth_agent_req(s);
2021 } else if (strcmp(rtype, "subsystem") == 0) {
2022 success = session_subsystem_req(s);
2023 } else if (strcmp(rtype, "break") == 0) {
2024 success = session_break_req(s);
2027 if (strcmp(rtype, "window-change") == 0) {
2028 success = session_window_change_req(s);
2034 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2037 fatal("session_set_fds: called for proto != 2.0");
2039 * now that have a child and a pipe to the child,
2040 * we can activate our channel and register the fd's
2042 if (s->chanid == -1)
2043 fatal("no channel for session %d", s->self);
2044 channel_set_fds(s->chanid,
2046 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2048 CHAN_SES_WINDOW_DEFAULT);
2052 * Function to perform pty cleanup. Also called if we get aborted abnormally
2053 * (e.g., due to a dropped connection).
2056 session_pty_cleanup2(void *session)
2058 Session *s = session;
2061 error("session_pty_cleanup: no session");
2067 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2069 /* Record that the user has logged out. */
2071 record_logout(s->pid, s->tty, s->pw->pw_name);
2073 /* Release the pseudo-tty. */
2075 pty_release(s->tty);
2078 * Close the server side of the socket pairs. We must do this after
2079 * the pty cleanup, so that another process doesn't get this pty
2080 * while we're still cleaning up.
2082 if (close(s->ptymaster) < 0)
2083 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2085 /* unlink pty from session */
2090 session_pty_cleanup(void *session)
2092 PRIVSEP(session_pty_cleanup2(session));
2098 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2113 return "SIG@openssh.com";
2117 session_exit_message(Session *s, int status)
2121 if ((c = channel_lookup(s->chanid)) == NULL)
2122 fatal("session_exit_message: session %d: no channel %d",
2123 s->self, s->chanid);
2124 debug("session_exit_message: session %d channel %d pid %ld",
2125 s->self, s->chanid, (long)s->pid);
2127 if (WIFEXITED(status)) {
2128 channel_request_start(s->chanid, "exit-status", 0);
2129 packet_put_int(WEXITSTATUS(status));
2131 } else if (WIFSIGNALED(status)) {
2132 channel_request_start(s->chanid, "exit-signal", 0);
2133 packet_put_cstring(sig2name(WTERMSIG(status)));
2135 packet_put_char(WCOREDUMP(status));
2136 #else /* WCOREDUMP */
2138 #endif /* WCOREDUMP */
2139 packet_put_cstring("");
2140 packet_put_cstring("");
2143 /* Some weird exit cause. Just exit. */
2144 packet_disconnect("wait returned status %04x.", status);
2147 /* disconnect channel */
2148 debug("session_exit_message: release channel %d", s->chanid);
2149 channel_cancel_cleanup(s->chanid);
2151 * emulate a write failure with 'chan_write_failed', nobody will be
2152 * interested in data we write.
2153 * Note that we must not call 'chan_read_failed', since there could
2154 * be some more data waiting in the pipe.
2156 if (c->ostate != CHAN_OUTPUT_CLOSED)
2157 chan_write_failed(c);
2162 session_close(Session *s)
2164 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2165 if (s->ttyfd != -1) {
2166 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2167 session_pty_cleanup(s);
2173 if (s->auth_display)
2174 xfree(s->auth_display);
2176 xfree(s->auth_data);
2178 xfree(s->auth_proto);
2180 session_proctitle(s);
2184 session_close_by_pid(pid_t pid, int status)
2186 Session *s = session_by_pid(pid);
2188 debug("session_close_by_pid: no session for pid %ld",
2192 if (s->chanid != -1)
2193 session_exit_message(s, status);
2198 * this is called when a channel dies before
2199 * the session 'child' itself dies
2202 session_close_by_channel(int id, void *arg)
2204 Session *s = session_by_channel(id);
2206 debug("session_close_by_channel: no session for id %d", id);
2209 debug("session_close_by_channel: channel %d child %ld",
2212 debug("session_close_by_channel: channel %d: has child", id);
2214 * delay detach of session, but release pty, since
2215 * the fd's to the child are already closed
2217 if (s->ttyfd != -1) {
2218 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2219 session_pty_cleanup(s);
2223 /* detach by removing callback */
2224 channel_cancel_cleanup(s->chanid);
2230 session_destroy_all(void (*closefunc)(Session *))
2233 for (i = 0; i < MAX_SESSIONS; i++) {
2234 Session *s = &sessions[i];
2236 if (closefunc != NULL)
2245 session_tty_list(void)
2247 static char buf[1024];
2252 for (i = 0; i < MAX_SESSIONS; i++) {
2253 Session *s = &sessions[i];
2254 if (s->used && s->ttyfd != -1) {
2256 if (strncmp(s->tty, "/dev/", 5) != 0) {
2257 cp = strrchr(s->tty, '/');
2258 cp = (cp == NULL) ? s->tty : cp + 1;
2263 strlcat(buf, ",", sizeof buf);
2264 strlcat(buf, cp, sizeof buf);
2268 strlcpy(buf, "notty", sizeof buf);
2273 session_proctitle(Session *s)
2276 error("no user for session %d", s->self);
2278 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2282 session_setup_x11fwd(Session *s)
2285 char display[512], auth_display[512];
2286 char hostname[MAXHOSTNAMELEN];
2288 if (no_x11_forwarding_flag) {
2289 packet_send_debug("X11 forwarding disabled in user configuration file.");
2292 if (!options.x11_forwarding) {
2293 debug("X11 forwarding disabled in server configuration file.");
2296 if (!options.xauth_location ||
2297 (stat(options.xauth_location, &st) == -1)) {
2298 packet_send_debug("No xauth program; cannot forward with spoofing.");
2301 if (options.use_login) {
2302 packet_send_debug("X11 forwarding disabled; "
2303 "not compatible with UseLogin=yes.");
2306 if (s->display != NULL) {
2307 debug("X11 display already set.");
2310 if (x11_create_display_inet(options.x11_display_offset,
2311 options.x11_use_localhost, s->single_connection,
2312 &s->display_number) == -1) {
2313 debug("x11_create_display_inet failed.");
2317 /* Set up a suitable value for the DISPLAY variable. */
2318 if (gethostname(hostname, sizeof(hostname)) < 0)
2319 fatal("gethostname: %.100s", strerror(errno));
2321 * auth_display must be used as the displayname when the
2322 * authorization entry is added with xauth(1). This will be
2323 * different than the DISPLAY string for localhost displays.
2325 if (options.x11_use_localhost) {
2326 snprintf(display, sizeof display, "localhost:%u.%u",
2327 s->display_number, s->screen);
2328 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2329 s->display_number, s->screen);
2330 s->display = xstrdup(display);
2331 s->auth_display = xstrdup(auth_display);
2333 #ifdef IPADDR_IN_DISPLAY
2335 struct in_addr my_addr;
2337 he = gethostbyname(hostname);
2339 error("Can't get IP address for X11 DISPLAY.");
2340 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2343 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2344 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2345 s->display_number, s->screen);
2347 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2348 s->display_number, s->screen);
2350 s->display = xstrdup(display);
2351 s->auth_display = xstrdup(display);
2358 do_authenticated2(Authctxt *authctxt)
2360 server_loop2(authctxt);
2362 if (options.gss_cleanup_creds)
2363 ssh_gssapi_cleanup_creds(NULL);