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 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.79 2001/06/03 14:55:39 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
60 #ifdef WITH_IRIX_PROJECT
62 #endif /* WITH_IRIX_PROJECT */
64 #include <sys/resource.h>
66 #ifdef WITH_IRIX_AUDIT
68 #endif /* WITH_IRIX_AUDIT */
70 #if defined(HAVE_USERSEC_H)
76 #include <sys/cygwin.h>
77 #define is_winnt (GetVersion() < 0x80000000)
81 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
82 # define S_UFSIZE_HARD S_UFSIZE "_hard"
83 # define S_UCPU_HARD S_UCPU "_hard"
84 # define S_UDATA_HARD S_UDATA "_hard"
85 # define S_USTACK_HARD S_USTACK "_hard"
86 # define S_URSS_HARD S_URSS "_hard"
87 # define S_UCORE_HARD S_UCORE "_hard"
88 # define S_UNOFILE_HARD S_UNOFILE "_hard"
98 typedef struct Session Session;
106 int ptyfd, ttyfd, ptymaster;
107 int row, col, xpixel, ypixel;
114 int single_connection;
122 Session *session_new(void);
123 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
124 void session_pty_cleanup(Session *s);
125 void session_proctitle(Session *s);
126 void do_exec_pty(Session *s, const char *command);
127 void do_exec_no_pty(Session *s, const char *command);
128 void do_login(Session *s, const char *command);
129 #ifdef LOGIN_NEEDS_UTMPX
130 void do_pre_login(Session *s);
132 void do_child(Session *s, const char *command);
134 int check_quietlogin(Session *s, const char *command);
135 void xauthfile_cleanup_proc(void *ignore);
137 void do_authenticated1(Authctxt *authctxt);
138 void do_authenticated2(Authctxt *authctxt);
141 extern ServerOptions options;
142 extern char *__progname;
143 extern int log_stderr;
144 extern int debug_flag;
145 extern u_int utmp_len;
146 extern int startup_pipe;
147 extern void destroy_sensitive_data(void);
149 /* Local Xauthority file. */
150 static char *xauthfile;
152 /* original command from peer. */
153 char *original_command = NULL;
156 #define MAX_SESSIONS 10
157 Session sessions[MAX_SESSIONS];
159 #ifdef WITH_AIXAUTHENTICATE
160 /* AIX's lastlogin message, set in auth1.c */
162 #endif /* WITH_AIXAUTHENTICATE */
164 #ifdef HAVE_LOGIN_CAP
165 static login_cap_t *lc;
169 do_authenticated(Authctxt *authctxt)
172 * Cancel the alarm we set to limit the time taken for
176 if (startup_pipe != -1) {
180 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
181 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
182 error("unable to get login class");
186 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
187 packet_disconnect("Approval failure for %s",
188 authctxt->pw->pw_name);
192 /* setup the channel layer */
193 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
194 channel_permit_all_opens();
197 do_authenticated2(authctxt);
199 do_authenticated1(authctxt);
201 /* remote user's local Xauthority file and agent socket */
203 xauthfile_cleanup_proc(NULL);
204 if (auth_get_socket_name())
205 auth_sock_cleanup_proc(NULL);
209 * Remove local Xauthority file.
212 xauthfile_cleanup_proc(void *ignore)
214 debug("xauthfile_cleanup_proc called");
216 if (xauthfile != NULL) {
219 p = strrchr(xauthfile, '/');
230 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
231 * dropped connection).
234 pty_cleanup_proc(void *session)
238 fatal("pty_cleanup_proc: no session");
239 debug("pty_cleanup_proc: %s", s->tty);
242 /* Record that the user has logged out. */
243 record_logout(s->pid, s->tty);
246 /* Release the pseudo-tty. */
251 * Prepares for an interactive session. This is called after the user has
252 * been successfully authenticated. During this message exchange, pseudo
253 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
254 * are requested, etc.
257 do_authenticated1(Authctxt *authctxt)
261 int success, type, fd, n_bytes, plen, screen_flag, have_pty = 0;
262 int compression_level = 0, enable_compression_after_reply = 0;
263 u_int proto_len, data_len, dlen;
267 s->pw = authctxt->pw;
270 * We stay in this loop until the client requests to execute a shell
276 /* Get a packet from the client. */
277 type = packet_read(&plen);
279 /* Process the packet. */
281 case SSH_CMSG_REQUEST_COMPRESSION:
282 packet_integrity_check(plen, 4, type);
283 compression_level = packet_get_int();
284 if (compression_level < 1 || compression_level > 9) {
285 packet_send_debug("Received illegal compression level %d.",
289 /* Enable compression after we have responded with SUCCESS. */
290 enable_compression_after_reply = 1;
294 case SSH_CMSG_REQUEST_PTY:
296 debug("Allocating a pty not permitted for this authentication.");
300 packet_disconnect("Protocol error: you already have a pty.");
302 debug("Allocating pty.");
304 /* Allocate a pty and open it. */
305 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
307 error("Failed to allocate pty.");
310 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
311 pty_setowner(s->pw, s->tty);
313 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
314 s->term = packet_get_string(&dlen);
315 packet_integrity_check(dlen, strlen(s->term), type);
316 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
317 /* Remaining bytes */
318 n_bytes = plen - (4 + dlen + 4 * 4);
320 if (strcmp(s->term, "") == 0) {
324 /* Get window size from the packet. */
325 s->row = packet_get_int();
326 s->col = packet_get_int();
327 s->xpixel = packet_get_int();
328 s->ypixel = packet_get_int();
329 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
331 /* Get tty modes from the packet. */
332 tty_parse_modes(s->ttyfd, &n_bytes);
333 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
335 session_proctitle(s);
337 /* Indicate that we now have a pty. */
342 case SSH_CMSG_X11_REQUEST_FORWARDING:
343 if (!options.x11_forwarding) {
344 packet_send_debug("X11 forwarding disabled in server configuration file.");
347 if (!options.xauth_location ||
348 (stat(options.xauth_location, &st) == -1)) {
349 packet_send_debug("No xauth program; cannot forward with spoofing.");
352 if (no_x11_forwarding_flag) {
353 packet_send_debug("X11 forwarding not permitted for this authentication.");
356 debug("Received request for X11 forwarding with auth spoofing.");
357 if (s->display != NULL)
358 packet_disconnect("Protocol error: X11 display already set.");
360 s->auth_proto = packet_get_string(&proto_len);
361 s->auth_data = packet_get_string(&data_len);
363 screen_flag = packet_get_protocol_flags() &
364 SSH_PROTOFLAG_SCREEN_NUMBER;
365 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
367 if (packet_remaining() == 4) {
369 debug2("Buggy client: "
370 "X11 screen flag missing");
371 packet_integrity_check(plen,
372 4 + proto_len + 4 + data_len + 4, type);
373 s->screen = packet_get_int();
375 packet_integrity_check(plen,
376 4 + proto_len + 4 + data_len, type);
379 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
381 if (s->display == NULL)
384 /* Setup to always have a local .Xauthority. */
385 xauthfile = xmalloc(MAXPATHLEN);
386 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
387 temporarily_use_uid(s->pw);
388 if (mkdtemp(xauthfile) == NULL) {
390 error("private X11 dir: mkdtemp %s failed: %s",
391 xauthfile, strerror(errno));
394 /* XXXX remove listening channels */
397 strlcat(xauthfile, "/cookies", MAXPATHLEN);
398 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
402 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
406 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
407 if (no_agent_forwarding_flag || compat13) {
408 debug("Authentication agent forwarding not permitted for this authentication.");
411 debug("Received authentication agent forwarding request.");
412 success = auth_input_request_forwarding(s->pw);
415 case SSH_CMSG_PORT_FORWARD_REQUEST:
416 if (no_port_forwarding_flag) {
417 debug("Port forwarding not permitted for this authentication.");
420 if (!options.allow_tcp_forwarding) {
421 debug("Port forwarding not permitted.");
424 debug("Received TCP/IP port forwarding request.");
425 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
429 case SSH_CMSG_MAX_PACKET_SIZE:
430 if (packet_set_maxsize(packet_get_int()) > 0)
434 case SSH_CMSG_EXEC_SHELL:
435 case SSH_CMSG_EXEC_CMD:
436 if (type == SSH_CMSG_EXEC_CMD) {
437 command = packet_get_string(&dlen);
438 debug("Exec command '%.500s'", command);
439 packet_integrity_check(plen, 4 + dlen, type);
442 packet_integrity_check(plen, 0, type);
444 if (forced_command != NULL) {
445 original_command = command;
446 command = forced_command;
447 debug("Forced command '%.500s'", forced_command);
450 do_exec_pty(s, command);
452 do_exec_no_pty(s, command);
460 * Any unknown messages in this phase are ignored,
461 * and a failure message is returned.
463 log("Unknown packet type received after authentication: %d", type);
465 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
469 /* Enable compression now that we have replied if appropriate. */
470 if (enable_compression_after_reply) {
471 enable_compression_after_reply = 0;
472 packet_start_compression(compression_level);
478 * This is called to fork and execute a command when we have no tty. This
479 * will call do_child from the child, and server_loop from the parent after
480 * setting up file descriptors and such.
483 do_exec_no_pty(Session *s, const char *command)
488 int pin[2], pout[2], perr[2];
489 /* Allocate pipes for communicating with the program. */
490 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
491 packet_disconnect("Could not create pipes: %.100s",
493 #else /* USE_PIPES */
494 int inout[2], err[2];
495 /* Uses socket pairs to communicate with the program. */
496 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
497 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
498 packet_disconnect("Could not create socket pairs: %.100s",
500 #endif /* USE_PIPES */
502 fatal("do_exec_no_pty: no session");
504 session_proctitle(s);
510 /* Fork the child. */
511 if ((pid = fork()) == 0) {
512 /* Child. Reinitialize the log since the pid has changed. */
513 log_init(__progname, options.log_level, options.log_facility, log_stderr);
516 * Create a new session and process group since the 4.4BSD
517 * setlogin() affects the entire process group.
520 error("setsid failed: %.100s", strerror(errno));
524 * Redirect stdin. We close the parent side of the socket
525 * pair, and make the child side the standard input.
528 if (dup2(pin[0], 0) < 0)
529 perror("dup2 stdin");
532 /* Redirect stdout. */
534 if (dup2(pout[1], 1) < 0)
535 perror("dup2 stdout");
538 /* Redirect stderr. */
540 if (dup2(perr[1], 2) < 0)
541 perror("dup2 stderr");
543 #else /* USE_PIPES */
545 * Redirect stdin, stdout, and stderr. Stdin and stdout will
546 * use the same socket, as some programs (particularly rdist)
547 * seem to depend on it.
551 if (dup2(inout[0], 0) < 0) /* stdin */
552 perror("dup2 stdin");
553 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
554 perror("dup2 stdout");
555 if (dup2(err[0], 2) < 0) /* stderr */
556 perror("dup2 stderr");
557 #endif /* USE_PIPES */
559 /* Do processing for the child (exec command etc). */
560 do_child(s, command);
565 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
568 packet_disconnect("fork failed: %.100s", strerror(errno));
570 /* Set interactive/non-interactive mode. */
571 packet_set_interactive(s->display != NULL);
573 /* We are the parent. Close the child sides of the pipes. */
579 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
581 /* Enter the interactive session. */
582 server_loop(pid, pin[1], pout[0], perr[0]);
583 /* server_loop has closed pin[1], pout[0], and perr[0]. */
585 #else /* USE_PIPES */
586 /* We are the parent. Close the child sides of the socket pairs. */
591 * Enter the interactive session. Note: server_loop must be able to
592 * handle the case that fdin and fdout are the same.
595 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
597 server_loop(pid, inout[1], inout[1], err[1]);
598 /* server_loop has closed inout[1] and err[1]. */
600 #endif /* USE_PIPES */
604 * This is called to fork and execute a command when we have a tty. This
605 * will call do_child from the child, and server_loop from the parent after
606 * setting up file descriptors, controlling tty, updating wtmp, utmp,
607 * lastlog, and other such operations.
610 do_exec_pty(Session *s, const char *command)
612 int fdout, ptyfd, ttyfd, ptymaster;
616 fatal("do_exec_pty: no session");
621 do_pam_session(s->pw->pw_name, s->tty);
625 /* Fork the child. */
626 if ((pid = fork()) == 0) {
627 /* Child. Reinitialize the log because the pid has changed. */
628 log_init(__progname, options.log_level, options.log_facility, log_stderr);
630 /* Close the master side of the pseudo tty. */
633 /* Make the pseudo tty our controlling tty. */
634 pty_make_controlling_tty(&ttyfd, s->tty);
636 /* Redirect stdin from the pseudo tty. */
637 if (dup2(ttyfd, fileno(stdin)) < 0)
638 error("dup2 stdin failed: %.100s", strerror(errno));
640 /* Redirect stdout to the pseudo tty. */
641 if (dup2(ttyfd, fileno(stdout)) < 0)
642 error("dup2 stdin failed: %.100s", strerror(errno));
644 /* Redirect stderr to the pseudo tty. */
645 if (dup2(ttyfd, fileno(stderr)) < 0)
646 error("dup2 stdin failed: %.100s", strerror(errno));
648 /* Close the extra descriptor for the pseudo tty. */
651 /* record login, etc. similar to login(1) */
653 if (!(options.use_login && command == NULL))
654 do_login(s, command);
655 # ifdef LOGIN_NEEDS_UTMPX
661 /* Do common processing for the child, such as execing the command. */
662 do_child(s, command);
667 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
670 packet_disconnect("fork failed: %.100s", strerror(errno));
673 /* Parent. Close the slave side of the pseudo tty. */
677 * Create another descriptor of the pty master side for use as the
678 * standard input. We could use the original descriptor, but this
679 * simplifies code in server_loop. The descriptor is bidirectional.
683 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
685 /* we keep a reference to the pty master */
686 ptymaster = dup(ptyfd);
688 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
689 s->ptymaster = ptymaster;
691 /* Enter interactive session. */
692 packet_set_interactive(1);
694 session_set_fds(s, ptyfd, fdout, -1);
696 server_loop(pid, ptyfd, fdout, -1);
697 /* server_loop _has_ closed ptyfd and fdout. */
698 session_pty_cleanup(s);
702 #ifdef LOGIN_NEEDS_UTMPX
704 do_pre_login(Session *s)
707 struct sockaddr_storage from;
708 pid_t pid = getpid();
711 * Get IP address of client. If the connection is not a socket, let
712 * the address be 0.0.0.0.
714 memset(&from, 0, sizeof(from));
715 if (packet_connection_is_on_socket()) {
716 fromlen = sizeof(from);
717 if (getpeername(packet_get_connection_in(),
718 (struct sockaddr *) & from, &fromlen) < 0) {
719 debug("getpeername: %.100s", strerror(errno));
724 record_utmp_only(pid, s->tty, s->pw->pw_name,
725 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
726 (struct sockaddr *)&from);
730 /* administrative, login(1)-like work */
732 do_login(Session *s, const char *command)
735 char hostname[MAXHOSTNAMELEN];
737 struct sockaddr_storage from;
738 time_t last_login_time;
739 struct passwd * pw = s->pw;
740 pid_t pid = getpid();
743 * Get IP address of client. If the connection is not a socket, let
744 * the address be 0.0.0.0.
746 memset(&from, 0, sizeof(from));
747 if (packet_connection_is_on_socket()) {
748 fromlen = sizeof(from);
749 if (getpeername(packet_get_connection_in(),
750 (struct sockaddr *) & from, &fromlen) < 0) {
751 debug("getpeername: %.100s", strerror(errno));
756 /* Get the time and hostname when the user last logged in. */
757 if (options.print_lastlog) {
759 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
760 hostname, sizeof(hostname));
763 /* Record that there was a login on that tty from the remote host. */
764 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
765 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
766 (struct sockaddr *)&from);
770 * If password change is needed, do it now.
771 * This needs to occur before the ~/.hushlogin check.
773 if (is_pam_password_change_required()) {
774 print_pam_messages();
779 if (check_quietlogin(s, command))
783 if (!is_pam_password_change_required())
784 print_pam_messages();
786 #ifdef WITH_AIXAUTHENTICATE
787 if (aixloginmsg && *aixloginmsg)
788 printf("%s\n", aixloginmsg);
789 #endif /* WITH_AIXAUTHENTICATE */
791 if (options.print_lastlog && last_login_time != 0) {
792 time_string = ctime(&last_login_time);
793 if (strchr(time_string, '\n'))
794 *strchr(time_string, '\n') = 0;
795 if (strcmp(hostname, "") == 0)
796 printf("Last login: %s\r\n", time_string);
798 printf("Last login: %s from %s\r\n", time_string, hostname);
805 * Display the message of the day.
813 if (options.print_motd) {
814 #ifdef HAVE_LOGIN_CAP
815 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
818 f = fopen("/etc/motd", "r");
821 while (fgets(buf, sizeof(buf), f))
830 * Check for quiet login, either .hushlogin or command given.
833 check_quietlogin(Session *s, const char *command)
836 struct passwd * pw = s->pw;
839 /* Return 1 if .hushlogin exists or a command given. */
842 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
843 #ifdef HAVE_LOGIN_CAP
844 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
847 if (stat(buf, &st) >= 0)
854 * Sets the value of the given variable in the environment. If the variable
855 * already exists, its value is overriden.
858 child_set_env(char ***envp, u_int *envsizep, const char *name,
865 * Find the slot where the value should be stored. If the variable
866 * already exists, we reuse the slot; otherwise we append a new slot
867 * at the end of the array, expanding if necessary.
870 namelen = strlen(name);
871 for (i = 0; env[i]; i++)
872 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
875 /* Reuse the slot. */
878 /* New variable. Expand if necessary. */
879 if (i >= (*envsizep) - 1) {
881 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
883 /* Need to set the NULL pointer at end of array beyond the new slot. */
887 /* Allocate space and format the variable in the appropriate slot. */
888 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
889 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
893 * Reads environment variables from the given file and adds/overrides them
894 * into the environment. If the file does not exist, this does nothing.
895 * Otherwise, it must consist of empty lines, comments (line starts with '#')
896 * and assignments of the form name=value. No other forms are allowed.
899 read_environment_file(char ***env, u_int *envsize,
900 const char *filename)
906 f = fopen(filename, "r");
910 while (fgets(buf, sizeof(buf), f)) {
911 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
913 if (!*cp || *cp == '#' || *cp == '\n')
915 if (strchr(cp, '\n'))
916 *strchr(cp, '\n') = '\0';
917 value = strchr(cp, '=');
919 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
923 * Replace the equals sign by nul, and advance value to
928 child_set_env(env, envsize, cp, value);
935 * Sets any environment variables which have been specified by PAM
937 void do_pam_environment(char ***env, int *envsize)
939 char *equals, var_name[512], var_val[512];
943 if ((pam_env = fetch_pam_environment()) == NULL)
946 for(i = 0; pam_env[i] != NULL; i++) {
947 if ((equals = strstr(pam_env[i], "=")) == NULL)
950 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
951 memset(var_name, '\0', sizeof(var_name));
952 memset(var_val, '\0', sizeof(var_val));
954 strncpy(var_name, pam_env[i], equals - pam_env[i]);
955 strcpy(var_val, equals + 1);
957 debug3("PAM environment: %s=%s", var_name, var_val);
959 child_set_env(env, envsize, var_name, var_val);
966 void copy_environment(char ***env, int *envsize)
968 char *equals, var_name[512], var_val[512];
971 for(i = 0; environ[i] != NULL; i++) {
972 if ((equals = strstr(environ[i], "=")) == NULL)
975 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
976 memset(var_name, '\0', sizeof(var_name));
977 memset(var_val, '\0', sizeof(var_val));
979 strncpy(var_name, environ[i], equals - environ[i]);
980 strcpy(var_val, equals + 1);
982 debug3("Copy environment: %s=%s", var_name, var_val);
984 child_set_env(env, envsize, var_name, var_val);
990 #if defined(HAVE_GETUSERATTR)
992 * AIX-specific login initialisation
994 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
999 getrlimit(resource, &rlim);
1002 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
1004 rlim.rlim_cur = RLIM_INFINITY;
1005 } else if (slim != 0) {
1006 /* See the wackiness below */
1007 if (rlim.rlim_cur == slim * mult)
1010 rlim.rlim_cur = slim * mult;
1015 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
1017 rlim.rlim_max = RLIM_INFINITY;
1018 } else if (hlim != 0) {
1019 rlim.rlim_max = hlim * mult;
1024 * XXX For cpu and fsize the soft limit is set to the hard limit
1025 * if the hard limit is left at its default value and the soft limit
1026 * is changed from its default value, either by requesting it
1027 * (slim == 0) or by setting it to the current default. At least
1028 * that's how rlogind does it. If you're confused you're not alone.
1029 * Bug or feature? AIX 4.3.1.2
1031 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
1032 && hlim == 0 && slim != 0)
1033 rlim.rlim_max = rlim.rlim_cur;
1034 /* A specified hard limit limits the soft limit */
1035 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
1036 rlim.rlim_cur = rlim.rlim_max;
1037 /* A soft limit can increase a hard limit */
1038 else if (rlim.rlim_cur > rlim.rlim_max)
1039 rlim.rlim_max = rlim.rlim_cur;
1041 if (setrlimit(resource, &rlim) != 0)
1042 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
1045 void set_limits_from_userattr(char *user)
1050 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
1051 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
1052 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
1053 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
1054 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
1055 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1056 #if defined(S_UNOFILE)
1057 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1060 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1061 /* Convert decimal to octal */
1062 (void) snprintf(buf, sizeof(buf), "%d", mask);
1063 if (sscanf(buf, "%o", &mask) == 1)
1067 #endif /* defined(HAVE_GETUSERATTR) */
1070 * Performs common processing for the child, such as setting up the
1071 * environment, closing extra file descriptors, setting the user and group
1072 * ids, and executing the command or shell.
1075 do_child(Session *s, const char *command)
1077 const char *shell, *hostname = NULL, *cp = NULL;
1078 struct passwd * pw = s->pw;
1084 extern char **environ;
1087 int do_xauth = s->auth_proto != NULL && s->auth_data != NULL;
1088 #ifdef WITH_IRIX_PROJECT
1090 #endif /* WITH_IRIX_PROJECT */
1091 #ifdef WITH_IRIX_JOBS
1094 #ifdef WITH_IRIX_ARRAY
1096 #endif /* WITH_IRIX_ARRAY */
1097 #endif /* WITH_IRIX_JOBS */
1099 /* remove hostkey from the child's memory */
1100 destroy_sensitive_data();
1102 /* login(1) is only called if we execute the login shell */
1103 if (options.use_login && command != NULL)
1104 options.use_login = 0;
1106 #if !defined(USE_PAM) && !defined(HAVE_OSF_SIA)
1107 if (!options.use_login) {
1108 # ifdef HAVE_LOGIN_CAP
1109 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1110 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1111 _PATH_NOLOGIN), "r");
1112 # else /* HAVE_LOGIN_CAP */
1114 f = fopen(_PATH_NOLOGIN, "r");
1115 # endif /* HAVE_LOGIN_CAP */
1117 /* /etc/nologin exists. Print its contents and exit. */
1118 while (fgets(buf, sizeof(buf), f))
1124 #endif /* USE_PAM || HAVE_OSF_SIA */
1126 /* Set login name, uid, gid, and groups. */
1127 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1128 switch, so we let login(1) to this for us. */
1129 if (!options.use_login) {
1131 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1132 if (!check_quietlogin(s, command))
1134 #else /* HAVE_OSF_SIA */
1138 if (getuid() == 0 || geteuid() == 0) {
1140 # ifdef HAVE_GETUSERATTR
1141 set_limits_from_userattr(pw->pw_name);
1142 # endif /* HAVE_GETUSERATTR */
1143 # ifdef HAVE_LOGIN_CAP
1144 if (setusercontext(lc, pw, pw->pw_uid,
1145 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1146 perror("unable to set user context");
1149 # else /* HAVE_LOGIN_CAP */
1150 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1151 /* Sets login uid for accounting */
1152 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1153 error("setluid: %s", strerror(errno));
1154 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1156 if (setlogin(pw->pw_name) < 0)
1157 error("setlogin failed: %s", strerror(errno));
1158 if (setgid(pw->pw_gid) < 0) {
1162 /* Initialize the group list. */
1163 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1164 perror("initgroups");
1170 * PAM credentials may take the form of
1171 * supplementary groups. These will have been
1172 * wiped by the above initgroups() call.
1173 * Reestablish them here.
1176 # endif /* USE_PAM */
1177 # ifdef WITH_IRIX_JOBS
1178 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1180 fatal("Failed to create job container: %.100s",
1183 # endif /* WITH_IRIX_JOBS */
1184 # ifdef WITH_IRIX_ARRAY
1185 /* initialize array session */
1187 if (newarraysess() != 0)
1188 fatal("Failed to set up new array session: %.100s",
1191 # endif /* WITH_IRIX_ARRAY */
1192 # ifdef WITH_IRIX_PROJECT
1193 /* initialize irix project info */
1194 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1195 debug("Failed to get project id, using projid 0");
1198 if (setprid(projid))
1199 fatal("Failed to initialize project %d for %s: %.100s",
1200 (int)projid, pw->pw_name, strerror(errno));
1201 # endif /* WITH_IRIX_PROJECT */
1202 #ifdef WITH_IRIX_AUDIT
1203 if (sysconf(_SC_AUDIT)) {
1204 debug("Setting sat id to %d", (int) pw->pw_uid);
1205 if (satsetid(pw->pw_uid))
1206 debug("error setting satid: %.100s", strerror(errno));
1208 #endif /* WITH_IRIX_AUDIT */
1212 * AIX has a "usrinfo" area where logname and
1213 * other stuff is stored - a few applications
1214 * actually use this and die if it's not set
1218 cp = xmalloc(22 + strlen(s->tty) +
1219 2 * strlen(pw->pw_name));
1220 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1221 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1222 if (usrinfo(SETUINFO, cp, i) == -1)
1223 fatal("Couldn't set usrinfo: %s",
1225 debug3("AIX/UsrInfo: set len %d", i);
1229 /* Permanently switch to the desired uid. */
1230 permanently_set_uid(pw);
1231 # endif /* HAVE_LOGIN_CAP */
1233 #endif /* HAVE_OSF_SIA */
1238 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1239 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1242 * Get the shell from the password data. An empty shell field is
1243 * legal, and means /bin/sh.
1245 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1246 #ifdef HAVE_LOGIN_CAP
1247 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1251 /* Try to get AFS tokens for the local cell. */
1255 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1256 krb_afslog(cell, 0);
1262 /* Initialize the environment. */
1264 env = xmalloc(envsize * sizeof(char *));
1269 * The Windows environment contains some setting which are
1270 * important for a running system. They must not be dropped.
1272 copy_environment(&env, &envsize);
1275 if (!options.use_login) {
1276 /* Set basic environment. */
1277 child_set_env(&env, &envsize, "USER", pw->pw_name);
1278 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1279 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1280 #ifdef HAVE_LOGIN_CAP
1281 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1282 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1283 #else /* HAVE_LOGIN_CAP */
1284 # ifndef HAVE_CYGWIN
1286 * There's no standard path on Windows. The path contains
1287 * important components pointing to the system directories,
1288 * needed for loading shared libraries. So the path better
1289 * remains intact here.
1291 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1292 # endif /* HAVE_CYGWIN */
1293 #endif /* HAVE_LOGIN_CAP */
1295 snprintf(buf, sizeof buf, "%.200s/%.50s",
1296 _PATH_MAILDIR, pw->pw_name);
1297 child_set_env(&env, &envsize, "MAIL", buf);
1299 /* Normal systems set SHELL by default. */
1300 child_set_env(&env, &envsize, "SHELL", shell);
1303 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1305 /* Set custom environment options from RSA authentication. */
1306 while (custom_environment) {
1307 struct envstring *ce = custom_environment;
1310 for (i = 0; s[i] != '=' && s[i]; i++);
1313 child_set_env(&env, &envsize, s, s + i + 1);
1315 custom_environment = ce->next;
1320 snprintf(buf, sizeof buf, "%.50s %d %d",
1321 get_remote_ipaddr(), get_remote_port(), get_local_port());
1322 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1325 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1327 child_set_env(&env, &envsize, "TERM", s->term);
1329 child_set_env(&env, &envsize, "DISPLAY", s->display);
1330 if (original_command)
1331 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1335 if ((cp = getenv("AUTHSTATE")) != NULL)
1336 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1337 if ((cp = getenv("KRB5CCNAME")) != NULL)
1338 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1339 read_environment_file(&env, &envsize, "/etc/environment");
1344 extern char *ticket;
1347 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1352 /* Pull in any environment variables that may have been set by PAM. */
1353 do_pam_environment(&env, &envsize);
1354 #endif /* USE_PAM */
1357 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1358 if (auth_get_socket_name() != NULL)
1359 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1360 auth_get_socket_name());
1362 /* read $HOME/.ssh/environment. */
1363 if (!options.use_login) {
1364 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1366 read_environment_file(&env, &envsize, buf);
1369 /* dump the environment */
1370 fprintf(stderr, "Environment:\n");
1371 for (i = 0; env[i]; i++)
1372 fprintf(stderr, " %.200s\n", env[i]);
1374 /* we have to stash the hostname before we close our socket. */
1375 if (options.use_login)
1376 hostname = get_remote_name_or_ip(utmp_len,
1377 options.reverse_mapping_check);
1379 * Close the connection descriptors; note that this is the child, and
1380 * the server will still have the socket open, and it is important
1381 * that we do not shutdown it. Note that the descriptors cannot be
1382 * closed before building the environment, as we call
1383 * get_remote_ipaddr there.
1385 if (packet_get_connection_in() == packet_get_connection_out())
1386 close(packet_get_connection_in());
1388 close(packet_get_connection_in());
1389 close(packet_get_connection_out());
1392 * Close all descriptors related to channels. They will still remain
1393 * open in the parent.
1395 /* XXX better use close-on-exec? -markus */
1396 channel_close_all();
1399 * Close any extra file descriptors. Note that there may still be
1400 * descriptors left by system functions. They will be closed later.
1405 * Close any extra open file descriptors so that we don\'t have them
1406 * hanging around in clients. Note that we want to do this after
1407 * initgroups, because at least on Solaris 2.3 it leaves file
1410 for (i = 3; i < 64; i++)
1413 /* Change current directory to the user\'s home directory. */
1414 if (chdir(pw->pw_dir) < 0) {
1415 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1416 pw->pw_dir, strerror(errno));
1417 #ifdef HAVE_LOGIN_CAP
1418 if (login_getcapbool(lc, "requirehome", 0))
1424 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1425 * xauth are run in the proper environment.
1430 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1433 if (!options.use_login) {
1434 /* ignore _PATH_SSH_USER_RC for subsystems */
1435 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1436 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1437 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1439 fprintf(stderr, "Running %s\n", cmd);
1440 f = popen(cmd, "w");
1443 fprintf(f, "%s %s\n", s->auth_proto,
1447 fprintf(stderr, "Could not run %s\n",
1449 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1451 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1452 _PATH_SSH_SYSTEM_RC);
1453 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1456 fprintf(f, "%s %s\n", s->auth_proto,
1460 fprintf(stderr, "Could not run %s\n",
1461 _PATH_SSH_SYSTEM_RC);
1462 } else if (do_xauth && options.xauth_location != NULL) {
1463 /* Add authority data to .Xauthority if appropriate. */
1464 char *screen = strchr(s->display, ':');
1468 "Running %.100s add "
1469 "%.100s %.100s %.100s\n",
1470 options.xauth_location, s->display,
1471 s->auth_proto, s->auth_data);
1474 "Adding %.*s/unix%s %s %s\n",
1475 (int)(screen - s->display),
1477 s->auth_proto, s->auth_data);
1479 snprintf(cmd, sizeof cmd, "%s -q -",
1480 options.xauth_location);
1481 f = popen(cmd, "w");
1483 fprintf(f, "add %s %s %s\n", s->display,
1484 s->auth_proto, s->auth_data);
1486 fprintf(f, "add %.*s/unix%s %s %s\n",
1487 (int)(screen - s->display),
1493 fprintf(stderr, "Could not run %s\n",
1497 /* Get the last component of the shell name. */
1498 cp = strrchr(shell, '/');
1505 /* restore SIGPIPE for child */
1506 signal(SIGPIPE, SIG_DFL);
1509 * If we have no command, execute the shell. In this case, the shell
1510 * name to be passed in argv[0] is preceded by '-' to indicate that
1511 * this is a login shell.
1514 if (!options.use_login) {
1518 * Check for mail if we have a tty and it was enabled
1519 * in server options.
1521 if (s->ttyfd != -1 && options.check_mail) {
1523 struct stat mailstat;
1525 mailbox = getenv("MAIL");
1526 if (mailbox != NULL) {
1527 if (stat(mailbox, &mailstat) != 0 ||
1528 mailstat.st_size == 0)
1529 printf("No mail.\n");
1530 else if (mailstat.st_mtime < mailstat.st_atime)
1531 printf("You have mail.\n");
1533 printf("You have new mail.\n");
1536 /* Start the shell. Set initial character to '-'. */
1538 strncpy(buf + 1, cp, sizeof(buf) - 1);
1539 buf[sizeof(buf) - 1] = 0;
1541 /* Execute the shell. */
1544 execve(shell, argv, env);
1546 /* Executing the shell failed. */
1551 /* Launch login(1). */
1553 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1554 #ifdef LOGIN_NEEDS_TERM
1555 s->term? s->term : "unknown",
1557 "-p", "-f", "--", pw->pw_name, NULL);
1559 /* Login couldn't be executed, die. */
1566 * Execute the command using the user's shell. This uses the -c
1567 * option to execute the command.
1569 argv[0] = (char *) cp;
1571 argv[2] = (char *) command;
1573 execve(shell, argv, env);
1582 static int did_init = 0;
1584 debug("session_new: init");
1585 for(i = 0; i < MAX_SESSIONS; i++) {
1586 sessions[i].used = 0;
1587 sessions[i].self = i;
1591 for(i = 0; i < MAX_SESSIONS; i++) {
1592 Session *s = &sessions[i];
1594 memset(s, 0, sizeof(*s));
1599 debug("session_new: session %d", i);
1610 for(i = 0; i < MAX_SESSIONS; i++) {
1611 Session *s = &sessions[i];
1612 debug("dump: used %d session %d %p channel %d pid %d",
1622 session_open(int chanid)
1624 Session *s = session_new();
1625 debug("session_open: channel %d", chanid);
1627 error("no more sessions");
1630 s->pw = auth_get_user();
1632 fatal("no user for session %d", s->self);
1633 debug("session_open: session %d: link with channel %d", s->self, chanid);
1639 session_by_channel(int id)
1642 for(i = 0; i < MAX_SESSIONS; i++) {
1643 Session *s = &sessions[i];
1644 if (s->used && s->chanid == id) {
1645 debug("session_by_channel: session %d channel %d", i, id);
1649 debug("session_by_channel: unknown channel %d", id);
1655 session_by_pid(pid_t pid)
1658 debug("session_by_pid: pid %d", pid);
1659 for(i = 0; i < MAX_SESSIONS; i++) {
1660 Session *s = &sessions[i];
1661 if (s->used && s->pid == pid)
1664 error("session_by_pid: unknown pid %d", pid);
1670 session_window_change_req(Session *s)
1672 s->col = packet_get_int();
1673 s->row = packet_get_int();
1674 s->xpixel = packet_get_int();
1675 s->ypixel = packet_get_int();
1677 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1682 session_pty_req(Session *s)
1691 s->term = packet_get_string(&len);
1692 s->col = packet_get_int();
1693 s->row = packet_get_int();
1694 s->xpixel = packet_get_int();
1695 s->ypixel = packet_get_int();
1697 if (strcmp(s->term, "") == 0) {
1701 /* Allocate a pty and open it. */
1702 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1707 error("session_pty_req: session %d alloc failed", s->self);
1710 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1712 * Add a cleanup function to clear the utmp entry and record logout
1713 * time in case we call fatal() (e.g., the connection gets closed).
1715 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1716 pty_setowner(s->pw, s->tty);
1717 /* Get window size from the packet. */
1718 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1720 /* Get tty modes from the packet. */
1721 tty_parse_modes(s->ttyfd, &n_bytes);
1724 session_proctitle(s);
1730 session_subsystem_req(Session *s)
1734 char *subsys = packet_get_string(&len);
1738 log("subsystem request for %s", subsys);
1740 for (i = 0; i < options.num_subsystems; i++) {
1741 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1742 debug("subsystem: exec() %s", options.subsystem_command[i]);
1743 s->is_subsystem = 1;
1744 do_exec_no_pty(s, options.subsystem_command[i]);
1750 log("subsystem request for %s failed, subsystem not found", subsys);
1757 session_x11_req(Session *s)
1761 if (no_x11_forwarding_flag) {
1762 debug("X11 forwarding disabled in user configuration file.");
1765 if (!options.x11_forwarding) {
1766 debug("X11 forwarding disabled in server configuration file.");
1769 if (!options.xauth_location ||
1770 (stat(options.xauth_location, &st) == -1)) {
1771 packet_send_debug("No xauth program; cannot forward with spoofing.");
1774 if (xauthfile != NULL) {
1775 debug("X11 fwd already started.");
1779 debug("Received request for X11 forwarding with auth spoofing.");
1780 if (s->display != NULL)
1781 packet_disconnect("Protocol error: X11 display already set.");
1783 s->single_connection = packet_get_char();
1784 s->auth_proto = packet_get_string(NULL);
1785 s->auth_data = packet_get_string(NULL);
1786 s->screen = packet_get_int();
1789 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1790 if (s->display == NULL) {
1791 xfree(s->auth_proto);
1792 xfree(s->auth_data);
1795 xauthfile = xmalloc(MAXPATHLEN);
1796 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1797 temporarily_use_uid(s->pw);
1798 if (mkdtemp(xauthfile) == NULL) {
1800 error("private X11 dir: mkdtemp %s failed: %s",
1801 xauthfile, strerror(errno));
1804 xfree(s->auth_proto);
1805 xfree(s->auth_data);
1806 /* XXXX remove listening channels */
1809 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1810 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1814 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1819 session_shell_req(Session *s)
1821 /* if forced_command == NULL, the shell is execed */
1822 char *shell = forced_command;
1825 do_exec_no_pty(s, shell);
1827 do_exec_pty(s, shell);
1832 session_exec_req(Session *s)
1835 char *command = packet_get_string(&len);
1837 if (forced_command) {
1838 original_command = command;
1839 command = forced_command;
1840 debug("Forced command '%.500s'", forced_command);
1843 do_exec_no_pty(s, command);
1845 do_exec_pty(s, command);
1846 if (forced_command == NULL)
1852 session_auth_agent_req(Session *s)
1854 static int called = 0;
1856 if (no_agent_forwarding_flag) {
1857 debug("session_auth_agent_req: no_agent_forwarding_flag");
1864 return auth_input_request_forwarding(s->pw);
1869 session_input_channel_req(int id, void *arg)
1878 rtype = packet_get_string(&len);
1879 reply = packet_get_char();
1881 s = session_by_channel(id);
1883 fatal("session_input_channel_req: channel %d: no session", id);
1884 c = channel_lookup(id);
1886 fatal("session_input_channel_req: channel %d: bad channel", id);
1888 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1889 s->self, id, rtype, reply);
1892 * a session is in LARVAL state until a shell, a command
1893 * or a subsystem is executed
1895 if (c->type == SSH_CHANNEL_LARVAL) {
1896 if (strcmp(rtype, "shell") == 0) {
1897 success = session_shell_req(s);
1898 } else if (strcmp(rtype, "exec") == 0) {
1899 success = session_exec_req(s);
1900 } else if (strcmp(rtype, "pty-req") == 0) {
1901 success = session_pty_req(s);
1902 } else if (strcmp(rtype, "x11-req") == 0) {
1903 success = session_x11_req(s);
1904 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1905 success = session_auth_agent_req(s);
1906 } else if (strcmp(rtype, "subsystem") == 0) {
1907 success = session_subsystem_req(s);
1910 if (strcmp(rtype, "window-change") == 0) {
1911 success = session_window_change_req(s);
1915 packet_start(success ?
1916 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1917 packet_put_int(c->remote_id);
1924 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1927 fatal("session_set_fds: called for proto != 2.0");
1929 * now that have a child and a pipe to the child,
1930 * we can activate our channel and register the fd's
1932 if (s->chanid == -1)
1933 fatal("no channel for session %d", s->self);
1934 channel_set_fds(s->chanid,
1936 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1941 session_pty_cleanup(Session *s)
1943 if (s == NULL || s->ttyfd == -1)
1946 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1948 /* Cancel the cleanup function. */
1949 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1951 /* Record that the user has logged out. */
1952 record_logout(s->pid, s->tty);
1954 /* Release the pseudo-tty. */
1955 pty_release(s->tty);
1958 * Close the server side of the socket pairs. We must do this after
1959 * the pty cleanup, so that another process doesn't get this pty
1960 * while we're still cleaning up.
1962 if (close(s->ptymaster) < 0)
1963 error("close(s->ptymaster): %s", strerror(errno));
1967 session_exit_message(Session *s, int status)
1971 fatal("session_close: no session");
1972 c = channel_lookup(s->chanid);
1974 fatal("session_close: session %d: no channel %d",
1975 s->self, s->chanid);
1976 debug("session_exit_message: session %d channel %d pid %d",
1977 s->self, s->chanid, s->pid);
1979 if (WIFEXITED(status)) {
1980 channel_request_start(s->chanid,
1982 packet_put_int(WEXITSTATUS(status));
1984 } else if (WIFSIGNALED(status)) {
1985 channel_request_start(s->chanid,
1987 packet_put_int(WTERMSIG(status));
1989 packet_put_char(WCOREDUMP(status));
1990 #else /* WCOREDUMP */
1992 #endif /* WCOREDUMP */
1993 packet_put_cstring("");
1994 packet_put_cstring("");
1997 /* Some weird exit cause. Just exit. */
1998 packet_disconnect("wait returned status %04x.", status);
2001 /* disconnect channel */
2002 debug("session_exit_message: release channel %d", s->chanid);
2003 channel_cancel_cleanup(s->chanid);
2005 * emulate a write failure with 'chan_write_failed', nobody will be
2006 * interested in data we write.
2007 * Note that we must not call 'chan_read_failed', since there could
2008 * be some more data waiting in the pipe.
2010 if (c->ostate != CHAN_OUTPUT_CLOSED)
2011 chan_write_failed(c);
2016 session_free(Session *s)
2018 debug("session_free: session %d pid %d", s->self, s->pid);
2024 xfree(s->auth_data);
2026 xfree(s->auth_proto);
2031 session_close(Session *s)
2033 session_pty_cleanup(s);
2035 session_proctitle(s);
2039 session_close_by_pid(pid_t pid, int status)
2041 Session *s = session_by_pid(pid);
2043 debug("session_close_by_pid: no session for pid %d", s->pid);
2046 if (s->chanid != -1)
2047 session_exit_message(s, status);
2052 * this is called when a channel dies before
2053 * the session 'child' itself dies
2056 session_close_by_channel(int id, void *arg)
2058 Session *s = session_by_channel(id);
2060 debug("session_close_by_channel: no session for channel %d", id);
2063 /* disconnect channel */
2064 channel_cancel_cleanup(s->chanid);
2067 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
2069 /* close session immediately */
2072 /* notify child, delay session cleanup */
2073 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
2074 error("session_close_by_channel: kill %d: %s",
2075 s->pid, strerror(errno));
2080 session_tty_list(void)
2082 static char buf[1024];
2085 for(i = 0; i < MAX_SESSIONS; i++) {
2086 Session *s = &sessions[i];
2087 if (s->used && s->ttyfd != -1) {
2089 strlcat(buf, ",", sizeof buf);
2090 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2094 strlcpy(buf, "notty", sizeof buf);
2099 session_proctitle(Session *s)
2102 error("no user for session %d", s->self);
2104 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2108 do_authenticated2(Authctxt *authctxt)