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.129 2002/03/18 03:41:08 provos Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
62 #include <sys/cygwin.h>
63 #define is_winnt (GetVersion() < 0x80000000)
69 typedef struct Session Session;
78 int ptyfd, ttyfd, ptymaster;
79 int row, col, xpixel, ypixel;
88 int single_connection;
96 Session *session_new(void);
97 void session_set_fds(Session *, int, int, int);
98 static void session_pty_cleanup(void *);
99 void session_proctitle(Session *);
100 int session_setup_x11fwd(Session *);
101 void do_exec_pty(Session *, const char *);
102 void do_exec_no_pty(Session *, const char *);
103 void do_exec(Session *, const char *);
104 void do_login(Session *, const char *);
105 #ifdef LOGIN_NEEDS_UTMPX
106 static void do_pre_login(Session *s);
108 void do_child(Session *, const char *);
110 int check_quietlogin(Session *, const char *);
112 static void do_authenticated1(Authctxt *);
113 static void do_authenticated2(Authctxt *);
115 static void session_close(Session *);
116 static int session_pty_req(Session *);
119 extern ServerOptions options;
120 extern char *__progname;
121 extern int log_stderr;
122 extern int debug_flag;
123 extern u_int utmp_len;
124 extern int startup_pipe;
125 extern void destroy_sensitive_data(void);
127 /* original command from peer. */
128 const char *original_command = NULL;
131 #define MAX_SESSIONS 10
132 Session sessions[MAX_SESSIONS];
134 #ifdef WITH_AIXAUTHENTICATE
136 #endif /* WITH_AIXAUTHENTICATE */
138 #ifdef HAVE_LOGIN_CAP
143 do_authenticated(Authctxt *authctxt)
146 * Cancel the alarm we set to limit the time taken for
150 if (startup_pipe != -1) {
154 #ifdef WITH_AIXAUTHENTICATE
155 /* We don't have a pty yet, so just label the line as "ssh" */
156 if (loginsuccess(authctxt->user,
157 get_canonical_hostname(options.verify_reverse_mapping),
158 "ssh", &aixloginmsg) < 0)
160 #endif /* WITH_AIXAUTHENTICATE */
162 /* setup the channel layer */
163 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
164 channel_permit_all_opens();
167 do_authenticated2(authctxt);
169 do_authenticated1(authctxt);
171 /* remove agent socket */
172 if (auth_get_socket_name())
173 auth_sock_cleanup_proc(authctxt->pw);
175 if (options.kerberos_ticket_cleanup)
176 krb4_cleanup_proc(authctxt);
179 if (options.kerberos_ticket_cleanup)
180 krb5_cleanup_proc(authctxt);
185 * Prepares for an interactive session. This is called after the user has
186 * been successfully authenticated. During this message exchange, pseudo
187 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
188 * are requested, etc.
191 do_authenticated1(Authctxt *authctxt)
195 int success, type, screen_flag;
196 int compression_level = 0, enable_compression_after_reply = 0;
197 u_int proto_len, data_len, dlen;
200 s->authctxt = authctxt;
201 s->pw = authctxt->pw;
204 * We stay in this loop until the client requests to execute a shell
210 /* Get a packet from the client. */
211 type = packet_read();
213 /* Process the packet. */
215 case SSH_CMSG_REQUEST_COMPRESSION:
216 compression_level = packet_get_int();
218 if (compression_level < 1 || compression_level > 9) {
219 packet_send_debug("Received illegal compression level %d.",
223 /* Enable compression after we have responded with SUCCESS. */
224 enable_compression_after_reply = 1;
228 case SSH_CMSG_REQUEST_PTY:
229 success = session_pty_req(s);
232 case SSH_CMSG_X11_REQUEST_FORWARDING:
233 s->auth_proto = packet_get_string(&proto_len);
234 s->auth_data = packet_get_string(&data_len);
236 screen_flag = packet_get_protocol_flags() &
237 SSH_PROTOFLAG_SCREEN_NUMBER;
238 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
240 if (packet_remaining() == 4) {
242 debug2("Buggy client: "
243 "X11 screen flag missing");
244 s->screen = packet_get_int();
249 success = session_setup_x11fwd(s);
251 xfree(s->auth_proto);
253 s->auth_proto = NULL;
258 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
259 if (no_agent_forwarding_flag || compat13) {
260 debug("Authentication agent forwarding not permitted for this authentication.");
263 debug("Received authentication agent forwarding request.");
264 success = auth_input_request_forwarding(s->pw);
267 case SSH_CMSG_PORT_FORWARD_REQUEST:
268 if (no_port_forwarding_flag) {
269 debug("Port forwarding not permitted for this authentication.");
272 if (!options.allow_tcp_forwarding) {
273 debug("Port forwarding not permitted.");
276 debug("Received TCP/IP port forwarding request.");
277 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
281 case SSH_CMSG_MAX_PACKET_SIZE:
282 if (packet_set_maxsize(packet_get_int()) > 0)
286 #if defined(AFS) || defined(KRB5)
287 case SSH_CMSG_HAVE_KERBEROS_TGT:
288 if (!options.kerberos_tgt_passing) {
289 verbose("Kerberos TGT passing disabled.");
291 char *kdata = packet_get_string(&dlen);
294 /* XXX - 0x41, see creds_to_radix version */
295 if (kdata[0] != 0x41) {
301 if (auth_krb5_tgt(s->authctxt, &tgt))
304 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
308 if (auth_krb4_tgt(s->authctxt, kdata))
311 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
317 #endif /* AFS || KRB5 */
320 case SSH_CMSG_HAVE_AFS_TOKEN:
321 if (!options.afs_token_passing || !k_hasafs()) {
322 verbose("AFS token passing disabled.");
324 /* Accept AFS token. */
325 char *token = packet_get_string(&dlen);
328 if (auth_afs_token(s->authctxt, token))
331 verbose("AFS token refused for %.100s",
338 case SSH_CMSG_EXEC_SHELL:
339 case SSH_CMSG_EXEC_CMD:
340 if (type == SSH_CMSG_EXEC_CMD) {
341 command = packet_get_string(&dlen);
342 debug("Exec command '%.500s'", command);
354 * Any unknown messages in this phase are ignored,
355 * and a failure message is returned.
357 log("Unknown packet type received after authentication: %d", type);
359 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
363 /* Enable compression now that we have replied if appropriate. */
364 if (enable_compression_after_reply) {
365 enable_compression_after_reply = 0;
366 packet_start_compression(compression_level);
372 * This is called to fork and execute a command when we have no tty. This
373 * will call do_child from the child, and server_loop from the parent after
374 * setting up file descriptors and such.
377 do_exec_no_pty(Session *s, const char *command)
382 int pin[2], pout[2], perr[2];
383 /* Allocate pipes for communicating with the program. */
384 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
385 packet_disconnect("Could not create pipes: %.100s",
387 #else /* USE_PIPES */
388 int inout[2], err[2];
389 /* Uses socket pairs to communicate with the program. */
390 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
391 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
392 packet_disconnect("Could not create socket pairs: %.100s",
394 #endif /* USE_PIPES */
396 fatal("do_exec_no_pty: no session");
398 session_proctitle(s);
401 do_pam_session(s->pw->pw_name, NULL);
403 if (is_pam_password_change_required())
404 packet_disconnect("Password change required but no "
408 /* Fork the child. */
409 if ((pid = fork()) == 0) {
410 /* Child. Reinitialize the log since the pid has changed. */
411 log_init(__progname, options.log_level, options.log_facility, log_stderr);
414 * Create a new session and process group since the 4.4BSD
415 * setlogin() affects the entire process group.
418 error("setsid failed: %.100s", strerror(errno));
422 * Redirect stdin. We close the parent side of the socket
423 * pair, and make the child side the standard input.
426 if (dup2(pin[0], 0) < 0)
427 perror("dup2 stdin");
430 /* Redirect stdout. */
432 if (dup2(pout[1], 1) < 0)
433 perror("dup2 stdout");
436 /* Redirect stderr. */
438 if (dup2(perr[1], 2) < 0)
439 perror("dup2 stderr");
441 #else /* USE_PIPES */
443 * Redirect stdin, stdout, and stderr. Stdin and stdout will
444 * use the same socket, as some programs (particularly rdist)
445 * seem to depend on it.
449 if (dup2(inout[0], 0) < 0) /* stdin */
450 perror("dup2 stdin");
451 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
452 perror("dup2 stdout");
453 if (dup2(err[0], 2) < 0) /* stderr */
454 perror("dup2 stderr");
455 #endif /* USE_PIPES */
457 /* Do processing for the child (exec command etc). */
458 do_child(s, command);
463 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
466 packet_disconnect("fork failed: %.100s", strerror(errno));
468 /* Set interactive/non-interactive mode. */
469 packet_set_interactive(s->display != NULL);
471 /* We are the parent. Close the child sides of the pipes. */
477 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
479 /* Enter the interactive session. */
480 server_loop(pid, pin[1], pout[0], perr[0]);
481 /* server_loop has closed pin[1], pout[0], and perr[0]. */
483 #else /* USE_PIPES */
484 /* We are the parent. Close the child sides of the socket pairs. */
489 * Enter the interactive session. Note: server_loop must be able to
490 * handle the case that fdin and fdout are the same.
493 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
495 server_loop(pid, inout[1], inout[1], err[1]);
496 /* server_loop has closed inout[1] and err[1]. */
498 #endif /* USE_PIPES */
502 * This is called to fork and execute a command when we have a tty. This
503 * will call do_child from the child, and server_loop from the parent after
504 * setting up file descriptors, controlling tty, updating wtmp, utmp,
505 * lastlog, and other such operations.
508 do_exec_pty(Session *s, const char *command)
510 int fdout, ptyfd, ttyfd, ptymaster;
514 fatal("do_exec_pty: no session");
519 do_pam_session(s->pw->pw_name, s->tty);
523 /* Fork the child. */
524 if ((pid = fork()) == 0) {
526 /* Child. Reinitialize the log because the pid has changed. */
527 log_init(__progname, options.log_level, options.log_facility, log_stderr);
528 /* Close the master side of the pseudo tty. */
531 /* Make the pseudo tty our controlling tty. */
532 pty_make_controlling_tty(&ttyfd, s->tty);
534 /* Redirect stdin/stdout/stderr from the pseudo tty. */
535 if (dup2(ttyfd, 0) < 0)
536 error("dup2 stdin: %s", strerror(errno));
537 if (dup2(ttyfd, 1) < 0)
538 error("dup2 stdout: %s", strerror(errno));
539 if (dup2(ttyfd, 2) < 0)
540 error("dup2 stderr: %s", strerror(errno));
542 /* Close the extra descriptor for the pseudo tty. */
545 /* record login, etc. similar to login(1) */
547 if (!(options.use_login && command == NULL))
548 do_login(s, command);
549 # ifdef LOGIN_NEEDS_UTMPX
555 /* Do common processing for the child, such as execing the command. */
556 do_child(s, command);
561 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
564 packet_disconnect("fork failed: %.100s", strerror(errno));
567 /* Parent. Close the slave side of the pseudo tty. */
571 * Create another descriptor of the pty master side for use as the
572 * standard input. We could use the original descriptor, but this
573 * simplifies code in server_loop. The descriptor is bidirectional.
577 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
579 /* we keep a reference to the pty master */
580 ptymaster = dup(ptyfd);
582 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
583 s->ptymaster = ptymaster;
585 /* Enter interactive session. */
586 packet_set_interactive(1);
588 session_set_fds(s, ptyfd, fdout, -1);
590 server_loop(pid, ptyfd, fdout, -1);
591 /* server_loop _has_ closed ptyfd and fdout. */
595 #ifdef LOGIN_NEEDS_UTMPX
597 do_pre_login(Session *s)
600 struct sockaddr_storage from;
601 pid_t pid = getpid();
604 * Get IP address of client. If the connection is not a socket, let
605 * the address be 0.0.0.0.
607 memset(&from, 0, sizeof(from));
608 if (packet_connection_is_on_socket()) {
609 fromlen = sizeof(from);
610 if (getpeername(packet_get_connection_in(),
611 (struct sockaddr *) & from, &fromlen) < 0) {
612 debug("getpeername: %.100s", strerror(errno));
617 record_utmp_only(pid, s->tty, s->pw->pw_name,
618 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
619 (struct sockaddr *)&from);
624 * This is called to fork and execute a command. If another command is
625 * to be forced, execute that instead.
628 do_exec(Session *s, const char *command)
630 if (forced_command) {
631 original_command = command;
632 command = forced_command;
633 debug("Forced command '%.900s'", command);
637 do_exec_pty(s, command);
639 do_exec_no_pty(s, command);
641 original_command = NULL;
645 /* administrative, login(1)-like work */
647 do_login(Session *s, const char *command)
650 char hostname[MAXHOSTNAMELEN];
652 struct sockaddr_storage from;
653 time_t last_login_time;
654 struct passwd * pw = s->pw;
655 pid_t pid = getpid();
658 * Get IP address of client. If the connection is not a socket, let
659 * the address be 0.0.0.0.
661 memset(&from, 0, sizeof(from));
662 if (packet_connection_is_on_socket()) {
663 fromlen = sizeof(from);
664 if (getpeername(packet_get_connection_in(),
665 (struct sockaddr *) & from, &fromlen) < 0) {
666 debug("getpeername: %.100s", strerror(errno));
671 /* Get the time and hostname when the user last logged in. */
672 if (options.print_lastlog) {
674 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
675 hostname, sizeof(hostname));
678 /* Record that there was a login on that tty from the remote host. */
679 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
680 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
681 (struct sockaddr *)&from);
685 * If password change is needed, do it now.
686 * This needs to occur before the ~/.hushlogin check.
688 if (is_pam_password_change_required()) {
689 print_pam_messages();
694 if (check_quietlogin(s, command))
698 if (!is_pam_password_change_required())
699 print_pam_messages();
701 #ifdef WITH_AIXAUTHENTICATE
702 if (aixloginmsg && *aixloginmsg)
703 printf("%s\n", aixloginmsg);
704 #endif /* WITH_AIXAUTHENTICATE */
706 if (options.print_lastlog && last_login_time != 0) {
707 time_string = ctime(&last_login_time);
708 if (strchr(time_string, '\n'))
709 *strchr(time_string, '\n') = 0;
710 if (strcmp(hostname, "") == 0)
711 printf("Last login: %s\r\n", time_string);
713 printf("Last login: %s from %s\r\n", time_string, hostname);
720 * Display the message of the day.
728 if (options.print_motd) {
729 #ifdef HAVE_LOGIN_CAP
730 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
733 f = fopen("/etc/motd", "r");
736 while (fgets(buf, sizeof(buf), f))
745 * Check for quiet login, either .hushlogin or command given.
748 check_quietlogin(Session *s, const char *command)
751 struct passwd *pw = s->pw;
754 /* Return 1 if .hushlogin exists or a command given. */
757 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
758 #ifdef HAVE_LOGIN_CAP
759 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
762 if (stat(buf, &st) >= 0)
769 * Sets the value of the given variable in the environment. If the variable
770 * already exists, its value is overriden.
773 child_set_env(char ***envp, u_int *envsizep, const char *name,
780 * Find the slot where the value should be stored. If the variable
781 * already exists, we reuse the slot; otherwise we append a new slot
782 * at the end of the array, expanding if necessary.
785 namelen = strlen(name);
786 for (i = 0; env[i]; i++)
787 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
790 /* Reuse the slot. */
793 /* New variable. Expand if necessary. */
794 if (i >= (*envsizep) - 1) {
796 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
798 /* Need to set the NULL pointer at end of array beyond the new slot. */
802 /* Allocate space and format the variable in the appropriate slot. */
803 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
804 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
808 * Reads environment variables from the given file and adds/overrides them
809 * into the environment. If the file does not exist, this does nothing.
810 * Otherwise, it must consist of empty lines, comments (line starts with '#')
811 * and assignments of the form name=value. No other forms are allowed.
814 read_environment_file(char ***env, u_int *envsize,
815 const char *filename)
821 f = fopen(filename, "r");
825 while (fgets(buf, sizeof(buf), f)) {
826 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
828 if (!*cp || *cp == '#' || *cp == '\n')
830 if (strchr(cp, '\n'))
831 *strchr(cp, '\n') = '\0';
832 value = strchr(cp, '=');
834 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
838 * Replace the equals sign by nul, and advance value to
843 child_set_env(env, envsize, cp, value);
848 void copy_environment(char **source, char ***env, u_int *envsize)
850 char *var_name, *var_val;
856 for(i = 0; source[i] != NULL; i++) {
857 var_name = xstrdup(source[i]);
858 if ((var_val = strstr(var_name, "=")) == NULL) {
864 debug3("Copy environment: %s=%s", var_name, var_val);
865 child_set_env(env, envsize, var_name, var_val);
872 do_setup_env(Session *s, const char *shell)
877 struct passwd *pw = s->pw;
879 /* Initialize the environment. */
881 env = xmalloc(envsize * sizeof(char *));
886 * The Windows environment contains some setting which are
887 * important for a running system. They must not be dropped.
889 copy_environment(environ, &env, &envsize);
892 if (!options.use_login) {
893 /* Set basic environment. */
894 child_set_env(&env, &envsize, "USER", pw->pw_name);
895 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
896 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
897 #ifdef HAVE_LOGIN_CAP
898 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
899 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
900 #else /* HAVE_LOGIN_CAP */
903 * There's no standard path on Windows. The path contains
904 * important components pointing to the system directories,
905 * needed for loading shared libraries. So the path better
906 * remains intact here.
908 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
909 # endif /* HAVE_CYGWIN */
910 #endif /* HAVE_LOGIN_CAP */
912 snprintf(buf, sizeof buf, "%.200s/%.50s",
913 _PATH_MAILDIR, pw->pw_name);
914 child_set_env(&env, &envsize, "MAIL", buf);
916 /* Normal systems set SHELL by default. */
917 child_set_env(&env, &envsize, "SHELL", shell);
920 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
922 /* Set custom environment options from RSA authentication. */
923 if (!options.use_login) {
924 while (custom_environment) {
925 struct envstring *ce = custom_environment;
928 for (i = 0; s[i] != '=' && s[i]; i++)
932 child_set_env(&env, &envsize, s, s + i + 1);
934 custom_environment = ce->next;
940 snprintf(buf, sizeof buf, "%.50s %d %d",
941 get_remote_ipaddr(), get_remote_port(), get_local_port());
942 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
945 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
947 child_set_env(&env, &envsize, "TERM", s->term);
949 child_set_env(&env, &envsize, "DISPLAY", s->display);
950 if (original_command)
951 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
958 if ((cp = getenv("AUTHSTATE")) != NULL)
959 child_set_env(&env, &envsize, "AUTHSTATE", cp);
960 if ((cp = getenv("KRB5CCNAME")) != NULL)
961 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
962 read_environment_file(&env, &envsize, "/etc/environment");
966 if (s->authctxt->krb4_ticket_file)
967 child_set_env(&env, &envsize, "KRBTKFILE",
968 s->authctxt->krb4_ticket_file);
971 if (s->authctxt->krb5_ticket_file)
972 child_set_env(&env, &envsize, "KRB5CCNAME",
973 s->authctxt->krb5_ticket_file);
976 /* Pull in any environment variables that may have been set by PAM. */
977 copy_environment(fetch_pam_environment(), &env, &envsize);
980 if (auth_get_socket_name() != NULL)
981 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
982 auth_get_socket_name());
984 /* read $HOME/.ssh/environment. */
985 if (!options.use_login) {
986 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
988 read_environment_file(&env, &envsize, buf);
991 /* dump the environment */
992 fprintf(stderr, "Environment:\n");
993 for (i = 0; env[i]; i++)
994 fprintf(stderr, " %.200s\n", env[i]);
1000 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1001 * first in this order).
1004 do_rc_files(Session *s, const char *shell)
1012 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1014 /* ignore _PATH_SSH_USER_RC for subsystems */
1015 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1016 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1017 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1019 fprintf(stderr, "Running %s\n", cmd);
1020 f = popen(cmd, "w");
1023 fprintf(f, "%s %s\n", s->auth_proto,
1027 fprintf(stderr, "Could not run %s\n",
1029 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1031 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1032 _PATH_SSH_SYSTEM_RC);
1033 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1036 fprintf(f, "%s %s\n", s->auth_proto,
1040 fprintf(stderr, "Could not run %s\n",
1041 _PATH_SSH_SYSTEM_RC);
1042 } else if (do_xauth && options.xauth_location != NULL) {
1043 /* Add authority data to .Xauthority if appropriate. */
1046 "Running %.100s add "
1047 "%.100s %.100s %.100s\n",
1048 options.xauth_location, s->auth_display,
1049 s->auth_proto, s->auth_data);
1051 snprintf(cmd, sizeof cmd, "%s -q -",
1052 options.xauth_location);
1053 f = popen(cmd, "w");
1055 fprintf(f, "add %s %s %s\n",
1056 s->auth_display, s->auth_proto,
1060 fprintf(stderr, "Could not run %s\n",
1067 do_nologin(struct passwd *pw)
1072 #ifdef HAVE_LOGIN_CAP
1073 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1074 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1075 _PATH_NOLOGIN), "r");
1078 f = fopen(_PATH_NOLOGIN, "r");
1081 /* /etc/nologin exists. Print its contents and exit. */
1082 while (fgets(buf, sizeof(buf), f))
1089 /* Set login name, uid, gid, and groups. */
1091 do_setusercontext(struct passwd *pw)
1095 #else /* HAVE_CYGWIN */
1096 if (getuid() == 0 || geteuid() == 0) {
1097 #endif /* HAVE_CYGWIN */
1098 #ifdef HAVE_GETUSERATTR
1099 set_limits_from_userattr(pw->pw_name);
1100 #endif /* HAVE_GETUSERATTR */
1101 #ifdef HAVE_LOGIN_CAP
1102 if (setusercontext(lc, pw, pw->pw_uid,
1103 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1104 perror("unable to set user context");
1108 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1109 /* Sets login uid for accounting */
1110 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1111 error("setluid: %s", strerror(errno));
1112 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1114 if (setlogin(pw->pw_name) < 0)
1115 error("setlogin failed: %s", strerror(errno));
1116 if (setgid(pw->pw_gid) < 0) {
1120 /* Initialize the group list. */
1121 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1122 perror("initgroups");
1128 * PAM credentials may take the form of supplementary groups.
1129 * These will have been wiped by the above initgroups() call.
1130 * Reestablish them here.
1133 # endif /* USE_PAM */
1134 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1135 irix_setusercontext(pw);
1136 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1137 /* Permanently switch to the desired uid. */
1138 permanently_set_uid(pw);
1141 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1142 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1146 * Performs common processing for the child, such as setting up the
1147 * environment, closing extra file descriptors, setting the user and group
1148 * ids, and executing the command or shell.
1151 do_child(Session *s, const char *command)
1153 extern char **environ;
1156 const char *shell, *shell0, *hostname = NULL;
1157 struct passwd *pw = s->pw;
1160 /* remove hostkey from the child's memory */
1161 destroy_sensitive_data();
1163 /* login(1) is only called if we execute the login shell */
1164 if (options.use_login && command != NULL)
1165 options.use_login = 0;
1168 * Login(1) does this as well, and it needs uid 0 for the "-h"
1169 * switch, so we let login(1) to this for us.
1171 if (!options.use_login) {
1173 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1174 if (!check_quietlogin(s, command))
1176 #else /* HAVE_OSF_SIA */
1179 aix_usrinfo(pw, s->tty, s->ttyfd);
1181 do_setusercontext(pw);
1182 #endif /* HAVE_OSF_SIA */
1186 * Get the shell from the password data. An empty shell field is
1187 * legal, and means /bin/sh.
1189 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1190 #ifdef HAVE_LOGIN_CAP
1191 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1194 env = do_setup_env(s, shell);
1196 /* we have to stash the hostname before we close our socket. */
1197 if (options.use_login)
1198 hostname = get_remote_name_or_ip(utmp_len,
1199 options.verify_reverse_mapping);
1201 * Close the connection descriptors; note that this is the child, and
1202 * the server will still have the socket open, and it is important
1203 * that we do not shutdown it. Note that the descriptors cannot be
1204 * closed before building the environment, as we call
1205 * get_remote_ipaddr there.
1207 if (packet_get_connection_in() == packet_get_connection_out())
1208 close(packet_get_connection_in());
1210 close(packet_get_connection_in());
1211 close(packet_get_connection_out());
1214 * Close all descriptors related to channels. They will still remain
1215 * open in the parent.
1217 /* XXX better use close-on-exec? -markus */
1218 channel_close_all();
1221 * Close any extra file descriptors. Note that there may still be
1222 * descriptors left by system functions. They will be closed later.
1227 * Close any extra open file descriptors so that we don\'t have them
1228 * hanging around in clients. Note that we want to do this after
1229 * initgroups, because at least on Solaris 2.3 it leaves file
1232 for (i = 3; i < 64; i++)
1236 * Must take new environment into use so that .ssh/rc,
1237 * /etc/ssh/sshrc and xauth are run in the proper environment.
1242 /* Try to get AFS tokens for the local cell. */
1246 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1247 krb_afslog(cell, 0);
1253 /* Change current directory to the user\'s home directory. */
1254 if (chdir(pw->pw_dir) < 0) {
1255 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1256 pw->pw_dir, strerror(errno));
1257 #ifdef HAVE_LOGIN_CAP
1258 if (login_getcapbool(lc, "requirehome", 0))
1263 if (!options.use_login)
1264 do_rc_files(s, shell);
1266 /* restore SIGPIPE for child */
1267 signal(SIGPIPE, SIG_DFL);
1269 if (options.use_login) {
1270 /* Launch login(1). */
1272 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1273 #ifdef LOGIN_NEEDS_TERM
1274 (s->term ? s->term : "unknown"),
1275 #endif /* LOGIN_NEEDS_TERM */
1276 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1278 /* Login couldn't be executed, die. */
1284 /* Get the last component of the shell name. */
1285 if ((shell0 = strrchr(shell, '/')) != NULL)
1291 * If we have no command, execute the shell. In this case, the shell
1292 * name to be passed in argv[0] is preceded by '-' to indicate that
1293 * this is a login shell.
1298 /* Start the shell. Set initial character to '-'. */
1301 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1302 >= sizeof(argv0) - 1) {
1308 /* Execute the shell. */
1311 execve(shell, argv, env);
1313 /* Executing the shell failed. */
1318 * Execute the command using the user's shell. This uses the -c
1319 * option to execute the command.
1321 argv[0] = (char *) shell0;
1323 argv[2] = (char *) command;
1325 execve(shell, argv, env);
1334 static int did_init = 0;
1336 debug("session_new: init");
1337 for (i = 0; i < MAX_SESSIONS; i++) {
1338 sessions[i].used = 0;
1342 for (i = 0; i < MAX_SESSIONS; i++) {
1343 Session *s = &sessions[i];
1345 memset(s, 0, sizeof(*s));
1351 debug("session_new: session %d", i);
1362 for (i = 0; i < MAX_SESSIONS; i++) {
1363 Session *s = &sessions[i];
1364 debug("dump: used %d session %d %p channel %d pid %d",
1374 session_open(Authctxt *authctxt, int chanid)
1376 Session *s = session_new();
1377 debug("session_open: channel %d", chanid);
1379 error("no more sessions");
1382 s->authctxt = authctxt;
1383 s->pw = authctxt->pw;
1385 fatal("no user for session %d", s->self);
1386 debug("session_open: session %d: link with channel %d", s->self, chanid);
1392 session_by_channel(int id)
1395 for (i = 0; i < MAX_SESSIONS; i++) {
1396 Session *s = &sessions[i];
1397 if (s->used && s->chanid == id) {
1398 debug("session_by_channel: session %d channel %d", i, id);
1402 debug("session_by_channel: unknown channel %d", id);
1408 session_by_pid(pid_t pid)
1411 debug("session_by_pid: pid %d", pid);
1412 for (i = 0; i < MAX_SESSIONS; i++) {
1413 Session *s = &sessions[i];
1414 if (s->used && s->pid == pid)
1417 error("session_by_pid: unknown pid %d", pid);
1423 session_window_change_req(Session *s)
1425 s->col = packet_get_int();
1426 s->row = packet_get_int();
1427 s->xpixel = packet_get_int();
1428 s->ypixel = packet_get_int();
1430 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1435 session_pty_req(Session *s)
1441 debug("Allocating a pty not permitted for this authentication.");
1444 if (s->ttyfd != -1) {
1445 packet_disconnect("Protocol error: you already have a pty.");
1449 s->term = packet_get_string(&len);
1452 s->col = packet_get_int();
1453 s->row = packet_get_int();
1455 s->row = packet_get_int();
1456 s->col = packet_get_int();
1458 s->xpixel = packet_get_int();
1459 s->ypixel = packet_get_int();
1461 if (strcmp(s->term, "") == 0) {
1466 /* Allocate a pty and open it. */
1467 debug("Allocating pty.");
1468 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1474 error("session_pty_req: session %d alloc failed", s->self);
1477 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1479 /* for SSH1 the tty modes length is not given */
1481 n_bytes = packet_remaining();
1482 tty_parse_modes(s->ttyfd, &n_bytes);
1485 * Add a cleanup function to clear the utmp entry and record logout
1486 * time in case we call fatal() (e.g., the connection gets closed).
1488 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1489 pty_setowner(s->pw, s->tty);
1491 /* Set window size from the packet. */
1492 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1495 session_proctitle(s);
1500 session_subsystem_req(Session *s)
1505 char *cmd, *subsys = packet_get_string(&len);
1509 log("subsystem request for %.100s", subsys);
1511 for (i = 0; i < options.num_subsystems; i++) {
1512 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1513 cmd = options.subsystem_command[i];
1514 if (stat(cmd, &st) < 0) {
1515 error("subsystem: cannot stat %s: %s", cmd,
1519 debug("subsystem: exec() %s", cmd);
1520 s->is_subsystem = 1;
1528 log("subsystem request for %.100s failed, subsystem not found",
1536 session_x11_req(Session *s)
1540 s->single_connection = packet_get_char();
1541 s->auth_proto = packet_get_string(NULL);
1542 s->auth_data = packet_get_string(NULL);
1543 s->screen = packet_get_int();
1546 success = session_setup_x11fwd(s);
1548 xfree(s->auth_proto);
1549 xfree(s->auth_data);
1550 s->auth_proto = NULL;
1551 s->auth_data = NULL;
1557 session_shell_req(Session *s)
1565 session_exec_req(Session *s)
1568 char *command = packet_get_string(&len);
1570 do_exec(s, command);
1576 session_auth_agent_req(Session *s)
1578 static int called = 0;
1580 if (no_agent_forwarding_flag) {
1581 debug("session_auth_agent_req: no_agent_forwarding_flag");
1588 return auth_input_request_forwarding(s->pw);
1593 session_input_channel_req(Channel *c, const char *rtype)
1598 if ((s = session_by_channel(c->self)) == NULL) {
1599 log("session_input_channel_req: no session %d req %.100s",
1603 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1606 * a session is in LARVAL state until a shell, a command
1607 * or a subsystem is executed
1609 if (c->type == SSH_CHANNEL_LARVAL) {
1610 if (strcmp(rtype, "shell") == 0) {
1611 success = session_shell_req(s);
1612 } else if (strcmp(rtype, "exec") == 0) {
1613 success = session_exec_req(s);
1614 } else if (strcmp(rtype, "pty-req") == 0) {
1615 success = session_pty_req(s);
1616 } else if (strcmp(rtype, "x11-req") == 0) {
1617 success = session_x11_req(s);
1618 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1619 success = session_auth_agent_req(s);
1620 } else if (strcmp(rtype, "subsystem") == 0) {
1621 success = session_subsystem_req(s);
1624 if (strcmp(rtype, "window-change") == 0) {
1625 success = session_window_change_req(s);
1631 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1634 fatal("session_set_fds: called for proto != 2.0");
1636 * now that have a child and a pipe to the child,
1637 * we can activate our channel and register the fd's
1639 if (s->chanid == -1)
1640 fatal("no channel for session %d", s->self);
1641 channel_set_fds(s->chanid,
1643 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1645 CHAN_SES_WINDOW_DEFAULT);
1649 * Function to perform pty cleanup. Also called if we get aborted abnormally
1650 * (e.g., due to a dropped connection).
1653 session_pty_cleanup(void *session)
1655 Session *s = session;
1658 error("session_pty_cleanup: no session");
1664 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1666 /* Record that the user has logged out. */
1668 record_logout(s->pid, s->tty, s->pw->pw_name);
1670 /* Release the pseudo-tty. */
1671 pty_release(s->tty);
1674 * Close the server side of the socket pairs. We must do this after
1675 * the pty cleanup, so that another process doesn't get this pty
1676 * while we're still cleaning up.
1678 if (close(s->ptymaster) < 0)
1679 error("close(s->ptymaster): %s", strerror(errno));
1681 /* unlink pty from session */
1686 session_exit_message(Session *s, int status)
1690 if ((c = channel_lookup(s->chanid)) == NULL)
1691 fatal("session_exit_message: session %d: no channel %d",
1692 s->self, s->chanid);
1693 debug("session_exit_message: session %d channel %d pid %d",
1694 s->self, s->chanid, s->pid);
1696 if (WIFEXITED(status)) {
1697 channel_request_start(s->chanid, "exit-status", 0);
1698 packet_put_int(WEXITSTATUS(status));
1700 } else if (WIFSIGNALED(status)) {
1701 channel_request_start(s->chanid, "exit-signal", 0);
1702 packet_put_int(WTERMSIG(status));
1704 packet_put_char(WCOREDUMP(status));
1705 #else /* WCOREDUMP */
1707 #endif /* WCOREDUMP */
1708 packet_put_cstring("");
1709 packet_put_cstring("");
1712 /* Some weird exit cause. Just exit. */
1713 packet_disconnect("wait returned status %04x.", status);
1716 /* disconnect channel */
1717 debug("session_exit_message: release channel %d", s->chanid);
1718 channel_cancel_cleanup(s->chanid);
1720 * emulate a write failure with 'chan_write_failed', nobody will be
1721 * interested in data we write.
1722 * Note that we must not call 'chan_read_failed', since there could
1723 * be some more data waiting in the pipe.
1725 if (c->ostate != CHAN_OUTPUT_CLOSED)
1726 chan_write_failed(c);
1731 session_close(Session *s)
1733 debug("session_close: session %d pid %d", s->self, s->pid);
1734 if (s->ttyfd != -1) {
1735 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1736 session_pty_cleanup(s);
1742 if (s->auth_display)
1743 xfree(s->auth_display);
1745 xfree(s->auth_data);
1747 xfree(s->auth_proto);
1749 session_proctitle(s);
1753 session_close_by_pid(pid_t pid, int status)
1755 Session *s = session_by_pid(pid);
1757 debug("session_close_by_pid: no session for pid %d", pid);
1760 if (s->chanid != -1)
1761 session_exit_message(s, status);
1766 * this is called when a channel dies before
1767 * the session 'child' itself dies
1770 session_close_by_channel(int id, void *arg)
1772 Session *s = session_by_channel(id);
1774 debug("session_close_by_channel: no session for id %d", id);
1777 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1779 debug("session_close_by_channel: channel %d: has child", id);
1781 * delay detach of session, but release pty, since
1782 * the fd's to the child are already closed
1784 if (s->ttyfd != -1) {
1785 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1786 session_pty_cleanup(s);
1790 /* detach by removing callback */
1791 channel_cancel_cleanup(s->chanid);
1797 session_destroy_all(void)
1800 for (i = 0; i < MAX_SESSIONS; i++) {
1801 Session *s = &sessions[i];
1808 session_tty_list(void)
1810 static char buf[1024];
1813 for (i = 0; i < MAX_SESSIONS; i++) {
1814 Session *s = &sessions[i];
1815 if (s->used && s->ttyfd != -1) {
1817 strlcat(buf, ",", sizeof buf);
1818 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1822 strlcpy(buf, "notty", sizeof buf);
1827 session_proctitle(Session *s)
1830 error("no user for session %d", s->self);
1832 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1836 session_setup_x11fwd(Session *s)
1839 char display[512], auth_display[512];
1840 char hostname[MAXHOSTNAMELEN];
1842 if (no_x11_forwarding_flag) {
1843 packet_send_debug("X11 forwarding disabled in user configuration file.");
1846 if (!options.x11_forwarding) {
1847 debug("X11 forwarding disabled in server configuration file.");
1850 if (!options.xauth_location ||
1851 (stat(options.xauth_location, &st) == -1)) {
1852 packet_send_debug("No xauth program; cannot forward with spoofing.");
1855 if (options.use_login) {
1856 packet_send_debug("X11 forwarding disabled; "
1857 "not compatible with UseLogin=yes.");
1860 if (s->display != NULL) {
1861 debug("X11 display already set.");
1864 s->display_number = x11_create_display_inet(options.x11_display_offset,
1865 options.x11_use_localhost, s->single_connection);
1866 if (s->display_number == -1) {
1867 debug("x11_create_display_inet failed.");
1871 /* Set up a suitable value for the DISPLAY variable. */
1872 if (gethostname(hostname, sizeof(hostname)) < 0)
1873 fatal("gethostname: %.100s", strerror(errno));
1875 * auth_display must be used as the displayname when the
1876 * authorization entry is added with xauth(1). This will be
1877 * different than the DISPLAY string for localhost displays.
1879 if (options.x11_use_localhost) {
1880 snprintf(display, sizeof display, "localhost:%d.%d",
1881 s->display_number, s->screen);
1882 snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1883 s->display_number, s->screen);
1884 s->display = xstrdup(display);
1885 s->auth_display = xstrdup(auth_display);
1887 #ifdef IPADDR_IN_DISPLAY
1889 struct in_addr my_addr;
1891 he = gethostbyname(hostname);
1893 error("Can't get IP address for X11 DISPLAY.");
1894 packet_send_debug("Can't get IP address for X11 DISPLAY.");
1897 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1898 snprintf(display, sizeof display, "%.50s:%d.%d", inet_ntoa(my_addr),
1899 s->display_number, s->screen);
1901 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1902 s->display_number, s->screen);
1904 s->display = xstrdup(display);
1905 s->auth_display = xstrdup(display);
1912 do_authenticated2(Authctxt *authctxt)
1914 server_loop2(authctxt);