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.128 2002/02/16 00:51:44 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
66 #include <sys/cygwin.h>
67 #define is_winnt (GetVersion() < 0x80000000)
73 typedef struct Session Session;
82 int ptyfd, ttyfd, ptymaster;
83 int row, col, xpixel, ypixel;
92 int single_connection;
100 Session *session_new(void);
101 void session_set_fds(Session *, int, int, int);
102 static void session_pty_cleanup(void *);
103 void session_proctitle(Session *);
104 int session_setup_x11fwd(Session *);
105 void do_exec_pty(Session *, const char *);
106 void do_exec_no_pty(Session *, const char *);
107 void do_exec(Session *, const char *);
108 void do_login(Session *, const char *);
109 #ifdef LOGIN_NEEDS_UTMPX
110 static void do_pre_login(Session *s);
112 void do_child(Session *, const char *);
114 int check_quietlogin(Session *, const char *);
116 static void do_authenticated1(Authctxt *);
117 static void do_authenticated2(Authctxt *);
119 static void session_close(Session *);
120 static int session_pty_req(Session *);
123 extern ServerOptions options;
124 extern char *__progname;
125 extern int log_stderr;
126 extern int debug_flag;
127 extern u_int utmp_len;
128 extern int startup_pipe;
129 extern void destroy_sensitive_data(void);
131 /* original command from peer. */
132 const char *original_command = NULL;
135 #define MAX_SESSIONS 10
136 Session sessions[MAX_SESSIONS];
138 #ifdef WITH_AIXAUTHENTICATE
140 #endif /* WITH_AIXAUTHENTICATE */
142 #ifdef HAVE_LOGIN_CAP
143 static login_cap_t *lc;
147 do_authenticated(Authctxt *authctxt)
150 * Cancel the alarm we set to limit the time taken for
154 if (startup_pipe != -1) {
158 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
159 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
160 error("unable to get login class");
164 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
165 packet_disconnect("Approval failure for %s",
166 authctxt->pw->pw_name);
170 #ifdef WITH_AIXAUTHENTICATE
171 /* We don't have a pty yet, so just label the line as "ssh" */
172 if (loginsuccess(authctxt->user,
173 get_canonical_hostname(options.verify_reverse_mapping),
174 "ssh", &aixloginmsg) < 0)
176 #endif /* WITH_AIXAUTHENTICATE */
178 /* setup the channel layer */
179 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
180 channel_permit_all_opens();
183 do_authenticated2(authctxt);
185 do_authenticated1(authctxt);
187 /* remove agent socket */
188 if (auth_get_socket_name())
189 auth_sock_cleanup_proc(authctxt->pw);
191 if (options.kerberos_ticket_cleanup)
192 krb4_cleanup_proc(authctxt);
195 if (options.kerberos_ticket_cleanup)
196 krb5_cleanup_proc(authctxt);
201 * Prepares for an interactive session. This is called after the user has
202 * been successfully authenticated. During this message exchange, pseudo
203 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
204 * are requested, etc.
207 do_authenticated1(Authctxt *authctxt)
211 int success, type, screen_flag;
212 int compression_level = 0, enable_compression_after_reply = 0;
213 u_int proto_len, data_len, dlen;
216 s->authctxt = authctxt;
217 s->pw = authctxt->pw;
220 * We stay in this loop until the client requests to execute a shell
226 /* Get a packet from the client. */
227 type = packet_read();
229 /* Process the packet. */
231 case SSH_CMSG_REQUEST_COMPRESSION:
232 compression_level = packet_get_int();
234 if (compression_level < 1 || compression_level > 9) {
235 packet_send_debug("Received illegal compression level %d.",
239 /* Enable compression after we have responded with SUCCESS. */
240 enable_compression_after_reply = 1;
244 case SSH_CMSG_REQUEST_PTY:
245 success = session_pty_req(s);
248 case SSH_CMSG_X11_REQUEST_FORWARDING:
249 s->auth_proto = packet_get_string(&proto_len);
250 s->auth_data = packet_get_string(&data_len);
252 screen_flag = packet_get_protocol_flags() &
253 SSH_PROTOFLAG_SCREEN_NUMBER;
254 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
256 if (packet_remaining() == 4) {
258 debug2("Buggy client: "
259 "X11 screen flag missing");
260 s->screen = packet_get_int();
265 success = session_setup_x11fwd(s);
267 xfree(s->auth_proto);
269 s->auth_proto = NULL;
274 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
275 if (no_agent_forwarding_flag || compat13) {
276 debug("Authentication agent forwarding not permitted for this authentication.");
279 debug("Received authentication agent forwarding request.");
280 success = auth_input_request_forwarding(s->pw);
283 case SSH_CMSG_PORT_FORWARD_REQUEST:
284 if (no_port_forwarding_flag) {
285 debug("Port forwarding not permitted for this authentication.");
288 if (!options.allow_tcp_forwarding) {
289 debug("Port forwarding not permitted.");
292 debug("Received TCP/IP port forwarding request.");
293 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
297 case SSH_CMSG_MAX_PACKET_SIZE:
298 if (packet_set_maxsize(packet_get_int()) > 0)
302 #if defined(AFS) || defined(KRB5)
303 case SSH_CMSG_HAVE_KERBEROS_TGT:
304 if (!options.kerberos_tgt_passing) {
305 verbose("Kerberos TGT passing disabled.");
307 char *kdata = packet_get_string(&dlen);
310 /* XXX - 0x41, see creds_to_radix version */
311 if (kdata[0] != 0x41) {
317 if (auth_krb5_tgt(s->authctxt, &tgt))
320 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
324 if (auth_krb4_tgt(s->authctxt, kdata))
327 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
333 #endif /* AFS || KRB5 */
336 case SSH_CMSG_HAVE_AFS_TOKEN:
337 if (!options.afs_token_passing || !k_hasafs()) {
338 verbose("AFS token passing disabled.");
340 /* Accept AFS token. */
341 char *token = packet_get_string(&dlen);
344 if (auth_afs_token(s->authctxt, token))
347 verbose("AFS token refused for %.100s",
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);
370 * Any unknown messages in this phase are ignored,
371 * and a failure message is returned.
373 log("Unknown packet type received after authentication: %d", type);
375 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
379 /* Enable compression now that we have replied if appropriate. */
380 if (enable_compression_after_reply) {
381 enable_compression_after_reply = 0;
382 packet_start_compression(compression_level);
388 * This is called to fork and execute a command when we have no tty. This
389 * will call do_child from the child, and server_loop from the parent after
390 * setting up file descriptors and such.
393 do_exec_no_pty(Session *s, const char *command)
398 int pin[2], pout[2], perr[2];
399 /* Allocate pipes for communicating with the program. */
400 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
401 packet_disconnect("Could not create pipes: %.100s",
403 #else /* USE_PIPES */
404 int inout[2], err[2];
405 /* Uses socket pairs to communicate with the program. */
406 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
407 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
408 packet_disconnect("Could not create socket pairs: %.100s",
410 #endif /* USE_PIPES */
412 fatal("do_exec_no_pty: no session");
414 session_proctitle(s);
417 temporarily_use_uid(s->pw);
418 ssh_gssapi_storecreds();
423 do_pam_session(s->pw->pw_name, NULL);
425 if (is_pam_password_change_required())
426 packet_disconnect("Password change required but no "
430 /* Fork the child. */
431 if ((pid = fork()) == 0) {
432 /* Child. Reinitialize the log since the pid has changed. */
433 log_init(__progname, options.log_level, options.log_facility, log_stderr);
436 * Create a new session and process group since the 4.4BSD
437 * setlogin() affects the entire process group.
440 error("setsid failed: %.100s", strerror(errno));
444 * Redirect stdin. We close the parent side of the socket
445 * pair, and make the child side the standard input.
448 if (dup2(pin[0], 0) < 0)
449 perror("dup2 stdin");
452 /* Redirect stdout. */
454 if (dup2(pout[1], 1) < 0)
455 perror("dup2 stdout");
458 /* Redirect stderr. */
460 if (dup2(perr[1], 2) < 0)
461 perror("dup2 stderr");
463 #else /* USE_PIPES */
465 * Redirect stdin, stdout, and stderr. Stdin and stdout will
466 * use the same socket, as some programs (particularly rdist)
467 * seem to depend on it.
471 if (dup2(inout[0], 0) < 0) /* stdin */
472 perror("dup2 stdin");
473 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
474 perror("dup2 stdout");
475 if (dup2(err[0], 2) < 0) /* stderr */
476 perror("dup2 stderr");
477 #endif /* USE_PIPES */
479 /* Do processing for the child (exec command etc). */
480 do_child(s, command);
485 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
488 packet_disconnect("fork failed: %.100s", strerror(errno));
490 /* Set interactive/non-interactive mode. */
491 packet_set_interactive(s->display != NULL);
493 /* We are the parent. Close the child sides of the pipes. */
499 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
501 /* Enter the interactive session. */
502 server_loop(pid, pin[1], pout[0], perr[0]);
503 /* server_loop has closed pin[1], pout[0], and perr[0]. */
505 #else /* USE_PIPES */
506 /* We are the parent. Close the child sides of the socket pairs. */
511 * Enter the interactive session. Note: server_loop must be able to
512 * handle the case that fdin and fdout are the same.
515 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
517 server_loop(pid, inout[1], inout[1], err[1]);
518 /* server_loop has closed inout[1] and err[1]. */
520 #endif /* USE_PIPES */
524 * This is called to fork and execute a command when we have a tty. This
525 * will call do_child from the child, and server_loop from the parent after
526 * setting up file descriptors, controlling tty, updating wtmp, utmp,
527 * lastlog, and other such operations.
530 do_exec_pty(Session *s, const char *command)
532 int fdout, ptyfd, ttyfd, ptymaster;
536 fatal("do_exec_pty: no session");
541 temporarily_use_uid(s->pw);
542 ssh_gssapi_storecreds();
547 do_pam_session(s->pw->pw_name, s->tty);
551 /* Fork the child. */
552 if ((pid = fork()) == 0) {
554 /* Child. Reinitialize the log because the pid has changed. */
555 log_init(__progname, options.log_level, options.log_facility, log_stderr);
556 /* Close the master side of the pseudo tty. */
559 /* Make the pseudo tty our controlling tty. */
560 pty_make_controlling_tty(&ttyfd, s->tty);
562 /* Redirect stdin/stdout/stderr from the pseudo tty. */
563 if (dup2(ttyfd, 0) < 0)
564 error("dup2 stdin: %s", strerror(errno));
565 if (dup2(ttyfd, 1) < 0)
566 error("dup2 stdout: %s", strerror(errno));
567 if (dup2(ttyfd, 2) < 0)
568 error("dup2 stderr: %s", strerror(errno));
570 /* Close the extra descriptor for the pseudo tty. */
573 /* record login, etc. similar to login(1) */
575 if (!(options.use_login && command == NULL))
576 do_login(s, command);
577 # ifdef LOGIN_NEEDS_UTMPX
583 /* Do common processing for the child, such as execing the command. */
584 do_child(s, command);
589 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
592 packet_disconnect("fork failed: %.100s", strerror(errno));
595 /* Parent. Close the slave side of the pseudo tty. */
599 * Create another descriptor of the pty master side for use as the
600 * standard input. We could use the original descriptor, but this
601 * simplifies code in server_loop. The descriptor is bidirectional.
605 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
607 /* we keep a reference to the pty master */
608 ptymaster = dup(ptyfd);
610 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
611 s->ptymaster = ptymaster;
613 /* Enter interactive session. */
614 packet_set_interactive(1);
616 session_set_fds(s, ptyfd, fdout, -1);
618 server_loop(pid, ptyfd, fdout, -1);
619 /* server_loop _has_ closed ptyfd and fdout. */
623 #ifdef LOGIN_NEEDS_UTMPX
625 do_pre_login(Session *s)
628 struct sockaddr_storage from;
629 pid_t pid = getpid();
632 * Get IP address of client. If the connection is not a socket, let
633 * the address be 0.0.0.0.
635 memset(&from, 0, sizeof(from));
636 if (packet_connection_is_on_socket()) {
637 fromlen = sizeof(from);
638 if (getpeername(packet_get_connection_in(),
639 (struct sockaddr *) & from, &fromlen) < 0) {
640 debug("getpeername: %.100s", strerror(errno));
645 record_utmp_only(pid, s->tty, s->pw->pw_name,
646 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
647 (struct sockaddr *)&from);
652 * This is called to fork and execute a command. If another command is
653 * to be forced, execute that instead.
656 do_exec(Session *s, const char *command)
658 if (forced_command) {
659 original_command = command;
660 command = forced_command;
661 debug("Forced command '%.900s'", command);
665 do_exec_pty(s, command);
667 do_exec_no_pty(s, command);
669 original_command = NULL;
673 /* administrative, login(1)-like work */
675 do_login(Session *s, const char *command)
678 char hostname[MAXHOSTNAMELEN];
680 struct sockaddr_storage from;
681 time_t last_login_time;
682 struct passwd * pw = s->pw;
683 pid_t pid = getpid();
686 * Get IP address of client. If the connection is not a socket, let
687 * the address be 0.0.0.0.
689 memset(&from, 0, sizeof(from));
690 if (packet_connection_is_on_socket()) {
691 fromlen = sizeof(from);
692 if (getpeername(packet_get_connection_in(),
693 (struct sockaddr *) & from, &fromlen) < 0) {
694 debug("getpeername: %.100s", strerror(errno));
699 /* Get the time and hostname when the user last logged in. */
700 if (options.print_lastlog) {
702 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
703 hostname, sizeof(hostname));
706 /* Record that there was a login on that tty from the remote host. */
707 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
708 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
709 (struct sockaddr *)&from);
713 * If password change is needed, do it now.
714 * This needs to occur before the ~/.hushlogin check.
716 if (is_pam_password_change_required()) {
717 print_pam_messages();
722 if (check_quietlogin(s, command))
726 if (!is_pam_password_change_required())
727 print_pam_messages();
729 #ifdef WITH_AIXAUTHENTICATE
730 if (aixloginmsg && *aixloginmsg)
731 printf("%s\n", aixloginmsg);
732 #endif /* WITH_AIXAUTHENTICATE */
734 if (options.print_lastlog && last_login_time != 0) {
735 time_string = ctime(&last_login_time);
736 if (strchr(time_string, '\n'))
737 *strchr(time_string, '\n') = 0;
738 if (strcmp(hostname, "") == 0)
739 printf("Last login: %s\r\n", time_string);
741 printf("Last login: %s from %s\r\n", time_string, hostname);
748 * Display the message of the day.
756 if (options.print_motd) {
757 #ifdef HAVE_LOGIN_CAP
758 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
761 f = fopen("/etc/motd", "r");
764 while (fgets(buf, sizeof(buf), f))
773 * Check for quiet login, either .hushlogin or command given.
776 check_quietlogin(Session *s, const char *command)
779 struct passwd *pw = s->pw;
782 /* Return 1 if .hushlogin exists or a command given. */
785 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
786 #ifdef HAVE_LOGIN_CAP
787 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
790 if (stat(buf, &st) >= 0)
797 * Sets the value of the given variable in the environment. If the variable
798 * already exists, its value is overriden.
801 child_set_env(char ***envp, u_int *envsizep, const char *name,
808 * Find the slot where the value should be stored. If the variable
809 * already exists, we reuse the slot; otherwise we append a new slot
810 * at the end of the array, expanding if necessary.
813 namelen = strlen(name);
814 for (i = 0; env[i]; i++)
815 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
818 /* Reuse the slot. */
821 /* New variable. Expand if necessary. */
822 if (i >= (*envsizep) - 1) {
824 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
826 /* Need to set the NULL pointer at end of array beyond the new slot. */
830 /* Allocate space and format the variable in the appropriate slot. */
831 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
832 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
836 * Reads environment variables from the given file and adds/overrides them
837 * into the environment. If the file does not exist, this does nothing.
838 * Otherwise, it must consist of empty lines, comments (line starts with '#')
839 * and assignments of the form name=value. No other forms are allowed.
842 read_environment_file(char ***env, u_int *envsize,
843 const char *filename)
849 f = fopen(filename, "r");
853 while (fgets(buf, sizeof(buf), f)) {
854 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
856 if (!*cp || *cp == '#' || *cp == '\n')
858 if (strchr(cp, '\n'))
859 *strchr(cp, '\n') = '\0';
860 value = strchr(cp, '=');
862 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
866 * Replace the equals sign by nul, and advance value to
871 child_set_env(env, envsize, cp, value);
876 void copy_environment(char **source, char ***env, u_int *envsize)
878 char *var_name, *var_val;
884 for(i = 0; source[i] != NULL; i++) {
885 var_name = xstrdup(source[i]);
886 if ((var_val = strstr(var_name, "=")) == NULL) {
892 debug3("Copy environment: %s=%s", var_name, var_val);
893 child_set_env(env, envsize, var_name, var_val);
900 do_setup_env(Session *s, const char *shell)
905 struct passwd *pw = s->pw;
907 /* Initialize the environment. */
909 env = xmalloc(envsize * sizeof(char *));
914 * The Windows environment contains some setting which are
915 * important for a running system. They must not be dropped.
917 copy_environment(environ, &env, &envsize);
921 /* Allow any GSSAPI methods that we've used to alter
922 * the childs environment as they see fit
924 ssh_gssapi_do_child(&env,&envsize);
927 if (!options.use_login) {
928 /* Set basic environment. */
929 child_set_env(&env, &envsize, "USER", pw->pw_name);
930 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
931 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
932 #ifdef HAVE_LOGIN_CAP
933 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
934 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
935 #else /* HAVE_LOGIN_CAP */
938 * There's no standard path on Windows. The path contains
939 * important components pointing to the system directories,
940 * needed for loading shared libraries. So the path better
941 * remains intact here.
943 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
944 # endif /* HAVE_CYGWIN */
945 #endif /* HAVE_LOGIN_CAP */
947 snprintf(buf, sizeof buf, "%.200s/%.50s",
948 _PATH_MAILDIR, pw->pw_name);
949 child_set_env(&env, &envsize, "MAIL", buf);
951 /* Normal systems set SHELL by default. */
952 child_set_env(&env, &envsize, "SHELL", shell);
955 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
957 /* Set custom environment options from RSA authentication. */
958 if (!options.use_login) {
959 while (custom_environment) {
960 struct envstring *ce = custom_environment;
963 for (i = 0; s[i] != '=' && s[i]; i++)
967 child_set_env(&env, &envsize, s, s + i + 1);
969 custom_environment = ce->next;
975 snprintf(buf, sizeof buf, "%.50s %d %d",
976 get_remote_ipaddr(), get_remote_port(), get_local_port());
977 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
980 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
982 child_set_env(&env, &envsize, "TERM", s->term);
984 child_set_env(&env, &envsize, "DISPLAY", s->display);
985 if (original_command)
986 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
993 if ((cp = getenv("AUTHSTATE")) != NULL)
994 child_set_env(&env, &envsize, "AUTHSTATE", cp);
995 if ((cp = getenv("KRB5CCNAME")) != NULL)
996 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
997 read_environment_file(&env, &envsize, "/etc/environment");
1001 if (s->authctxt->krb4_ticket_file)
1002 child_set_env(&env, &envsize, "KRBTKFILE",
1003 s->authctxt->krb4_ticket_file);
1006 if (s->authctxt->krb5_ticket_file)
1007 child_set_env(&env, &envsize, "KRB5CCNAME",
1008 s->authctxt->krb5_ticket_file);
1011 /* Pull in any environment variables that may have been set by PAM. */
1012 copy_environment(fetch_pam_environment(), &env, &envsize);
1013 #endif /* USE_PAM */
1015 if (auth_get_socket_name() != NULL)
1016 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1017 auth_get_socket_name());
1019 /* read $HOME/.ssh/environment. */
1020 if (!options.use_login) {
1021 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1023 read_environment_file(&env, &envsize, buf);
1026 /* dump the environment */
1027 fprintf(stderr, "Environment:\n");
1028 for (i = 0; env[i]; i++)
1029 fprintf(stderr, " %.200s\n", env[i]);
1035 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1036 * first in this order).
1039 do_rc_files(Session *s, const char *shell)
1047 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1049 /* ignore _PATH_SSH_USER_RC for subsystems */
1050 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1051 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1052 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1054 fprintf(stderr, "Running %s\n", cmd);
1055 f = popen(cmd, "w");
1058 fprintf(f, "%s %s\n", s->auth_proto,
1062 fprintf(stderr, "Could not run %s\n",
1064 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1066 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1067 _PATH_SSH_SYSTEM_RC);
1068 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1071 fprintf(f, "%s %s\n", s->auth_proto,
1075 fprintf(stderr, "Could not run %s\n",
1076 _PATH_SSH_SYSTEM_RC);
1077 } else if (do_xauth && options.xauth_location != NULL) {
1078 /* Add authority data to .Xauthority if appropriate. */
1081 "Running %.100s add "
1082 "%.100s %.100s %.100s\n",
1083 options.xauth_location, s->auth_display,
1084 s->auth_proto, s->auth_data);
1086 snprintf(cmd, sizeof cmd, "%s -q -",
1087 options.xauth_location);
1088 f = popen(cmd, "w");
1090 fprintf(f, "add %s %s %s\n",
1091 s->auth_display, s->auth_proto,
1095 fprintf(stderr, "Could not run %s\n",
1102 do_nologin(struct passwd *pw)
1107 #ifdef HAVE_LOGIN_CAP
1108 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1109 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1110 _PATH_NOLOGIN), "r");
1113 f = fopen(_PATH_NOLOGIN, "r");
1116 /* /etc/nologin exists. Print its contents and exit. */
1117 while (fgets(buf, sizeof(buf), f))
1124 /* Set login name, uid, gid, and groups. */
1126 do_setusercontext(struct passwd *pw)
1130 #else /* HAVE_CYGWIN */
1131 if (getuid() == 0 || geteuid() == 0) {
1132 #endif /* HAVE_CYGWIN */
1133 #ifdef HAVE_GETUSERATTR
1134 set_limits_from_userattr(pw->pw_name);
1135 #endif /* HAVE_GETUSERATTR */
1136 #ifdef HAVE_LOGIN_CAP
1137 if (setusercontext(lc, pw, pw->pw_uid,
1138 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1139 perror("unable to set user context");
1143 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1144 /* Sets login uid for accounting */
1145 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1146 error("setluid: %s", strerror(errno));
1147 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1149 if (setlogin(pw->pw_name) < 0)
1150 error("setlogin failed: %s", strerror(errno));
1151 if (setgid(pw->pw_gid) < 0) {
1155 /* Initialize the group list. */
1156 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1157 perror("initgroups");
1163 * PAM credentials may take the form of supplementary groups.
1164 * These will have been wiped by the above initgroups() call.
1165 * Reestablish them here.
1168 # endif /* USE_PAM */
1169 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1170 irix_setusercontext(pw);
1171 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1172 /* Permanently switch to the desired uid. */
1173 permanently_set_uid(pw);
1176 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1177 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1181 * Performs common processing for the child, such as setting up the
1182 * environment, closing extra file descriptors, setting the user and group
1183 * ids, and executing the command or shell.
1186 do_child(Session *s, const char *command)
1188 extern char **environ;
1191 const char *shell, *shell0, *hostname = NULL;
1192 struct passwd *pw = s->pw;
1195 /* remove hostkey from the child's memory */
1196 destroy_sensitive_data();
1198 /* login(1) is only called if we execute the login shell */
1199 if (options.use_login && command != NULL)
1200 options.use_login = 0;
1203 * Login(1) does this as well, and it needs uid 0 for the "-h"
1204 * switch, so we let login(1) to this for us.
1206 if (!options.use_login) {
1208 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1209 if (!check_quietlogin(s, command))
1211 #else /* HAVE_OSF_SIA */
1214 aix_usrinfo(pw, s->tty, s->ttyfd);
1216 do_setusercontext(pw);
1217 #endif /* HAVE_OSF_SIA */
1221 * Get the shell from the password data. An empty shell field is
1222 * legal, and means /bin/sh.
1224 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1225 #ifdef HAVE_LOGIN_CAP
1226 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1229 env = do_setup_env(s, shell);
1231 /* we have to stash the hostname before we close our socket. */
1232 if (options.use_login)
1233 hostname = get_remote_name_or_ip(utmp_len,
1234 options.verify_reverse_mapping);
1236 * Close the connection descriptors; note that this is the child, and
1237 * the server will still have the socket open, and it is important
1238 * that we do not shutdown it. Note that the descriptors cannot be
1239 * closed before building the environment, as we call
1240 * get_remote_ipaddr there.
1242 if (packet_get_connection_in() == packet_get_connection_out())
1243 close(packet_get_connection_in());
1245 close(packet_get_connection_in());
1246 close(packet_get_connection_out());
1249 * Close all descriptors related to channels. They will still remain
1250 * open in the parent.
1252 /* XXX better use close-on-exec? -markus */
1253 channel_close_all();
1256 * Close any extra file descriptors. Note that there may still be
1257 * descriptors left by system functions. They will be closed later.
1262 * Close any extra open file descriptors so that we don\'t have them
1263 * hanging around in clients. Note that we want to do this after
1264 * initgroups, because at least on Solaris 2.3 it leaves file
1267 for (i = 3; i < 64; i++)
1271 * Must take new environment into use so that .ssh/rc,
1272 * /etc/ssh/sshrc and xauth are run in the proper environment.
1277 /* Try to get AFS tokens for the local cell. */
1281 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1282 krb_afslog(cell, 0);
1288 /* Change current directory to the user\'s home directory. */
1289 if (chdir(pw->pw_dir) < 0) {
1290 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1291 pw->pw_dir, strerror(errno));
1292 #ifdef HAVE_LOGIN_CAP
1293 if (login_getcapbool(lc, "requirehome", 0))
1298 if (!options.use_login)
1299 do_rc_files(s, shell);
1301 /* restore SIGPIPE for child */
1302 signal(SIGPIPE, SIG_DFL);
1304 if (options.use_login) {
1305 /* Launch login(1). */
1307 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1308 #ifdef LOGIN_NEEDS_TERM
1309 (s->term ? s->term : "unknown"),
1310 #endif /* LOGIN_NEEDS_TERM */
1311 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1313 /* Login couldn't be executed, die. */
1319 /* Get the last component of the shell name. */
1320 if ((shell0 = strrchr(shell, '/')) != NULL)
1326 * If we have no command, execute the shell. In this case, the shell
1327 * name to be passed in argv[0] is preceded by '-' to indicate that
1328 * this is a login shell.
1333 /* Start the shell. Set initial character to '-'. */
1336 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1337 >= sizeof(argv0) - 1) {
1343 /* Execute the shell. */
1346 execve(shell, argv, env);
1348 /* Executing the shell failed. */
1353 * Execute the command using the user's shell. This uses the -c
1354 * option to execute the command.
1356 argv[0] = (char *) shell0;
1358 argv[2] = (char *) command;
1360 execve(shell, argv, env);
1369 static int did_init = 0;
1371 debug("session_new: init");
1372 for (i = 0; i < MAX_SESSIONS; i++) {
1373 sessions[i].used = 0;
1377 for (i = 0; i < MAX_SESSIONS; i++) {
1378 Session *s = &sessions[i];
1380 memset(s, 0, sizeof(*s));
1386 debug("session_new: session %d", i);
1397 for (i = 0; i < MAX_SESSIONS; i++) {
1398 Session *s = &sessions[i];
1399 debug("dump: used %d session %d %p channel %d pid %d",
1409 session_open(Authctxt *authctxt, int chanid)
1411 Session *s = session_new();
1412 debug("session_open: channel %d", chanid);
1414 error("no more sessions");
1417 s->authctxt = authctxt;
1418 s->pw = authctxt->pw;
1420 fatal("no user for session %d", s->self);
1421 debug("session_open: session %d: link with channel %d", s->self, chanid);
1427 session_by_channel(int id)
1430 for (i = 0; i < MAX_SESSIONS; i++) {
1431 Session *s = &sessions[i];
1432 if (s->used && s->chanid == id) {
1433 debug("session_by_channel: session %d channel %d", i, id);
1437 debug("session_by_channel: unknown channel %d", id);
1443 session_by_pid(pid_t pid)
1446 debug("session_by_pid: pid %d", pid);
1447 for (i = 0; i < MAX_SESSIONS; i++) {
1448 Session *s = &sessions[i];
1449 if (s->used && s->pid == pid)
1452 error("session_by_pid: unknown pid %d", pid);
1458 session_window_change_req(Session *s)
1460 s->col = packet_get_int();
1461 s->row = packet_get_int();
1462 s->xpixel = packet_get_int();
1463 s->ypixel = packet_get_int();
1465 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1470 session_pty_req(Session *s)
1476 debug("Allocating a pty not permitted for this authentication.");
1479 if (s->ttyfd != -1) {
1480 packet_disconnect("Protocol error: you already have a pty.");
1484 s->term = packet_get_string(&len);
1487 s->col = packet_get_int();
1488 s->row = packet_get_int();
1490 s->row = packet_get_int();
1491 s->col = packet_get_int();
1493 s->xpixel = packet_get_int();
1494 s->ypixel = packet_get_int();
1496 if (strcmp(s->term, "") == 0) {
1501 /* Allocate a pty and open it. */
1502 debug("Allocating pty.");
1503 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1509 error("session_pty_req: session %d alloc failed", s->self);
1512 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1514 /* for SSH1 the tty modes length is not given */
1516 n_bytes = packet_remaining();
1517 tty_parse_modes(s->ttyfd, &n_bytes);
1520 * Add a cleanup function to clear the utmp entry and record logout
1521 * time in case we call fatal() (e.g., the connection gets closed).
1523 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1524 pty_setowner(s->pw, s->tty);
1526 /* Set window size from the packet. */
1527 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1530 session_proctitle(s);
1535 session_subsystem_req(Session *s)
1540 char *cmd, *subsys = packet_get_string(&len);
1544 log("subsystem request for %.100s", subsys);
1546 for (i = 0; i < options.num_subsystems; i++) {
1547 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1548 cmd = options.subsystem_command[i];
1549 if (stat(cmd, &st) < 0) {
1550 error("subsystem: cannot stat %s: %s", cmd,
1554 debug("subsystem: exec() %s", cmd);
1555 s->is_subsystem = 1;
1563 log("subsystem request for %.100s failed, subsystem not found",
1571 session_x11_req(Session *s)
1575 s->single_connection = packet_get_char();
1576 s->auth_proto = packet_get_string(NULL);
1577 s->auth_data = packet_get_string(NULL);
1578 s->screen = packet_get_int();
1581 success = session_setup_x11fwd(s);
1583 xfree(s->auth_proto);
1584 xfree(s->auth_data);
1585 s->auth_proto = NULL;
1586 s->auth_data = NULL;
1592 session_shell_req(Session *s)
1600 session_exec_req(Session *s)
1603 char *command = packet_get_string(&len);
1605 do_exec(s, command);
1611 session_auth_agent_req(Session *s)
1613 static int called = 0;
1615 if (no_agent_forwarding_flag) {
1616 debug("session_auth_agent_req: no_agent_forwarding_flag");
1623 return auth_input_request_forwarding(s->pw);
1628 session_input_channel_req(Channel *c, const char *rtype)
1633 if ((s = session_by_channel(c->self)) == NULL) {
1634 log("session_input_channel_req: no session %d req %.100s",
1638 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1641 * a session is in LARVAL state until a shell, a command
1642 * or a subsystem is executed
1644 if (c->type == SSH_CHANNEL_LARVAL) {
1645 if (strcmp(rtype, "shell") == 0) {
1646 success = session_shell_req(s);
1647 } else if (strcmp(rtype, "exec") == 0) {
1648 success = session_exec_req(s);
1649 } else if (strcmp(rtype, "pty-req") == 0) {
1650 success = session_pty_req(s);
1651 } else if (strcmp(rtype, "x11-req") == 0) {
1652 success = session_x11_req(s);
1653 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1654 success = session_auth_agent_req(s);
1655 } else if (strcmp(rtype, "subsystem") == 0) {
1656 success = session_subsystem_req(s);
1659 if (strcmp(rtype, "window-change") == 0) {
1660 success = session_window_change_req(s);
1666 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1669 fatal("session_set_fds: called for proto != 2.0");
1671 * now that have a child and a pipe to the child,
1672 * we can activate our channel and register the fd's
1674 if (s->chanid == -1)
1675 fatal("no channel for session %d", s->self);
1676 channel_set_fds(s->chanid,
1678 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1680 CHAN_SES_WINDOW_DEFAULT);
1684 * Function to perform pty cleanup. Also called if we get aborted abnormally
1685 * (e.g., due to a dropped connection).
1688 session_pty_cleanup(void *session)
1690 Session *s = session;
1693 error("session_pty_cleanup: no session");
1699 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1701 /* Record that the user has logged out. */
1703 record_logout(s->pid, s->tty, s->pw->pw_name);
1705 /* Release the pseudo-tty. */
1706 pty_release(s->tty);
1709 * Close the server side of the socket pairs. We must do this after
1710 * the pty cleanup, so that another process doesn't get this pty
1711 * while we're still cleaning up.
1713 if (close(s->ptymaster) < 0)
1714 error("close(s->ptymaster): %s", strerror(errno));
1716 /* unlink pty from session */
1721 session_exit_message(Session *s, int status)
1725 if ((c = channel_lookup(s->chanid)) == NULL)
1726 fatal("session_exit_message: session %d: no channel %d",
1727 s->self, s->chanid);
1728 debug("session_exit_message: session %d channel %d pid %d",
1729 s->self, s->chanid, s->pid);
1731 if (WIFEXITED(status)) {
1732 channel_request_start(s->chanid, "exit-status", 0);
1733 packet_put_int(WEXITSTATUS(status));
1735 } else if (WIFSIGNALED(status)) {
1736 channel_request_start(s->chanid, "exit-signal", 0);
1737 packet_put_int(WTERMSIG(status));
1739 packet_put_char(WCOREDUMP(status));
1740 #else /* WCOREDUMP */
1742 #endif /* WCOREDUMP */
1743 packet_put_cstring("");
1744 packet_put_cstring("");
1747 /* Some weird exit cause. Just exit. */
1748 packet_disconnect("wait returned status %04x.", status);
1751 /* disconnect channel */
1752 debug("session_exit_message: release channel %d", s->chanid);
1753 channel_cancel_cleanup(s->chanid);
1755 * emulate a write failure with 'chan_write_failed', nobody will be
1756 * interested in data we write.
1757 * Note that we must not call 'chan_read_failed', since there could
1758 * be some more data waiting in the pipe.
1760 if (c->ostate != CHAN_OUTPUT_CLOSED)
1761 chan_write_failed(c);
1766 session_close(Session *s)
1768 debug("session_close: session %d pid %d", s->self, s->pid);
1769 if (s->ttyfd != -1) {
1770 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1771 session_pty_cleanup(s);
1777 if (s->auth_display)
1778 xfree(s->auth_display);
1780 xfree(s->auth_data);
1782 xfree(s->auth_proto);
1784 session_proctitle(s);
1788 session_close_by_pid(pid_t pid, int status)
1790 Session *s = session_by_pid(pid);
1792 debug("session_close_by_pid: no session for pid %d", pid);
1795 if (s->chanid != -1)
1796 session_exit_message(s, status);
1801 * this is called when a channel dies before
1802 * the session 'child' itself dies
1805 session_close_by_channel(int id, void *arg)
1807 Session *s = session_by_channel(id);
1809 debug("session_close_by_channel: no session for id %d", id);
1812 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1814 debug("session_close_by_channel: channel %d: has child", id);
1816 * delay detach of session, but release pty, since
1817 * the fd's to the child are already closed
1819 if (s->ttyfd != -1) {
1820 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1821 session_pty_cleanup(s);
1825 /* detach by removing callback */
1826 channel_cancel_cleanup(s->chanid);
1832 session_destroy_all(void)
1835 for (i = 0; i < MAX_SESSIONS; i++) {
1836 Session *s = &sessions[i];
1843 session_tty_list(void)
1845 static char buf[1024];
1848 for (i = 0; i < MAX_SESSIONS; i++) {
1849 Session *s = &sessions[i];
1850 if (s->used && s->ttyfd != -1) {
1852 strlcat(buf, ",", sizeof buf);
1853 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1857 strlcpy(buf, "notty", sizeof buf);
1862 session_proctitle(Session *s)
1865 error("no user for session %d", s->self);
1867 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1871 session_setup_x11fwd(Session *s)
1874 char display[512], auth_display[512];
1875 char hostname[MAXHOSTNAMELEN];
1877 if (no_x11_forwarding_flag) {
1878 packet_send_debug("X11 forwarding disabled in user configuration file.");
1881 if (!options.x11_forwarding) {
1882 debug("X11 forwarding disabled in server configuration file.");
1885 if (!options.xauth_location ||
1886 (stat(options.xauth_location, &st) == -1)) {
1887 packet_send_debug("No xauth program; cannot forward with spoofing.");
1890 if (options.use_login) {
1891 packet_send_debug("X11 forwarding disabled; "
1892 "not compatible with UseLogin=yes.");
1895 if (s->display != NULL) {
1896 debug("X11 display already set.");
1899 s->display_number = x11_create_display_inet(options.x11_display_offset,
1900 options.x11_use_localhost, s->single_connection);
1901 if (s->display_number == -1) {
1902 debug("x11_create_display_inet failed.");
1906 /* Set up a suitable value for the DISPLAY variable. */
1907 if (gethostname(hostname, sizeof(hostname)) < 0)
1908 fatal("gethostname: %.100s", strerror(errno));
1910 * auth_display must be used as the displayname when the
1911 * authorization entry is added with xauth(1). This will be
1912 * different than the DISPLAY string for localhost displays.
1914 if (options.x11_use_localhost) {
1915 snprintf(display, sizeof display, "localhost:%d.%d",
1916 s->display_number, s->screen);
1917 snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1918 s->display_number, s->screen);
1919 s->display = xstrdup(display);
1920 s->auth_display = xstrdup(auth_display);
1922 #ifdef IPADDR_IN_DISPLAY
1924 struct in_addr my_addr;
1926 he = gethostbyname(hostname);
1928 error("Can't get IP address for X11 DISPLAY.");
1929 packet_send_debug("Can't get IP address for X11 DISPLAY.");
1932 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1933 snprintf(display, sizeof display, "%.50s:%d.%d", inet_ntoa(my_addr),
1934 s->display_number, s->screen);
1936 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1937 s->display_number, s->screen);
1939 s->display = xstrdup(display);
1940 s->auth_display = xstrdup(display);
1947 do_authenticated2(Authctxt *authctxt)
1949 server_loop2(authctxt);
1951 ssh_gssapi_cleanup_creds(NULL);