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.75 2001/05/03 15:45:15 markus Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
61 #ifdef WITH_IRIX_PROJECT
63 #endif /* WITH_IRIX_PROJECT */
65 #include <sys/resource.h>
67 #ifdef WITH_IRIX_AUDIT
69 #endif /* WITH_IRIX_AUDIT */
71 #if defined(HAVE_USERSEC_H)
77 #include <sys/cygwin.h>
78 #define is_winnt (GetVersion() < 0x80000000)
82 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
83 # define S_UFSIZE_HARD S_UFSIZE "_hard"
84 # define S_UCPU_HARD S_UCPU "_hard"
85 # define S_UDATA_HARD S_UDATA "_hard"
86 # define S_USTACK_HARD S_USTACK "_hard"
87 # define S_URSS_HARD S_URSS "_hard"
88 # define S_UCORE_HARD S_UCORE "_hard"
89 # define S_UNOFILE_HARD S_UNOFILE "_hard"
99 typedef struct Session Session;
107 int ptyfd, ttyfd, ptymaster;
108 int row, col, xpixel, ypixel;
115 int single_connection;
123 Session *session_new(void);
124 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
125 void session_pty_cleanup(Session *s);
126 void session_proctitle(Session *s);
127 void do_exec_pty(Session *s, const char *command);
128 void do_exec_no_pty(Session *s, const char *command);
129 void do_login(Session *s, const char *command);
130 void do_child(Session *s, const char *command);
132 int check_quietlogin(Session *s, const char *command);
134 void do_authenticated1(Authctxt *authctxt);
135 void do_authenticated2(Authctxt *authctxt);
138 extern ServerOptions options;
139 extern char *__progname;
140 extern int log_stderr;
141 extern int debug_flag;
142 extern u_int utmp_len;
143 extern int startup_pipe;
144 extern void destroy_sensitive_data(void);
146 /* Local Xauthority file. */
147 static char *xauthfile;
149 /* original command from peer. */
150 char *original_command = NULL;
153 #define MAX_SESSIONS 10
154 Session sessions[MAX_SESSIONS];
156 #ifdef WITH_AIXAUTHENTICATE
157 /* AIX's lastlogin message, set in auth1.c */
159 #endif /* WITH_AIXAUTHENTICATE */
161 #ifdef HAVE_LOGIN_CAP
162 static login_cap_t *lc;
166 do_authenticated(Authctxt *authctxt)
169 * Cancel the alarm we set to limit the time taken for
173 if (startup_pipe != -1) {
177 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
178 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
179 error("unable to get login class");
183 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
184 packet_disconnect("Approval failure for %s",
185 authctxt->pw->pw_name);
189 /* setup the channel layer */
190 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
191 channel_permit_all_opens();
194 do_authenticated2(authctxt);
196 do_authenticated1(authctxt);
200 * Remove local Xauthority file.
203 xauthfile_cleanup_proc(void *ignore)
205 debug("xauthfile_cleanup_proc called");
207 if (xauthfile != NULL) {
210 p = strrchr(xauthfile, '/');
221 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
222 * dropped connection).
225 pty_cleanup_proc(void *session)
229 fatal("pty_cleanup_proc: no session");
230 debug("pty_cleanup_proc: %s", s->tty);
233 /* Record that the user has logged out. */
234 record_logout(s->pid, s->tty);
237 /* Release the pseudo-tty. */
242 * Prepares for an interactive session. This is called after the user has
243 * been successfully authenticated. During this message exchange, pseudo
244 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
245 * are requested, etc.
248 do_authenticated1(Authctxt *authctxt)
252 int success, type, fd, n_bytes, plen, screen_flag, have_pty = 0;
253 int compression_level = 0, enable_compression_after_reply = 0;
254 u_int proto_len, data_len, dlen;
257 s->pw = authctxt->pw;
260 * We stay in this loop until the client requests to execute a shell
266 /* Get a packet from the client. */
267 type = packet_read(&plen);
269 /* Process the packet. */
271 case SSH_CMSG_REQUEST_COMPRESSION:
272 packet_integrity_check(plen, 4, type);
273 compression_level = packet_get_int();
274 if (compression_level < 1 || compression_level > 9) {
275 packet_send_debug("Received illegal compression level %d.",
279 /* Enable compression after we have responded with SUCCESS. */
280 enable_compression_after_reply = 1;
284 case SSH_CMSG_REQUEST_PTY:
286 debug("Allocating a pty not permitted for this authentication.");
290 packet_disconnect("Protocol error: you already have a pty.");
292 debug("Allocating pty.");
294 /* Allocate a pty and open it. */
295 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
297 error("Failed to allocate pty.");
300 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
301 pty_setowner(s->pw, s->tty);
303 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
304 s->term = packet_get_string(&dlen);
305 packet_integrity_check(dlen, strlen(s->term), type);
306 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
307 /* Remaining bytes */
308 n_bytes = plen - (4 + dlen + 4 * 4);
310 if (strcmp(s->term, "") == 0) {
314 /* Get window size from the packet. */
315 s->row = packet_get_int();
316 s->col = packet_get_int();
317 s->xpixel = packet_get_int();
318 s->ypixel = packet_get_int();
319 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
321 /* Get tty modes from the packet. */
322 tty_parse_modes(s->ttyfd, &n_bytes);
323 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
325 session_proctitle(s);
327 /* Indicate that we now have a pty. */
332 case SSH_CMSG_X11_REQUEST_FORWARDING:
333 if (!options.x11_forwarding) {
334 packet_send_debug("X11 forwarding disabled in server configuration file.");
337 if (!options.xauth_location) {
338 packet_send_debug("No xauth program; cannot forward with spoofing.");
341 if (no_x11_forwarding_flag) {
342 packet_send_debug("X11 forwarding not permitted for this authentication.");
345 debug("Received request for X11 forwarding with auth spoofing.");
346 if (s->display != NULL)
347 packet_disconnect("Protocol error: X11 display already set.");
349 s->auth_proto = packet_get_string(&proto_len);
350 s->auth_data = packet_get_string(&data_len);
352 screen_flag = packet_get_protocol_flags() &
353 SSH_PROTOFLAG_SCREEN_NUMBER;
354 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
356 if (packet_remaining() == 4) {
358 debug2("Buggy client: "
359 "X11 screen flag missing");
360 packet_integrity_check(plen,
361 4 + proto_len + 4 + data_len + 4, type);
362 s->screen = packet_get_int();
364 packet_integrity_check(plen,
365 4 + proto_len + 4 + data_len, type);
368 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
370 if (s->display == NULL)
373 /* Setup to always have a local .Xauthority. */
374 xauthfile = xmalloc(MAXPATHLEN);
375 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
376 temporarily_use_uid(s->pw);
377 if (mkdtemp(xauthfile) == NULL) {
379 error("private X11 dir: mkdtemp %s failed: %s",
380 xauthfile, strerror(errno));
383 /* XXXX remove listening channels */
386 strlcat(xauthfile, "/cookies", MAXPATHLEN);
387 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
391 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
395 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
396 if (no_agent_forwarding_flag || compat13) {
397 debug("Authentication agent forwarding not permitted for this authentication.");
400 debug("Received authentication agent forwarding request.");
401 success = auth_input_request_forwarding(s->pw);
404 case SSH_CMSG_PORT_FORWARD_REQUEST:
405 if (no_port_forwarding_flag) {
406 debug("Port forwarding not permitted for this authentication.");
409 if (!options.allow_tcp_forwarding) {
410 debug("Port forwarding not permitted.");
413 debug("Received TCP/IP port forwarding request.");
414 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
418 case SSH_CMSG_MAX_PACKET_SIZE:
419 if (packet_set_maxsize(packet_get_int()) > 0)
423 case SSH_CMSG_EXEC_SHELL:
424 case SSH_CMSG_EXEC_CMD:
425 if (type == SSH_CMSG_EXEC_CMD) {
426 command = packet_get_string(&dlen);
427 debug("Exec command '%.500s'", command);
428 packet_integrity_check(plen, 4 + dlen, type);
431 packet_integrity_check(plen, 0, type);
433 if (forced_command != NULL) {
434 original_command = command;
435 command = forced_command;
436 debug("Forced command '%.500s'", forced_command);
439 do_exec_pty(s, command);
441 do_exec_no_pty(s, command);
445 /* Cleanup user's local Xauthority file. */
447 xauthfile_cleanup_proc(NULL);
452 * Any unknown messages in this phase are ignored,
453 * and a failure message is returned.
455 log("Unknown packet type received after authentication: %d", type);
457 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
461 /* Enable compression now that we have replied if appropriate. */
462 if (enable_compression_after_reply) {
463 enable_compression_after_reply = 0;
464 packet_start_compression(compression_level);
470 * This is called to fork and execute a command when we have no tty. This
471 * will call do_child from the child, and server_loop from the parent after
472 * setting up file descriptors and such.
475 do_exec_no_pty(Session *s, const char *command)
480 int pin[2], pout[2], perr[2];
481 /* Allocate pipes for communicating with the program. */
482 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
483 packet_disconnect("Could not create pipes: %.100s",
485 #else /* USE_PIPES */
486 int inout[2], err[2];
487 /* Uses socket pairs to communicate with the program. */
488 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
489 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
490 packet_disconnect("Could not create socket pairs: %.100s",
492 #endif /* USE_PIPES */
494 fatal("do_exec_no_pty: no session");
496 session_proctitle(s);
502 /* Fork the child. */
503 if ((pid = fork()) == 0) {
504 /* Child. Reinitialize the log since the pid has changed. */
505 log_init(__progname, options.log_level, options.log_facility, log_stderr);
508 * Create a new session and process group since the 4.4BSD
509 * setlogin() affects the entire process group.
512 error("setsid failed: %.100s", strerror(errno));
516 * Redirect stdin. We close the parent side of the socket
517 * pair, and make the child side the standard input.
520 if (dup2(pin[0], 0) < 0)
521 perror("dup2 stdin");
524 /* Redirect stdout. */
526 if (dup2(pout[1], 1) < 0)
527 perror("dup2 stdout");
530 /* Redirect stderr. */
532 if (dup2(perr[1], 2) < 0)
533 perror("dup2 stderr");
535 #else /* USE_PIPES */
537 * Redirect stdin, stdout, and stderr. Stdin and stdout will
538 * use the same socket, as some programs (particularly rdist)
539 * seem to depend on it.
543 if (dup2(inout[0], 0) < 0) /* stdin */
544 perror("dup2 stdin");
545 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
546 perror("dup2 stdout");
547 if (dup2(err[0], 2) < 0) /* stderr */
548 perror("dup2 stderr");
549 #endif /* USE_PIPES */
551 /* Do processing for the child (exec command etc). */
552 do_child(s, command);
557 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
560 packet_disconnect("fork failed: %.100s", strerror(errno));
562 /* Set interactive/non-interactive mode. */
563 packet_set_interactive(s->display != NULL);
565 /* We are the parent. Close the child sides of the pipes. */
571 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
573 /* Enter the interactive session. */
574 server_loop(pid, pin[1], pout[0], perr[0]);
575 /* server_loop has closed pin[1], pout[0], and perr[0]. */
577 #else /* USE_PIPES */
578 /* We are the parent. Close the child sides of the socket pairs. */
583 * Enter the interactive session. Note: server_loop must be able to
584 * handle the case that fdin and fdout are the same.
587 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
589 server_loop(pid, inout[1], inout[1], err[1]);
590 /* server_loop has closed inout[1] and err[1]. */
592 #endif /* USE_PIPES */
596 * This is called to fork and execute a command when we have a tty. This
597 * will call do_child from the child, and server_loop from the parent after
598 * setting up file descriptors, controlling tty, updating wtmp, utmp,
599 * lastlog, and other such operations.
602 do_exec_pty(Session *s, const char *command)
604 int fdout, ptyfd, ttyfd, ptymaster;
608 fatal("do_exec_pty: no session");
613 do_pam_session(s->pw->pw_name, s->tty);
617 /* Fork the child. */
618 if ((pid = fork()) == 0) {
619 /* Child. Reinitialize the log because the pid has changed. */
620 log_init(__progname, options.log_level, options.log_facility, log_stderr);
622 /* Close the master side of the pseudo tty. */
625 /* Make the pseudo tty our controlling tty. */
626 pty_make_controlling_tty(&ttyfd, s->tty);
628 /* Redirect stdin from the pseudo tty. */
629 if (dup2(ttyfd, fileno(stdin)) < 0)
630 error("dup2 stdin failed: %.100s", strerror(errno));
632 /* Redirect stdout to the pseudo tty. */
633 if (dup2(ttyfd, fileno(stdout)) < 0)
634 error("dup2 stdin failed: %.100s", strerror(errno));
636 /* Redirect stderr to the pseudo tty. */
637 if (dup2(ttyfd, fileno(stderr)) < 0)
638 error("dup2 stdin failed: %.100s", strerror(errno));
640 /* Close the extra descriptor for the pseudo tty. */
643 /* record login, etc. similar to login(1) */
645 if (!(options.use_login && command == NULL))
646 do_login(s, command);
649 /* Do common processing for the child, such as execing the command. */
650 do_child(s, command);
655 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
658 packet_disconnect("fork failed: %.100s", strerror(errno));
661 /* Parent. Close the slave side of the pseudo tty. */
665 * Create another descriptor of the pty master side for use as the
666 * standard input. We could use the original descriptor, but this
667 * simplifies code in server_loop. The descriptor is bidirectional.
671 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
673 /* we keep a reference to the pty master */
674 ptymaster = dup(ptyfd);
676 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
677 s->ptymaster = ptymaster;
679 /* Enter interactive session. */
680 packet_set_interactive(1);
682 session_set_fds(s, ptyfd, fdout, -1);
684 server_loop(pid, ptyfd, fdout, -1);
685 /* server_loop _has_ closed ptyfd and fdout. */
686 session_pty_cleanup(s);
690 /* administrative, login(1)-like work */
692 do_login(Session *s, const char *command)
695 char hostname[MAXHOSTNAMELEN];
697 struct sockaddr_storage from;
698 time_t last_login_time;
699 struct passwd * pw = s->pw;
700 pid_t pid = getpid();
703 * Get IP address of client. If the connection is not a socket, let
704 * the address be 0.0.0.0.
706 memset(&from, 0, sizeof(from));
707 if (packet_connection_is_on_socket()) {
708 fromlen = sizeof(from);
709 if (getpeername(packet_get_connection_in(),
710 (struct sockaddr *) & from, &fromlen) < 0) {
711 debug("getpeername: %.100s", strerror(errno));
716 /* Get the time and hostname when the user last logged in. */
717 if (options.print_lastlog) {
719 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
720 hostname, sizeof(hostname));
723 /* Record that there was a login on that tty from the remote host. */
724 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
725 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
726 (struct sockaddr *)&from);
730 * If password change is needed, do it now.
731 * This needs to occur before the ~/.hushlogin check.
733 if (is_pam_password_change_required()) {
734 print_pam_messages();
739 if (check_quietlogin(s, command))
743 if (!is_pam_password_change_required())
744 print_pam_messages();
746 #ifdef WITH_AIXAUTHENTICATE
747 if (aixloginmsg && *aixloginmsg)
748 printf("%s\n", aixloginmsg);
749 #endif /* WITH_AIXAUTHENTICATE */
751 if (options.print_lastlog && last_login_time != 0) {
752 time_string = ctime(&last_login_time);
753 if (strchr(time_string, '\n'))
754 *strchr(time_string, '\n') = 0;
755 if (strcmp(hostname, "") == 0)
756 printf("Last login: %s\r\n", time_string);
758 printf("Last login: %s from %s\r\n", time_string, hostname);
765 * Display the message of the day.
773 if (options.print_motd) {
774 #ifdef HAVE_LOGIN_CAP
775 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
778 f = fopen("/etc/motd", "r");
781 while (fgets(buf, sizeof(buf), f))
790 * Check for quiet login, either .hushlogin or command given.
793 check_quietlogin(Session *s, const char *command)
796 struct passwd * pw = s->pw;
799 /* Return 1 if .hushlogin exists or a command given. */
802 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
803 #ifdef HAVE_LOGIN_CAP
804 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
807 if (stat(buf, &st) >= 0)
814 * Sets the value of the given variable in the environment. If the variable
815 * already exists, its value is overriden.
818 child_set_env(char ***envp, u_int *envsizep, const char *name,
825 * Find the slot where the value should be stored. If the variable
826 * already exists, we reuse the slot; otherwise we append a new slot
827 * at the end of the array, expanding if necessary.
830 namelen = strlen(name);
831 for (i = 0; env[i]; i++)
832 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
835 /* Reuse the slot. */
838 /* New variable. Expand if necessary. */
839 if (i >= (*envsizep) - 1) {
841 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
843 /* Need to set the NULL pointer at end of array beyond the new slot. */
847 /* Allocate space and format the variable in the appropriate slot. */
848 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
849 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
853 * Reads environment variables from the given file and adds/overrides them
854 * into the environment. If the file does not exist, this does nothing.
855 * Otherwise, it must consist of empty lines, comments (line starts with '#')
856 * and assignments of the form name=value. No other forms are allowed.
859 read_environment_file(char ***env, u_int *envsize,
860 const char *filename)
866 f = fopen(filename, "r");
870 while (fgets(buf, sizeof(buf), f)) {
871 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
873 if (!*cp || *cp == '#' || *cp == '\n')
875 if (strchr(cp, '\n'))
876 *strchr(cp, '\n') = '\0';
877 value = strchr(cp, '=');
879 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
883 * Replace the equals sign by nul, and advance value to
888 child_set_env(env, envsize, cp, value);
895 * Sets any environment variables which have been specified by PAM
897 void do_pam_environment(char ***env, int *envsize)
899 char *equals, var_name[512], var_val[512];
903 if ((pam_env = fetch_pam_environment()) == NULL)
906 for(i = 0; pam_env[i] != NULL; i++) {
907 if ((equals = strstr(pam_env[i], "=")) == NULL)
910 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
911 memset(var_name, '\0', sizeof(var_name));
912 memset(var_val, '\0', sizeof(var_val));
914 strncpy(var_name, pam_env[i], equals - pam_env[i]);
915 strcpy(var_val, equals + 1);
917 debug3("PAM environment: %s=%s", var_name, var_val);
919 child_set_env(env, envsize, var_name, var_val);
926 void copy_environment(char ***env, int *envsize)
928 char *equals, var_name[512], var_val[512];
931 for(i = 0; environ[i] != NULL; i++) {
932 if ((equals = strstr(environ[i], "=")) == NULL)
935 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
936 memset(var_name, '\0', sizeof(var_name));
937 memset(var_val, '\0', sizeof(var_val));
939 strncpy(var_name, environ[i], equals - environ[i]);
940 strcpy(var_val, equals + 1);
942 debug3("Copy environment: %s=%s", var_name, var_val);
944 child_set_env(env, envsize, var_name, var_val);
950 #if defined(HAVE_GETUSERATTR)
952 * AIX-specific login initialisation
954 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
959 getrlimit(resource, &rlim);
962 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
964 rlim.rlim_cur = RLIM_INFINITY;
965 } else if (slim != 0) {
966 /* See the wackiness below */
967 if (rlim.rlim_cur == slim * mult)
970 rlim.rlim_cur = slim * mult;
975 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
977 rlim.rlim_max = RLIM_INFINITY;
978 } else if (hlim != 0) {
979 rlim.rlim_max = hlim * mult;
984 * XXX For cpu and fsize the soft limit is set to the hard limit
985 * if the hard limit is left at its default value and the soft limit
986 * is changed from its default value, either by requesting it
987 * (slim == 0) or by setting it to the current default. At least
988 * that's how rlogind does it. If you're confused you're not alone.
989 * Bug or feature? AIX 4.3.1.2
991 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
992 && hlim == 0 && slim != 0)
993 rlim.rlim_max = rlim.rlim_cur;
994 /* A specified hard limit limits the soft limit */
995 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
996 rlim.rlim_cur = rlim.rlim_max;
997 /* A soft limit can increase a hard limit */
998 else if (rlim.rlim_cur > rlim.rlim_max)
999 rlim.rlim_max = rlim.rlim_cur;
1001 if (setrlimit(resource, &rlim) != 0)
1002 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
1005 void set_limits_from_userattr(char *user)
1010 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
1011 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
1012 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
1013 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
1014 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
1015 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1016 #if defined(S_UNOFILE)
1017 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1020 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1021 /* Convert decimal to octal */
1022 (void) snprintf(buf, sizeof(buf), "%d", mask);
1023 if (sscanf(buf, "%o", &mask) == 1)
1027 #endif /* defined(HAVE_GETUSERATTR) */
1030 * Performs common processing for the child, such as setting up the
1031 * environment, closing extra file descriptors, setting the user and group
1032 * ids, and executing the command or shell.
1035 do_child(Session *s, const char *command)
1037 const char *shell, *hostname = NULL, *cp = NULL;
1038 struct passwd * pw = s->pw;
1044 extern char **environ;
1047 int do_xauth = s->auth_proto != NULL && s->auth_data != NULL;
1048 #ifdef WITH_IRIX_PROJECT
1050 #endif /* WITH_IRIX_PROJECT */
1051 #ifdef WITH_IRIX_JOBS
1054 #ifdef WITH_IRIX_ARRAY
1056 #endif /* WITH_IRIX_ARRAY */
1057 #endif /* WITH_IRIX_JOBS */
1059 /* remove hostkey from the child's memory */
1060 destroy_sensitive_data();
1062 /* login(1) is only called if we execute the login shell */
1063 if (options.use_login && command != NULL)
1064 options.use_login = 0;
1066 #if !defined(USE_PAM) && !defined(HAVE_OSF_SIA)
1067 if (!options.use_login) {
1068 # ifdef HAVE_LOGIN_CAP
1069 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1070 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1071 _PATH_NOLOGIN), "r");
1072 # else /* HAVE_LOGIN_CAP */
1074 f = fopen(_PATH_NOLOGIN, "r");
1075 # endif /* HAVE_LOGIN_CAP */
1077 /* /etc/nologin exists. Print its contents and exit. */
1078 while (fgets(buf, sizeof(buf), f))
1084 #endif /* USE_PAM || HAVE_OSF_SIA */
1086 /* Set login name, uid, gid, and groups. */
1087 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1088 switch, so we let login(1) to this for us. */
1089 if (!options.use_login) {
1091 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1092 if (!check_quietlogin(s, command))
1094 #else /* HAVE_OSF_SIA */
1098 if (getuid() == 0 || geteuid() == 0) {
1100 # ifdef HAVE_GETUSERATTR
1101 set_limits_from_userattr(pw->pw_name);
1102 # endif /* HAVE_GETUSERATTR */
1103 # ifdef HAVE_LOGIN_CAP
1104 if (setusercontext(lc, pw, pw->pw_uid,
1105 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1106 perror("unable to set user context");
1109 # else /* HAVE_LOGIN_CAP */
1110 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1111 /* Sets login uid for accounting */
1112 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1113 error("setluid: %s", strerror(errno));
1114 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1116 if (setlogin(pw->pw_name) < 0)
1117 error("setlogin failed: %s", strerror(errno));
1118 if (setgid(pw->pw_gid) < 0) {
1122 /* Initialize the group list. */
1123 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1124 perror("initgroups");
1130 * PAM credentials may take the form of
1131 * supplementary groups. These will have been
1132 * wiped by the above initgroups() call.
1133 * Reestablish them here.
1136 # endif /* USE_PAM */
1137 # ifdef WITH_IRIX_JOBS
1138 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1140 fatal("Failed to create job container: %.100s",
1143 # endif /* WITH_IRIX_JOBS */
1144 # ifdef WITH_IRIX_ARRAY
1145 /* initialize array session */
1147 if (newarraysess() != 0)
1148 fatal("Failed to set up new array session: %.100s",
1151 # endif /* WITH_IRIX_ARRAY */
1152 # ifdef WITH_IRIX_PROJECT
1153 /* initialize irix project info */
1154 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1155 debug("Failed to get project id, using projid 0");
1158 if (setprid(projid))
1159 fatal("Failed to initialize project %d for %s: %.100s",
1160 (int)projid, pw->pw_name, strerror(errno));
1161 # endif /* WITH_IRIX_PROJECT */
1162 #ifdef WITH_IRIX_AUDIT
1163 if (sysconf(_SC_AUDIT)) {
1164 debug("Setting sat id to %d", (int) pw->pw_uid);
1165 if (satsetid(pw->pw_uid))
1166 debug("error setting satid: %.100s", strerror(errno));
1168 #endif /* WITH_IRIX_AUDIT */
1172 * AIX has a "usrinfo" area where logname and
1173 * other stuff is stored - a few applications
1174 * actually use this and die if it's not set
1178 cp = xmalloc(22 + strlen(s->tty) +
1179 2 * strlen(pw->pw_name));
1180 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1181 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1182 if (usrinfo(SETUINFO, cp, i) == -1)
1183 fatal("Couldn't set usrinfo: %s",
1185 debug3("AIX/UsrInfo: set len %d", i);
1189 /* Permanently switch to the desired uid. */
1190 permanently_set_uid(pw);
1191 # endif /* HAVE_LOGIN_CAP */
1193 #endif /* HAVE_OSF_SIA */
1198 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1199 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1202 * Get the shell from the password data. An empty shell field is
1203 * legal, and means /bin/sh.
1205 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1206 #ifdef HAVE_LOGIN_CAP
1207 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1211 /* Try to get AFS tokens for the local cell. */
1215 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1216 krb_afslog(cell, 0);
1222 /* Initialize the environment. */
1224 env = xmalloc(envsize * sizeof(char *));
1229 * The Windows environment contains some setting which are
1230 * important for a running system. They must not be dropped.
1232 copy_environment(&env, &envsize);
1235 if (!options.use_login) {
1236 /* Set basic environment. */
1237 child_set_env(&env, &envsize, "USER", pw->pw_name);
1238 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1239 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1240 #ifdef HAVE_LOGIN_CAP
1241 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1242 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1243 #else /* HAVE_LOGIN_CAP */
1244 # ifndef HAVE_CYGWIN
1246 * There's no standard path on Windows. The path contains
1247 * important components pointing to the system directories,
1248 * needed for loading shared libraries. So the path better
1249 * remains intact here.
1251 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1252 # endif /* HAVE_CYGWIN */
1253 #endif /* HAVE_LOGIN_CAP */
1255 snprintf(buf, sizeof buf, "%.200s/%.50s",
1256 _PATH_MAILDIR, pw->pw_name);
1257 child_set_env(&env, &envsize, "MAIL", buf);
1259 /* Normal systems set SHELL by default. */
1260 child_set_env(&env, &envsize, "SHELL", shell);
1263 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1265 /* Set custom environment options from RSA authentication. */
1266 while (custom_environment) {
1267 struct envstring *ce = custom_environment;
1270 for (i = 0; s[i] != '=' && s[i]; i++);
1273 child_set_env(&env, &envsize, s, s + i + 1);
1275 custom_environment = ce->next;
1280 snprintf(buf, sizeof buf, "%.50s %d %d",
1281 get_remote_ipaddr(), get_remote_port(), get_local_port());
1282 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1285 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1287 child_set_env(&env, &envsize, "TERM", s->term);
1289 child_set_env(&env, &envsize, "DISPLAY", s->display);
1290 if (original_command)
1291 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1295 if ((cp = getenv("AUTHSTATE")) != NULL)
1296 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1297 if ((cp = getenv("KRB5CCNAME")) != NULL)
1298 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1299 read_environment_file(&env, &envsize, "/etc/environment");
1304 extern char *ticket;
1307 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1312 /* Pull in any environment variables that may have been set by PAM. */
1313 do_pam_environment(&env, &envsize);
1314 #endif /* USE_PAM */
1317 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1318 if (auth_get_socket_name() != NULL)
1319 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1320 auth_get_socket_name());
1322 /* read $HOME/.ssh/environment. */
1323 if (!options.use_login) {
1324 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1326 read_environment_file(&env, &envsize, buf);
1329 /* dump the environment */
1330 fprintf(stderr, "Environment:\n");
1331 for (i = 0; env[i]; i++)
1332 fprintf(stderr, " %.200s\n", env[i]);
1334 /* we have to stash the hostname before we close our socket. */
1335 if (options.use_login)
1336 hostname = get_remote_name_or_ip(utmp_len,
1337 options.reverse_mapping_check);
1339 * Close the connection descriptors; note that this is the child, and
1340 * the server will still have the socket open, and it is important
1341 * that we do not shutdown it. Note that the descriptors cannot be
1342 * closed before building the environment, as we call
1343 * get_remote_ipaddr there.
1345 if (packet_get_connection_in() == packet_get_connection_out())
1346 close(packet_get_connection_in());
1348 close(packet_get_connection_in());
1349 close(packet_get_connection_out());
1352 * Close all descriptors related to channels. They will still remain
1353 * open in the parent.
1355 /* XXX better use close-on-exec? -markus */
1356 channel_close_all();
1359 * Close any extra file descriptors. Note that there may still be
1360 * descriptors left by system functions. They will be closed later.
1365 * Close any extra open file descriptors so that we don\'t have them
1366 * hanging around in clients. Note that we want to do this after
1367 * initgroups, because at least on Solaris 2.3 it leaves file
1370 for (i = 3; i < 64; i++)
1373 /* Change current directory to the user\'s home directory. */
1374 if (chdir(pw->pw_dir) < 0) {
1375 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1376 pw->pw_dir, strerror(errno));
1377 #ifdef HAVE_LOGIN_CAP
1378 if (login_getcapbool(lc, "requirehome", 0))
1384 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1385 * xauth are run in the proper environment.
1390 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1393 if (!options.use_login) {
1394 /* ignore _PATH_SSH_USER_RC for subsystems */
1395 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1396 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1397 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1399 fprintf(stderr, "Running %s\n", cmd);
1400 f = popen(cmd, "w");
1403 fprintf(f, "%s %s\n", s->auth_proto,
1407 fprintf(stderr, "Could not run %s\n",
1409 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1411 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1412 _PATH_SSH_SYSTEM_RC);
1414 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1417 fprintf(f, "%s %s\n", s->auth_proto,
1421 fprintf(stderr, "Could not run %s\n",
1422 _PATH_SSH_SYSTEM_RC);
1423 } else if (do_xauth && options.xauth_location != NULL) {
1424 /* Add authority data to .Xauthority if appropriate. */
1425 char *screen = strchr(s->display, ':');
1429 "Running %.100s add "
1430 "%.100s %.100s %.100s\n",
1431 options.xauth_location, s->display,
1432 s->auth_proto, s->auth_data);
1435 "Adding %.*s/unix%s %s %s\n",
1436 (int)(screen - s->display),
1438 s->auth_proto, s->auth_data);
1440 snprintf(cmd, sizeof cmd, "%s -q -",
1441 options.xauth_location);
1442 f = popen(cmd, "w");
1444 fprintf(f, "add %s %s %s\n", s->display,
1445 s->auth_proto, s->auth_data);
1447 fprintf(f, "add %.*s/unix%s %s %s\n",
1448 (int)(screen - s->display),
1454 fprintf(stderr, "Could not run %s\n",
1458 /* Get the last component of the shell name. */
1459 cp = strrchr(shell, '/');
1466 /* restore SIGPIPE for child */
1467 signal(SIGPIPE, SIG_DFL);
1470 * If we have no command, execute the shell. In this case, the shell
1471 * name to be passed in argv[0] is preceded by '-' to indicate that
1472 * this is a login shell.
1475 if (!options.use_login) {
1479 * Check for mail if we have a tty and it was enabled
1480 * in server options.
1482 if (s->ttyfd != -1 && options.check_mail) {
1484 struct stat mailstat;
1486 mailbox = getenv("MAIL");
1487 if (mailbox != NULL) {
1488 if (stat(mailbox, &mailstat) != 0 ||
1489 mailstat.st_size == 0)
1490 printf("No mail.\n");
1491 else if (mailstat.st_mtime < mailstat.st_atime)
1492 printf("You have mail.\n");
1494 printf("You have new mail.\n");
1497 /* Start the shell. Set initial character to '-'. */
1499 strncpy(buf + 1, cp, sizeof(buf) - 1);
1500 buf[sizeof(buf) - 1] = 0;
1502 /* Execute the shell. */
1505 execve(shell, argv, env);
1507 /* Executing the shell failed. */
1512 /* Launch login(1). */
1514 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1515 "-p", "-f", "--", pw->pw_name, NULL);
1517 /* Login couldn't be executed, die. */
1524 * Execute the command using the user's shell. This uses the -c
1525 * option to execute the command.
1527 argv[0] = (char *) cp;
1529 argv[2] = (char *) command;
1531 execve(shell, argv, env);
1540 static int did_init = 0;
1542 debug("session_new: init");
1543 for(i = 0; i < MAX_SESSIONS; i++) {
1544 sessions[i].used = 0;
1545 sessions[i].self = i;
1549 for(i = 0; i < MAX_SESSIONS; i++) {
1550 Session *s = &sessions[i];
1552 memset(s, 0, sizeof(*s));
1557 debug("session_new: session %d", i);
1568 for(i = 0; i < MAX_SESSIONS; i++) {
1569 Session *s = &sessions[i];
1570 debug("dump: used %d session %d %p channel %d pid %d",
1580 session_open(int chanid)
1582 Session *s = session_new();
1583 debug("session_open: channel %d", chanid);
1585 error("no more sessions");
1588 s->pw = auth_get_user();
1590 fatal("no user for session %d", s->self);
1591 debug("session_open: session %d: link with channel %d", s->self, chanid);
1597 session_by_channel(int id)
1600 for(i = 0; i < MAX_SESSIONS; i++) {
1601 Session *s = &sessions[i];
1602 if (s->used && s->chanid == id) {
1603 debug("session_by_channel: session %d channel %d", i, id);
1607 debug("session_by_channel: unknown channel %d", id);
1613 session_by_pid(pid_t pid)
1616 debug("session_by_pid: pid %d", pid);
1617 for(i = 0; i < MAX_SESSIONS; i++) {
1618 Session *s = &sessions[i];
1619 if (s->used && s->pid == pid)
1622 error("session_by_pid: unknown pid %d", pid);
1628 session_window_change_req(Session *s)
1630 s->col = packet_get_int();
1631 s->row = packet_get_int();
1632 s->xpixel = packet_get_int();
1633 s->ypixel = packet_get_int();
1635 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1640 session_pty_req(Session *s)
1649 s->term = packet_get_string(&len);
1650 s->col = packet_get_int();
1651 s->row = packet_get_int();
1652 s->xpixel = packet_get_int();
1653 s->ypixel = packet_get_int();
1655 if (strcmp(s->term, "") == 0) {
1659 /* Allocate a pty and open it. */
1660 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1665 error("session_pty_req: session %d alloc failed", s->self);
1668 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1670 * Add a cleanup function to clear the utmp entry and record logout
1671 * time in case we call fatal() (e.g., the connection gets closed).
1673 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1674 pty_setowner(s->pw, s->tty);
1675 /* Get window size from the packet. */
1676 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1678 /* Get tty modes from the packet. */
1679 tty_parse_modes(s->ttyfd, &n_bytes);
1682 session_proctitle(s);
1688 session_subsystem_req(Session *s)
1692 char *subsys = packet_get_string(&len);
1696 log("subsystem request for %s", subsys);
1698 for (i = 0; i < options.num_subsystems; i++) {
1699 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1700 debug("subsystem: exec() %s", options.subsystem_command[i]);
1701 s->is_subsystem = 1;
1702 do_exec_no_pty(s, options.subsystem_command[i]);
1708 log("subsystem request for %s failed, subsystem not found", subsys);
1715 session_x11_req(Session *s)
1718 if (no_x11_forwarding_flag) {
1719 debug("X11 forwarding disabled in user configuration file.");
1722 if (!options.x11_forwarding) {
1723 debug("X11 forwarding disabled in server configuration file.");
1726 if (xauthfile != NULL) {
1727 debug("X11 fwd already started.");
1731 debug("Received request for X11 forwarding with auth spoofing.");
1732 if (s->display != NULL)
1733 packet_disconnect("Protocol error: X11 display already set.");
1735 s->single_connection = packet_get_char();
1736 s->auth_proto = packet_get_string(NULL);
1737 s->auth_data = packet_get_string(NULL);
1738 s->screen = packet_get_int();
1741 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1742 if (s->display == NULL) {
1743 xfree(s->auth_proto);
1744 xfree(s->auth_data);
1747 xauthfile = xmalloc(MAXPATHLEN);
1748 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1749 temporarily_use_uid(s->pw);
1750 if (mkdtemp(xauthfile) == NULL) {
1752 error("private X11 dir: mkdtemp %s failed: %s",
1753 xauthfile, strerror(errno));
1756 xfree(s->auth_proto);
1757 xfree(s->auth_data);
1758 /* XXXX remove listening channels */
1761 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1762 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1766 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1771 session_shell_req(Session *s)
1773 /* if forced_command == NULL, the shell is execed */
1774 char *shell = forced_command;
1777 do_exec_no_pty(s, shell);
1779 do_exec_pty(s, shell);
1784 session_exec_req(Session *s)
1787 char *command = packet_get_string(&len);
1789 if (forced_command) {
1790 original_command = command;
1791 command = forced_command;
1792 debug("Forced command '%.500s'", forced_command);
1795 do_exec_no_pty(s, command);
1797 do_exec_pty(s, command);
1798 if (forced_command == NULL)
1804 session_auth_agent_req(Session *s)
1806 static int called = 0;
1808 if (no_agent_forwarding_flag) {
1809 debug("session_auth_agent_req: no_agent_forwarding_flag");
1816 return auth_input_request_forwarding(s->pw);
1821 session_input_channel_req(int id, void *arg)
1830 rtype = packet_get_string(&len);
1831 reply = packet_get_char();
1833 s = session_by_channel(id);
1835 fatal("session_input_channel_req: channel %d: no session", id);
1836 c = channel_lookup(id);
1838 fatal("session_input_channel_req: channel %d: bad channel", id);
1840 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1841 s->self, id, rtype, reply);
1844 * a session is in LARVAL state until a shell, a command
1845 * or a subsystem is executed
1847 if (c->type == SSH_CHANNEL_LARVAL) {
1848 if (strcmp(rtype, "shell") == 0) {
1849 success = session_shell_req(s);
1850 } else if (strcmp(rtype, "exec") == 0) {
1851 success = session_exec_req(s);
1852 } else if (strcmp(rtype, "pty-req") == 0) {
1853 success = session_pty_req(s);
1854 } else if (strcmp(rtype, "x11-req") == 0) {
1855 success = session_x11_req(s);
1856 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1857 success = session_auth_agent_req(s);
1858 } else if (strcmp(rtype, "subsystem") == 0) {
1859 success = session_subsystem_req(s);
1862 if (strcmp(rtype, "window-change") == 0) {
1863 success = session_window_change_req(s);
1867 packet_start(success ?
1868 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1869 packet_put_int(c->remote_id);
1876 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1879 fatal("session_set_fds: called for proto != 2.0");
1881 * now that have a child and a pipe to the child,
1882 * we can activate our channel and register the fd's
1884 if (s->chanid == -1)
1885 fatal("no channel for session %d", s->self);
1886 channel_set_fds(s->chanid,
1888 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1893 session_pty_cleanup(Session *s)
1895 if (s == NULL || s->ttyfd == -1)
1898 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1900 /* Cancel the cleanup function. */
1901 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1903 /* Record that the user has logged out. */
1904 record_logout(s->pid, s->tty);
1906 /* Release the pseudo-tty. */
1907 pty_release(s->tty);
1910 * Close the server side of the socket pairs. We must do this after
1911 * the pty cleanup, so that another process doesn't get this pty
1912 * while we're still cleaning up.
1914 if (close(s->ptymaster) < 0)
1915 error("close(s->ptymaster): %s", strerror(errno));
1919 session_exit_message(Session *s, int status)
1923 fatal("session_close: no session");
1924 c = channel_lookup(s->chanid);
1926 fatal("session_close: session %d: no channel %d",
1927 s->self, s->chanid);
1928 debug("session_exit_message: session %d channel %d pid %d",
1929 s->self, s->chanid, s->pid);
1931 if (WIFEXITED(status)) {
1932 channel_request_start(s->chanid,
1934 packet_put_int(WEXITSTATUS(status));
1936 } else if (WIFSIGNALED(status)) {
1937 channel_request_start(s->chanid,
1939 packet_put_int(WTERMSIG(status));
1941 packet_put_char(WCOREDUMP(status));
1942 #else /* WCOREDUMP */
1944 #endif /* WCOREDUMP */
1945 packet_put_cstring("");
1946 packet_put_cstring("");
1949 /* Some weird exit cause. Just exit. */
1950 packet_disconnect("wait returned status %04x.", status);
1953 /* disconnect channel */
1954 debug("session_exit_message: release channel %d", s->chanid);
1955 channel_cancel_cleanup(s->chanid);
1957 * emulate a write failure with 'chan_write_failed', nobody will be
1958 * interested in data we write.
1959 * Note that we must not call 'chan_read_failed', since there could
1960 * be some more data waiting in the pipe.
1962 if (c->ostate != CHAN_OUTPUT_CLOSED)
1963 chan_write_failed(c);
1968 session_free(Session *s)
1970 debug("session_free: session %d pid %d", s->self, s->pid);
1976 xfree(s->auth_data);
1978 xfree(s->auth_proto);
1983 session_close(Session *s)
1985 session_pty_cleanup(s);
1987 session_proctitle(s);
1991 session_close_by_pid(pid_t pid, int status)
1993 Session *s = session_by_pid(pid);
1995 debug("session_close_by_pid: no session for pid %d", s->pid);
1998 if (s->chanid != -1)
1999 session_exit_message(s, status);
2004 * this is called when a channel dies before
2005 * the session 'child' itself dies
2008 session_close_by_channel(int id, void *arg)
2010 Session *s = session_by_channel(id);
2012 debug("session_close_by_channel: no session for channel %d", id);
2015 /* disconnect channel */
2016 channel_cancel_cleanup(s->chanid);
2019 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
2021 /* close session immediately */
2024 /* notify child, delay session cleanup */
2025 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
2026 error("session_close_by_channel: kill %d: %s",
2027 s->pid, strerror(errno));
2032 session_tty_list(void)
2034 static char buf[1024];
2037 for(i = 0; i < MAX_SESSIONS; i++) {
2038 Session *s = &sessions[i];
2039 if (s->used && s->ttyfd != -1) {
2041 strlcat(buf, ",", sizeof buf);
2042 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2046 strlcpy(buf, "notty", sizeof buf);
2051 session_proctitle(Session *s)
2054 error("no user for session %d", s->self);
2056 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2060 do_authenticated2(Authctxt *authctxt)
2065 xauthfile_cleanup_proc(NULL);