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"
60 #include "monitor_wrap.h"
64 #include <sys/cygwin.h>
65 #define is_winnt (GetVersion() < 0x80000000)
69 extern int use_privsep;
74 Session *session_new(void);
75 void session_set_fds(Session *, int, int, int);
76 void session_pty_cleanup(void *);
77 void session_proctitle(Session *);
78 int session_setup_x11fwd(Session *);
79 void do_exec_pty(Session *, const char *);
80 void do_exec_no_pty(Session *, const char *);
81 void do_exec(Session *, const char *);
82 void do_login(Session *, const char *);
83 #ifdef LOGIN_NEEDS_UTMPX
84 static void do_pre_login(Session *s);
86 void do_child(Session *, const char *);
88 int check_quietlogin(Session *, const char *);
90 static void do_authenticated1(Authctxt *);
91 static void do_authenticated2(Authctxt *);
93 static int session_pty_req(Session *);
96 extern ServerOptions options;
97 extern char *__progname;
98 extern int log_stderr;
99 extern int debug_flag;
100 extern u_int utmp_len;
101 extern int startup_pipe;
102 extern void destroy_sensitive_data(void);
104 /* original command from peer. */
105 const char *original_command = NULL;
108 #define MAX_SESSIONS 10
109 Session sessions[MAX_SESSIONS];
111 #ifdef WITH_AIXAUTHENTICATE
113 #endif /* WITH_AIXAUTHENTICATE */
115 #ifdef HAVE_LOGIN_CAP
116 static login_cap_t *lc;
120 do_authenticated(Authctxt *authctxt)
123 * Cancel the alarm we set to limit the time taken for
127 if (startup_pipe != -1) {
131 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
132 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
133 error("unable to get login class");
137 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
138 packet_disconnect("Approval failure for %s",
139 authctxt->pw->pw_name);
143 #ifdef WITH_AIXAUTHENTICATE
144 /* We don't have a pty yet, so just label the line as "ssh" */
145 if (loginsuccess(authctxt->user,
146 get_canonical_hostname(options.verify_reverse_mapping),
147 "ssh", &aixloginmsg) < 0)
149 #endif /* WITH_AIXAUTHENTICATE */
151 /* setup the channel layer */
152 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
153 channel_permit_all_opens();
156 do_authenticated2(authctxt);
158 do_authenticated1(authctxt);
160 /* remove agent socket */
161 if (auth_get_socket_name())
162 auth_sock_cleanup_proc(authctxt->pw);
164 if (options.kerberos_ticket_cleanup)
165 krb4_cleanup_proc(authctxt);
168 if (options.kerberos_ticket_cleanup)
169 krb5_cleanup_proc(authctxt);
174 * Prepares for an interactive session. This is called after the user has
175 * been successfully authenticated. During this message exchange, pseudo
176 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
177 * are requested, etc.
180 do_authenticated1(Authctxt *authctxt)
184 int success, type, screen_flag;
185 int compression_level = 0, enable_compression_after_reply = 0;
186 u_int proto_len, data_len, dlen;
189 s->authctxt = authctxt;
190 s->pw = authctxt->pw;
193 * We stay in this loop until the client requests to execute a shell
199 /* Get a packet from the client. */
200 type = packet_read();
202 /* Process the packet. */
204 case SSH_CMSG_REQUEST_COMPRESSION:
205 compression_level = packet_get_int();
207 if (compression_level < 1 || compression_level > 9) {
208 packet_send_debug("Received illegal compression level %d.",
212 /* Enable compression after we have responded with SUCCESS. */
213 enable_compression_after_reply = 1;
217 case SSH_CMSG_REQUEST_PTY:
218 success = session_pty_req(s);
221 case SSH_CMSG_X11_REQUEST_FORWARDING:
222 s->auth_proto = packet_get_string(&proto_len);
223 s->auth_data = packet_get_string(&data_len);
225 screen_flag = packet_get_protocol_flags() &
226 SSH_PROTOFLAG_SCREEN_NUMBER;
227 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
229 if (packet_remaining() == 4) {
231 debug2("Buggy client: "
232 "X11 screen flag missing");
233 s->screen = packet_get_int();
238 success = session_setup_x11fwd(s);
240 xfree(s->auth_proto);
242 s->auth_proto = NULL;
247 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
248 if (no_agent_forwarding_flag || compat13) {
249 debug("Authentication agent forwarding not permitted for this authentication.");
252 debug("Received authentication agent forwarding request.");
253 success = auth_input_request_forwarding(s->pw);
256 case SSH_CMSG_PORT_FORWARD_REQUEST:
257 if (no_port_forwarding_flag) {
258 debug("Port forwarding not permitted for this authentication.");
261 if (!options.allow_tcp_forwarding) {
262 debug("Port forwarding not permitted.");
265 debug("Received TCP/IP port forwarding request.");
266 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
270 case SSH_CMSG_MAX_PACKET_SIZE:
271 if (packet_set_maxsize(packet_get_int()) > 0)
275 #if defined(AFS) || defined(KRB5)
276 case SSH_CMSG_HAVE_KERBEROS_TGT:
277 if (!options.kerberos_tgt_passing) {
278 verbose("Kerberos TGT passing disabled.");
280 char *kdata = packet_get_string(&dlen);
283 /* XXX - 0x41, see creds_to_radix version */
284 if (kdata[0] != 0x41) {
290 if (auth_krb5_tgt(s->authctxt, &tgt))
293 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
297 if (auth_krb4_tgt(s->authctxt, kdata))
300 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
306 #endif /* AFS || KRB5 */
309 case SSH_CMSG_HAVE_AFS_TOKEN:
310 if (!options.afs_token_passing || !k_hasafs()) {
311 verbose("AFS token passing disabled.");
313 /* Accept AFS token. */
314 char *token = packet_get_string(&dlen);
317 if (auth_afs_token(s->authctxt, token))
320 verbose("AFS token refused for %.100s",
327 case SSH_CMSG_EXEC_SHELL:
328 case SSH_CMSG_EXEC_CMD:
329 if (type == SSH_CMSG_EXEC_CMD) {
330 command = packet_get_string(&dlen);
331 debug("Exec command '%.500s'", command);
343 * Any unknown messages in this phase are ignored,
344 * and a failure message is returned.
346 log("Unknown packet type received after authentication: %d", type);
348 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
352 /* Enable compression now that we have replied if appropriate. */
353 if (enable_compression_after_reply) {
354 enable_compression_after_reply = 0;
355 packet_start_compression(compression_level);
361 * This is called to fork and execute a command when we have no tty. This
362 * will call do_child from the child, and server_loop from the parent after
363 * setting up file descriptors and such.
366 do_exec_no_pty(Session *s, const char *command)
371 int pin[2], pout[2], perr[2];
372 /* Allocate pipes for communicating with the program. */
373 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
374 packet_disconnect("Could not create pipes: %.100s",
376 #else /* USE_PIPES */
377 int inout[2], err[2];
378 /* Uses socket pairs to communicate with the program. */
379 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
380 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
381 packet_disconnect("Could not create socket pairs: %.100s",
383 #endif /* USE_PIPES */
385 fatal("do_exec_no_pty: no session");
387 session_proctitle(s);
390 do_pam_session(s->pw->pw_name, NULL);
392 if (is_pam_password_change_required())
393 packet_disconnect("Password change required but no "
397 /* Fork the child. */
398 if ((pid = fork()) == 0) {
399 /* Child. Reinitialize the log since the pid has changed. */
400 log_init(__progname, options.log_level, options.log_facility, log_stderr);
403 * Create a new session and process group since the 4.4BSD
404 * setlogin() affects the entire process group.
407 error("setsid failed: %.100s", strerror(errno));
411 * Redirect stdin. We close the parent side of the socket
412 * pair, and make the child side the standard input.
415 if (dup2(pin[0], 0) < 0)
416 perror("dup2 stdin");
419 /* Redirect stdout. */
421 if (dup2(pout[1], 1) < 0)
422 perror("dup2 stdout");
425 /* Redirect stderr. */
427 if (dup2(perr[1], 2) < 0)
428 perror("dup2 stderr");
430 #else /* USE_PIPES */
432 * Redirect stdin, stdout, and stderr. Stdin and stdout will
433 * use the same socket, as some programs (particularly rdist)
434 * seem to depend on it.
438 if (dup2(inout[0], 0) < 0) /* stdin */
439 perror("dup2 stdin");
440 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
441 perror("dup2 stdout");
442 if (dup2(err[0], 2) < 0) /* stderr */
443 perror("dup2 stderr");
444 #endif /* USE_PIPES */
446 /* Do processing for the child (exec command etc). */
447 do_child(s, command);
452 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
455 packet_disconnect("fork failed: %.100s", strerror(errno));
457 /* Set interactive/non-interactive mode. */
458 packet_set_interactive(s->display != NULL);
460 /* We are the parent. Close the child sides of the pipes. */
466 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
468 /* Enter the interactive session. */
469 server_loop(pid, pin[1], pout[0], perr[0]);
470 /* server_loop has closed pin[1], pout[0], and perr[0]. */
472 #else /* USE_PIPES */
473 /* We are the parent. Close the child sides of the socket pairs. */
478 * Enter the interactive session. Note: server_loop must be able to
479 * handle the case that fdin and fdout are the same.
482 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
484 server_loop(pid, inout[1], inout[1], err[1]);
485 /* server_loop has closed inout[1] and err[1]. */
487 #endif /* USE_PIPES */
491 * This is called to fork and execute a command when we have a tty. This
492 * will call do_child from the child, and server_loop from the parent after
493 * setting up file descriptors, controlling tty, updating wtmp, utmp,
494 * lastlog, and other such operations.
497 do_exec_pty(Session *s, const char *command)
499 int fdout, ptyfd, ttyfd, ptymaster;
503 fatal("do_exec_pty: no session");
508 do_pam_session(s->pw->pw_name, s->tty);
512 /* Fork the child. */
513 if ((pid = fork()) == 0) {
515 /* Child. Reinitialize the log because the pid has changed. */
516 log_init(__progname, options.log_level, options.log_facility, log_stderr);
517 /* Close the master side of the pseudo tty. */
520 /* Make the pseudo tty our controlling tty. */
521 pty_make_controlling_tty(&ttyfd, s->tty);
523 /* Redirect stdin/stdout/stderr from the pseudo tty. */
524 if (dup2(ttyfd, 0) < 0)
525 error("dup2 stdin: %s", strerror(errno));
526 if (dup2(ttyfd, 1) < 0)
527 error("dup2 stdout: %s", strerror(errno));
528 if (dup2(ttyfd, 2) < 0)
529 error("dup2 stderr: %s", strerror(errno));
531 /* Close the extra descriptor for the pseudo tty. */
534 /* record login, etc. similar to login(1) */
536 if (!(options.use_login && command == NULL))
537 do_login(s, command);
538 # ifdef LOGIN_NEEDS_UTMPX
544 /* Do common processing for the child, such as execing the command. */
545 do_child(s, command);
550 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
553 packet_disconnect("fork failed: %.100s", strerror(errno));
556 /* Parent. Close the slave side of the pseudo tty. */
560 * Create another descriptor of the pty master side for use as the
561 * standard input. We could use the original descriptor, but this
562 * simplifies code in server_loop. The descriptor is bidirectional.
566 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
568 /* we keep a reference to the pty master */
569 ptymaster = dup(ptyfd);
571 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
572 s->ptymaster = ptymaster;
574 /* Enter interactive session. */
575 packet_set_interactive(1);
577 session_set_fds(s, ptyfd, fdout, -1);
579 server_loop(pid, ptyfd, fdout, -1);
580 /* server_loop _has_ closed ptyfd and fdout. */
584 #ifdef LOGIN_NEEDS_UTMPX
586 do_pre_login(Session *s)
589 struct sockaddr_storage from;
590 pid_t pid = getpid();
593 * Get IP address of client. If the connection is not a socket, let
594 * the address be 0.0.0.0.
596 memset(&from, 0, sizeof(from));
597 if (packet_connection_is_on_socket()) {
598 fromlen = sizeof(from);
599 if (getpeername(packet_get_connection_in(),
600 (struct sockaddr *) & from, &fromlen) < 0) {
601 debug("getpeername: %.100s", strerror(errno));
606 record_utmp_only(pid, s->tty, s->pw->pw_name,
607 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
608 (struct sockaddr *)&from);
613 * This is called to fork and execute a command. If another command is
614 * to be forced, execute that instead.
617 do_exec(Session *s, const char *command)
619 if (forced_command) {
620 original_command = command;
621 command = forced_command;
622 debug("Forced command '%.900s'", command);
626 do_exec_pty(s, command);
628 do_exec_no_pty(s, command);
630 original_command = NULL;
634 /* administrative, login(1)-like work */
636 do_login(Session *s, const char *command)
639 char hostname[MAXHOSTNAMELEN];
641 struct sockaddr_storage from;
642 time_t last_login_time;
643 struct passwd * pw = s->pw;
644 pid_t pid = getpid();
647 * Get IP address of client. If the connection is not a socket, let
648 * the address be 0.0.0.0.
650 memset(&from, 0, sizeof(from));
651 if (packet_connection_is_on_socket()) {
652 fromlen = sizeof(from);
653 if (getpeername(packet_get_connection_in(),
654 (struct sockaddr *) & from, &fromlen) < 0) {
655 debug("getpeername: %.100s", strerror(errno));
660 /* Get the time and hostname when the user last logged in. */
661 if (options.print_lastlog) {
663 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
664 hostname, sizeof(hostname));
667 /* Record that there was a login on that tty from the remote host. */
668 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
669 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
670 (struct sockaddr *)&from);
674 * If password change is needed, do it now.
675 * This needs to occur before the ~/.hushlogin check.
677 if (is_pam_password_change_required()) {
678 print_pam_messages();
683 if (check_quietlogin(s, command))
687 if (!is_pam_password_change_required())
688 print_pam_messages();
690 #ifdef WITH_AIXAUTHENTICATE
691 if (aixloginmsg && *aixloginmsg)
692 printf("%s\n", aixloginmsg);
693 #endif /* WITH_AIXAUTHENTICATE */
695 if (options.print_lastlog && last_login_time != 0) {
696 time_string = ctime(&last_login_time);
697 if (strchr(time_string, '\n'))
698 *strchr(time_string, '\n') = 0;
699 if (strcmp(hostname, "") == 0)
700 printf("Last login: %s\r\n", time_string);
702 printf("Last login: %s from %s\r\n", time_string, hostname);
709 * Display the message of the day.
717 if (options.print_motd) {
718 #ifdef HAVE_LOGIN_CAP
719 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
722 f = fopen("/etc/motd", "r");
725 while (fgets(buf, sizeof(buf), f))
734 * Check for quiet login, either .hushlogin or command given.
737 check_quietlogin(Session *s, const char *command)
740 struct passwd *pw = s->pw;
743 /* Return 1 if .hushlogin exists or a command given. */
746 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
747 #ifdef HAVE_LOGIN_CAP
748 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
751 if (stat(buf, &st) >= 0)
758 * Sets the value of the given variable in the environment. If the variable
759 * already exists, its value is overriden.
762 child_set_env(char ***envp, u_int *envsizep, const char *name,
769 * Find the slot where the value should be stored. If the variable
770 * already exists, we reuse the slot; otherwise we append a new slot
771 * at the end of the array, expanding if necessary.
774 namelen = strlen(name);
775 for (i = 0; env[i]; i++)
776 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
779 /* Reuse the slot. */
782 /* New variable. Expand if necessary. */
783 if (i >= (*envsizep) - 1) {
785 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
787 /* Need to set the NULL pointer at end of array beyond the new slot. */
791 /* Allocate space and format the variable in the appropriate slot. */
792 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
793 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
797 * Reads environment variables from the given file and adds/overrides them
798 * into the environment. If the file does not exist, this does nothing.
799 * Otherwise, it must consist of empty lines, comments (line starts with '#')
800 * and assignments of the form name=value. No other forms are allowed.
803 read_environment_file(char ***env, u_int *envsize,
804 const char *filename)
810 f = fopen(filename, "r");
814 while (fgets(buf, sizeof(buf), f)) {
815 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
817 if (!*cp || *cp == '#' || *cp == '\n')
819 if (strchr(cp, '\n'))
820 *strchr(cp, '\n') = '\0';
821 value = strchr(cp, '=');
823 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
827 * Replace the equals sign by nul, and advance value to
832 child_set_env(env, envsize, cp, value);
837 void copy_environment(char **source, char ***env, u_int *envsize)
839 char *var_name, *var_val;
845 for(i = 0; source[i] != NULL; i++) {
846 var_name = xstrdup(source[i]);
847 if ((var_val = strstr(var_name, "=")) == NULL) {
853 debug3("Copy environment: %s=%s", var_name, var_val);
854 child_set_env(env, envsize, var_name, var_val);
861 do_setup_env(Session *s, const char *shell)
866 struct passwd *pw = s->pw;
868 /* Initialize the environment. */
870 env = xmalloc(envsize * sizeof(char *));
875 * The Windows environment contains some setting which are
876 * important for a running system. They must not be dropped.
878 copy_environment(environ, &env, &envsize);
881 if (!options.use_login) {
882 /* Set basic environment. */
883 child_set_env(&env, &envsize, "USER", pw->pw_name);
884 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
885 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
886 #ifdef HAVE_LOGIN_CAP
887 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
888 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
889 #else /* HAVE_LOGIN_CAP */
892 * There's no standard path on Windows. The path contains
893 * important components pointing to the system directories,
894 * needed for loading shared libraries. So the path better
895 * remains intact here.
897 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
898 # endif /* HAVE_CYGWIN */
899 #endif /* HAVE_LOGIN_CAP */
901 snprintf(buf, sizeof buf, "%.200s/%.50s",
902 _PATH_MAILDIR, pw->pw_name);
903 child_set_env(&env, &envsize, "MAIL", buf);
905 /* Normal systems set SHELL by default. */
906 child_set_env(&env, &envsize, "SHELL", shell);
909 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
911 /* Set custom environment options from RSA authentication. */
912 if (!options.use_login) {
913 while (custom_environment) {
914 struct envstring *ce = custom_environment;
917 for (i = 0; s[i] != '=' && s[i]; i++)
921 child_set_env(&env, &envsize, s, s + i + 1);
923 custom_environment = ce->next;
929 snprintf(buf, sizeof buf, "%.50s %d %d",
930 get_remote_ipaddr(), get_remote_port(), get_local_port());
931 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
934 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
936 child_set_env(&env, &envsize, "TERM", s->term);
938 child_set_env(&env, &envsize, "DISPLAY", s->display);
939 if (original_command)
940 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
947 if ((cp = getenv("AUTHSTATE")) != NULL)
948 child_set_env(&env, &envsize, "AUTHSTATE", cp);
949 if ((cp = getenv("KRB5CCNAME")) != NULL)
950 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
951 read_environment_file(&env, &envsize, "/etc/environment");
955 if (s->authctxt->krb4_ticket_file)
956 child_set_env(&env, &envsize, "KRBTKFILE",
957 s->authctxt->krb4_ticket_file);
960 if (s->authctxt->krb5_ticket_file)
961 child_set_env(&env, &envsize, "KRB5CCNAME",
962 s->authctxt->krb5_ticket_file);
965 /* Pull in any environment variables that may have been set by PAM. */
966 copy_environment(fetch_pam_environment(), &env, &envsize);
969 if (auth_get_socket_name() != NULL)
970 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
971 auth_get_socket_name());
973 /* read $HOME/.ssh/environment. */
974 if (!options.use_login) {
975 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
977 read_environment_file(&env, &envsize, buf);
980 /* dump the environment */
981 fprintf(stderr, "Environment:\n");
982 for (i = 0; env[i]; i++)
983 fprintf(stderr, " %.200s\n", env[i]);
989 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
990 * first in this order).
993 do_rc_files(Session *s, const char *shell)
1001 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1003 /* ignore _PATH_SSH_USER_RC for subsystems */
1004 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1005 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1006 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1008 fprintf(stderr, "Running %s\n", cmd);
1009 f = popen(cmd, "w");
1012 fprintf(f, "%s %s\n", s->auth_proto,
1016 fprintf(stderr, "Could not run %s\n",
1018 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1020 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1021 _PATH_SSH_SYSTEM_RC);
1022 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1025 fprintf(f, "%s %s\n", s->auth_proto,
1029 fprintf(stderr, "Could not run %s\n",
1030 _PATH_SSH_SYSTEM_RC);
1031 } else if (do_xauth && options.xauth_location != NULL) {
1032 /* Add authority data to .Xauthority if appropriate. */
1035 "Running %.100s add "
1036 "%.100s %.100s %.100s\n",
1037 options.xauth_location, s->auth_display,
1038 s->auth_proto, s->auth_data);
1040 snprintf(cmd, sizeof cmd, "%s -q -",
1041 options.xauth_location);
1042 f = popen(cmd, "w");
1044 fprintf(f, "add %s %s %s\n",
1045 s->auth_display, s->auth_proto,
1049 fprintf(stderr, "Could not run %s\n",
1056 do_nologin(struct passwd *pw)
1061 #ifdef HAVE_LOGIN_CAP
1062 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1063 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1064 _PATH_NOLOGIN), "r");
1067 f = fopen(_PATH_NOLOGIN, "r");
1070 /* /etc/nologin exists. Print its contents and exit. */
1071 while (fgets(buf, sizeof(buf), f))
1078 /* Set login name, uid, gid, and groups. */
1080 do_setusercontext(struct passwd *pw)
1084 #else /* HAVE_CYGWIN */
1085 if (getuid() == 0 || geteuid() == 0) {
1086 #endif /* HAVE_CYGWIN */
1087 #ifdef HAVE_GETUSERATTR
1088 set_limits_from_userattr(pw->pw_name);
1089 #endif /* HAVE_GETUSERATTR */
1090 #ifdef HAVE_LOGIN_CAP
1091 if (setusercontext(lc, pw, pw->pw_uid,
1092 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1093 perror("unable to set user context");
1097 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1098 /* Sets login uid for accounting */
1099 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1100 error("setluid: %s", strerror(errno));
1101 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1103 if (setlogin(pw->pw_name) < 0)
1104 error("setlogin failed: %s", strerror(errno));
1105 if (setgid(pw->pw_gid) < 0) {
1109 /* Initialize the group list. */
1110 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1111 perror("initgroups");
1117 * PAM credentials may take the form of supplementary groups.
1118 * These will have been wiped by the above initgroups() call.
1119 * Reestablish them here.
1122 # endif /* USE_PAM */
1123 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1124 irix_setusercontext(pw);
1125 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1126 /* Permanently switch to the desired uid. */
1127 permanently_set_uid(pw);
1130 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1131 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1135 * Performs common processing for the child, such as setting up the
1136 * environment, closing extra file descriptors, setting the user and group
1137 * ids, and executing the command or shell.
1140 do_child(Session *s, const char *command)
1142 extern char **environ;
1145 const char *shell, *shell0, *hostname = NULL;
1146 struct passwd *pw = s->pw;
1149 /* remove hostkey from the child's memory */
1150 destroy_sensitive_data();
1152 /* login(1) is only called if we execute the login shell */
1153 if (options.use_login && command != NULL)
1154 options.use_login = 0;
1157 * Login(1) does this as well, and it needs uid 0 for the "-h"
1158 * switch, so we let login(1) to this for us.
1160 if (!options.use_login) {
1162 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1163 if (!check_quietlogin(s, command))
1165 #else /* HAVE_OSF_SIA */
1168 aix_usrinfo(pw, s->tty, s->ttyfd);
1170 do_setusercontext(pw);
1171 #endif /* HAVE_OSF_SIA */
1175 * Get the shell from the password data. An empty shell field is
1176 * legal, and means /bin/sh.
1178 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1179 #ifdef HAVE_LOGIN_CAP
1180 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1183 env = do_setup_env(s, shell);
1185 /* we have to stash the hostname before we close our socket. */
1186 if (options.use_login)
1187 hostname = get_remote_name_or_ip(utmp_len,
1188 options.verify_reverse_mapping);
1190 * Close the connection descriptors; note that this is the child, and
1191 * the server will still have the socket open, and it is important
1192 * that we do not shutdown it. Note that the descriptors cannot be
1193 * closed before building the environment, as we call
1194 * get_remote_ipaddr there.
1196 if (packet_get_connection_in() == packet_get_connection_out())
1197 close(packet_get_connection_in());
1199 close(packet_get_connection_in());
1200 close(packet_get_connection_out());
1203 * Close all descriptors related to channels. They will still remain
1204 * open in the parent.
1206 /* XXX better use close-on-exec? -markus */
1207 channel_close_all();
1210 * Close any extra file descriptors. Note that there may still be
1211 * descriptors left by system functions. They will be closed later.
1216 * Close any extra open file descriptors so that we don\'t have them
1217 * hanging around in clients. Note that we want to do this after
1218 * initgroups, because at least on Solaris 2.3 it leaves file
1221 for (i = 3; i < 64; i++)
1225 * Must take new environment into use so that .ssh/rc,
1226 * /etc/ssh/sshrc and xauth are run in the proper environment.
1231 /* Try to get AFS tokens for the local cell. */
1235 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1236 krb_afslog(cell, 0);
1242 /* Change current directory to the user\'s home directory. */
1243 if (chdir(pw->pw_dir) < 0) {
1244 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1245 pw->pw_dir, strerror(errno));
1246 #ifdef HAVE_LOGIN_CAP
1247 if (login_getcapbool(lc, "requirehome", 0))
1252 if (!options.use_login)
1253 do_rc_files(s, shell);
1255 /* restore SIGPIPE for child */
1256 signal(SIGPIPE, SIG_DFL);
1258 if (options.use_login) {
1259 /* Launch login(1). */
1261 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1262 #ifdef LOGIN_NEEDS_TERM
1263 (s->term ? s->term : "unknown"),
1264 #endif /* LOGIN_NEEDS_TERM */
1265 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1267 /* Login couldn't be executed, die. */
1273 /* Get the last component of the shell name. */
1274 if ((shell0 = strrchr(shell, '/')) != NULL)
1280 * If we have no command, execute the shell. In this case, the shell
1281 * name to be passed in argv[0] is preceded by '-' to indicate that
1282 * this is a login shell.
1287 /* Start the shell. Set initial character to '-'. */
1290 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1291 >= sizeof(argv0) - 1) {
1297 /* Execute the shell. */
1300 execve(shell, argv, env);
1302 /* Executing the shell failed. */
1307 * Execute the command using the user's shell. This uses the -c
1308 * option to execute the command.
1310 argv[0] = (char *) shell0;
1312 argv[2] = (char *) command;
1314 execve(shell, argv, env);
1323 static int did_init = 0;
1325 debug("session_new: init");
1326 for (i = 0; i < MAX_SESSIONS; i++) {
1327 sessions[i].used = 0;
1331 for (i = 0; i < MAX_SESSIONS; i++) {
1332 Session *s = &sessions[i];
1334 memset(s, 0, sizeof(*s));
1340 debug("session_new: session %d", i);
1351 for (i = 0; i < MAX_SESSIONS; i++) {
1352 Session *s = &sessions[i];
1353 debug("dump: used %d session %d %p channel %d pid %d",
1363 session_open(Authctxt *authctxt, int chanid)
1365 Session *s = session_new();
1366 debug("session_open: channel %d", chanid);
1368 error("no more sessions");
1371 s->authctxt = authctxt;
1372 s->pw = authctxt->pw;
1374 fatal("no user for session %d", s->self);
1375 debug("session_open: session %d: link with channel %d", s->self, chanid);
1381 session_by_channel(int id)
1384 for (i = 0; i < MAX_SESSIONS; i++) {
1385 Session *s = &sessions[i];
1386 if (s->used && s->chanid == id) {
1387 debug("session_by_channel: session %d channel %d", i, id);
1391 debug("session_by_channel: unknown channel %d", id);
1397 session_by_pid(pid_t pid)
1400 debug("session_by_pid: pid %d", pid);
1401 for (i = 0; i < MAX_SESSIONS; i++) {
1402 Session *s = &sessions[i];
1403 if (s->used && s->pid == pid)
1406 error("session_by_pid: unknown pid %d", pid);
1412 session_window_change_req(Session *s)
1414 s->col = packet_get_int();
1415 s->row = packet_get_int();
1416 s->xpixel = packet_get_int();
1417 s->ypixel = packet_get_int();
1419 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1424 session_pty_req(Session *s)
1431 debug("Allocating a pty not permitted for this authentication.");
1434 if (s->ttyfd != -1) {
1435 packet_disconnect("Protocol error: you already have a pty.");
1439 s->term = packet_get_string(&len);
1442 s->col = packet_get_int();
1443 s->row = packet_get_int();
1445 s->row = packet_get_int();
1446 s->col = packet_get_int();
1448 s->xpixel = packet_get_int();
1449 s->ypixel = packet_get_int();
1451 if (strcmp(s->term, "") == 0) {
1456 /* Allocate a pty and open it. */
1457 debug("Allocating pty.");
1459 res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1462 pty_setowner(s->pw, s->tty);
1464 res = mm_pty_allocown(mm_recvfd,
1465 &s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1472 error("session_pty_req: session %d alloc failed", s->self);
1475 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1477 /* for SSH1 the tty modes length is not given */
1479 n_bytes = packet_remaining();
1480 tty_parse_modes(s->ttyfd, &n_bytes);
1483 * Add a cleanup function to clear the utmp entry and record logout
1484 * time in case we call fatal() (e.g., the connection gets closed).
1486 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1488 /* Set window size from the packet. */
1489 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1492 session_proctitle(s);
1497 session_subsystem_req(Session *s)
1502 char *cmd, *subsys = packet_get_string(&len);
1506 log("subsystem request for %.100s", subsys);
1508 for (i = 0; i < options.num_subsystems; i++) {
1509 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1510 cmd = options.subsystem_command[i];
1511 if (stat(cmd, &st) < 0) {
1512 error("subsystem: cannot stat %s: %s", cmd,
1516 debug("subsystem: exec() %s", cmd);
1517 s->is_subsystem = 1;
1525 log("subsystem request for %.100s failed, subsystem not found",
1533 session_x11_req(Session *s)
1537 s->single_connection = packet_get_char();
1538 s->auth_proto = packet_get_string(NULL);
1539 s->auth_data = packet_get_string(NULL);
1540 s->screen = packet_get_int();
1543 success = session_setup_x11fwd(s);
1545 xfree(s->auth_proto);
1546 xfree(s->auth_data);
1547 s->auth_proto = NULL;
1548 s->auth_data = NULL;
1554 session_shell_req(Session *s)
1562 session_exec_req(Session *s)
1565 char *command = packet_get_string(&len);
1567 do_exec(s, command);
1573 session_auth_agent_req(Session *s)
1575 static int called = 0;
1577 if (no_agent_forwarding_flag) {
1578 debug("session_auth_agent_req: no_agent_forwarding_flag");
1585 return auth_input_request_forwarding(s->pw);
1590 session_input_channel_req(Channel *c, const char *rtype)
1595 if ((s = session_by_channel(c->self)) == NULL) {
1596 log("session_input_channel_req: no session %d req %.100s",
1600 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1603 * a session is in LARVAL state until a shell, a command
1604 * or a subsystem is executed
1606 if (c->type == SSH_CHANNEL_LARVAL) {
1607 if (strcmp(rtype, "shell") == 0) {
1608 success = session_shell_req(s);
1609 } else if (strcmp(rtype, "exec") == 0) {
1610 success = session_exec_req(s);
1611 } else if (strcmp(rtype, "pty-req") == 0) {
1612 success = session_pty_req(s);
1613 } else if (strcmp(rtype, "x11-req") == 0) {
1614 success = session_x11_req(s);
1615 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1616 success = session_auth_agent_req(s);
1617 } else if (strcmp(rtype, "subsystem") == 0) {
1618 success = session_subsystem_req(s);
1621 if (strcmp(rtype, "window-change") == 0) {
1622 success = session_window_change_req(s);
1628 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1631 fatal("session_set_fds: called for proto != 2.0");
1633 * now that have a child and a pipe to the child,
1634 * we can activate our channel and register the fd's
1636 if (s->chanid == -1)
1637 fatal("no channel for session %d", s->self);
1638 channel_set_fds(s->chanid,
1640 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1642 CHAN_SES_WINDOW_DEFAULT);
1646 * Function to perform pty cleanup. Also called if we get aborted abnormally
1647 * (e.g., due to a dropped connection).
1650 session_pty_cleanup(void *session)
1652 Session *s = session;
1655 error("session_pty_cleanup: no session");
1661 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1663 /* Record that the user has logged out. */
1665 record_logout(s->pid, s->tty, s->pw->pw_name);
1667 /* Release the pseudo-tty. */
1668 pty_release(s->tty);
1671 * Close the server side of the socket pairs. We must do this after
1672 * the pty cleanup, so that another process doesn't get this pty
1673 * while we're still cleaning up.
1675 if (close(s->ptymaster) < 0)
1676 error("close(s->ptymaster): %s", strerror(errno));
1678 /* unlink pty from session */
1683 session_exit_message(Session *s, int status)
1687 if ((c = channel_lookup(s->chanid)) == NULL)
1688 fatal("session_exit_message: session %d: no channel %d",
1689 s->self, s->chanid);
1690 debug("session_exit_message: session %d channel %d pid %d",
1691 s->self, s->chanid, s->pid);
1693 if (WIFEXITED(status)) {
1694 channel_request_start(s->chanid, "exit-status", 0);
1695 packet_put_int(WEXITSTATUS(status));
1697 } else if (WIFSIGNALED(status)) {
1698 channel_request_start(s->chanid, "exit-signal", 0);
1699 packet_put_int(WTERMSIG(status));
1701 packet_put_char(WCOREDUMP(status));
1702 #else /* WCOREDUMP */
1704 #endif /* WCOREDUMP */
1705 packet_put_cstring("");
1706 packet_put_cstring("");
1709 /* Some weird exit cause. Just exit. */
1710 packet_disconnect("wait returned status %04x.", status);
1713 /* disconnect channel */
1714 debug("session_exit_message: release channel %d", s->chanid);
1715 channel_cancel_cleanup(s->chanid);
1717 * emulate a write failure with 'chan_write_failed', nobody will be
1718 * interested in data we write.
1719 * Note that we must not call 'chan_read_failed', since there could
1720 * be some more data waiting in the pipe.
1722 if (c->ostate != CHAN_OUTPUT_CLOSED)
1723 chan_write_failed(c);
1728 session_close(Session *s)
1730 debug("session_close: session %d pid %d", s->self, s->pid);
1731 if (s->ttyfd != -1) {
1732 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1733 session_pty_cleanup(s);
1739 if (s->auth_display)
1740 xfree(s->auth_display);
1742 xfree(s->auth_data);
1744 xfree(s->auth_proto);
1746 session_proctitle(s);
1750 session_close_by_pid(pid_t pid, int status)
1752 Session *s = session_by_pid(pid);
1754 debug("session_close_by_pid: no session for pid %d", pid);
1757 if (s->chanid != -1)
1758 session_exit_message(s, status);
1763 * this is called when a channel dies before
1764 * the session 'child' itself dies
1767 session_close_by_channel(int id, void *arg)
1769 Session *s = session_by_channel(id);
1771 debug("session_close_by_channel: no session for id %d", id);
1774 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1776 debug("session_close_by_channel: channel %d: has child", id);
1778 * delay detach of session, but release pty, since
1779 * the fd's to the child are already closed
1781 if (s->ttyfd != -1) {
1782 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1783 session_pty_cleanup(s);
1787 /* detach by removing callback */
1788 channel_cancel_cleanup(s->chanid);
1794 session_destroy_all(void)
1797 for (i = 0; i < MAX_SESSIONS; i++) {
1798 Session *s = &sessions[i];
1805 session_tty_list(void)
1807 static char buf[1024];
1810 for (i = 0; i < MAX_SESSIONS; i++) {
1811 Session *s = &sessions[i];
1812 if (s->used && s->ttyfd != -1) {
1814 strlcat(buf, ",", sizeof buf);
1815 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1819 strlcpy(buf, "notty", sizeof buf);
1824 session_proctitle(Session *s)
1827 error("no user for session %d", s->self);
1829 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1833 session_setup_x11fwd(Session *s)
1836 char display[512], auth_display[512];
1837 char hostname[MAXHOSTNAMELEN];
1839 if (no_x11_forwarding_flag) {
1840 packet_send_debug("X11 forwarding disabled in user configuration file.");
1843 if (!options.x11_forwarding) {
1844 debug("X11 forwarding disabled in server configuration file.");
1847 if (!options.xauth_location ||
1848 (stat(options.xauth_location, &st) == -1)) {
1849 packet_send_debug("No xauth program; cannot forward with spoofing.");
1852 if (options.use_login) {
1853 packet_send_debug("X11 forwarding disabled; "
1854 "not compatible with UseLogin=yes.");
1857 if (s->display != NULL) {
1858 debug("X11 display already set.");
1861 s->display_number = x11_create_display_inet(options.x11_display_offset,
1862 options.x11_use_localhost, s->single_connection);
1863 if (s->display_number == -1) {
1864 debug("x11_create_display_inet failed.");
1868 /* Set up a suitable value for the DISPLAY variable. */
1869 if (gethostname(hostname, sizeof(hostname)) < 0)
1870 fatal("gethostname: %.100s", strerror(errno));
1872 * auth_display must be used as the displayname when the
1873 * authorization entry is added with xauth(1). This will be
1874 * different than the DISPLAY string for localhost displays.
1876 if (options.x11_use_localhost) {
1877 snprintf(display, sizeof display, "localhost:%d.%d",
1878 s->display_number, s->screen);
1879 snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1880 s->display_number, s->screen);
1881 s->display = xstrdup(display);
1882 s->auth_display = xstrdup(auth_display);
1884 #ifdef IPADDR_IN_DISPLAY
1886 struct in_addr my_addr;
1888 he = gethostbyname(hostname);
1890 error("Can't get IP address for X11 DISPLAY.");
1891 packet_send_debug("Can't get IP address for X11 DISPLAY.");
1894 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1895 snprintf(display, sizeof display, "%.50s:%d.%d", inet_ntoa(my_addr),
1896 s->display_number, s->screen);
1898 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1899 s->display_number, s->screen);
1901 s->display = xstrdup(display);
1902 s->auth_display = xstrdup(display);
1909 do_authenticated2(Authctxt *authctxt)
1911 server_loop2(authctxt);