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.67 2001/03/23 14:28:32 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 void do_authenticated1(Authctxt *authctxt);
133 void do_authenticated2(Authctxt *authctxt);
136 extern ServerOptions options;
137 extern char *__progname;
138 extern int log_stderr;
139 extern int debug_flag;
140 extern u_int utmp_len;
142 extern int startup_pipe;
144 /* Local Xauthority file. */
145 static char *xauthfile;
147 /* original command from peer. */
148 char *original_command = NULL;
151 #define MAX_SESSIONS 10
152 Session sessions[MAX_SESSIONS];
154 #ifdef WITH_AIXAUTHENTICATE
155 /* AIX's lastlogin message, set in auth1.c */
157 #endif /* WITH_AIXAUTHENTICATE */
159 #ifdef HAVE_LOGIN_CAP
160 static login_cap_t *lc;
164 do_authenticated(Authctxt *authctxt)
167 * Cancel the alarm we set to limit the time taken for
171 if (startup_pipe != -1) {
175 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
176 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
177 error("unable to get login class");
181 /* setup the channel layer */
182 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
183 channel_permit_all_opens();
186 do_authenticated2(authctxt);
188 do_authenticated1(authctxt);
192 * Remove local Xauthority file.
195 xauthfile_cleanup_proc(void *ignore)
197 debug("xauthfile_cleanup_proc called");
199 if (xauthfile != NULL) {
202 p = strrchr(xauthfile, '/');
213 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
214 * dropped connection).
217 pty_cleanup_proc(void *session)
221 fatal("pty_cleanup_proc: no session");
222 debug("pty_cleanup_proc: %s", s->tty);
225 /* Record that the user has logged out. */
226 record_logout(s->pid, s->tty);
229 /* Release the pseudo-tty. */
234 * Prepares for an interactive session. This is called after the user has
235 * been successfully authenticated. During this message exchange, pseudo
236 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
237 * are requested, etc.
240 do_authenticated1(Authctxt *authctxt)
244 int success, type, fd, n_bytes, plen, screen_flag, have_pty = 0;
245 int compression_level = 0, enable_compression_after_reply = 0;
246 u_int proto_len, data_len, dlen;
249 s->pw = authctxt->pw;
252 * We stay in this loop until the client requests to execute a shell
258 /* Get a packet from the client. */
259 type = packet_read(&plen);
261 /* Process the packet. */
263 case SSH_CMSG_REQUEST_COMPRESSION:
264 packet_integrity_check(plen, 4, type);
265 compression_level = packet_get_int();
266 if (compression_level < 1 || compression_level > 9) {
267 packet_send_debug("Received illegal compression level %d.",
271 /* Enable compression after we have responded with SUCCESS. */
272 enable_compression_after_reply = 1;
276 case SSH_CMSG_REQUEST_PTY:
278 debug("Allocating a pty not permitted for this authentication.");
282 packet_disconnect("Protocol error: you already have a pty.");
284 debug("Allocating pty.");
286 /* Allocate a pty and open it. */
287 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
289 error("Failed to allocate pty.");
292 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
293 pty_setowner(s->pw, s->tty);
295 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
296 s->term = packet_get_string(&dlen);
297 packet_integrity_check(dlen, strlen(s->term), type);
298 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
299 /* Remaining bytes */
300 n_bytes = plen - (4 + dlen + 4 * 4);
302 if (strcmp(s->term, "") == 0) {
306 /* Get window size from the packet. */
307 s->row = packet_get_int();
308 s->col = packet_get_int();
309 s->xpixel = packet_get_int();
310 s->ypixel = packet_get_int();
311 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
313 /* Get tty modes from the packet. */
314 tty_parse_modes(s->ttyfd, &n_bytes);
315 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
317 session_proctitle(s);
319 /* Indicate that we now have a pty. */
324 case SSH_CMSG_X11_REQUEST_FORWARDING:
325 if (!options.x11_forwarding) {
326 packet_send_debug("X11 forwarding disabled in server configuration file.");
329 if (!options.xauth_location) {
330 packet_send_debug("No xauth program; cannot forward with spoofing.");
333 if (no_x11_forwarding_flag) {
334 packet_send_debug("X11 forwarding not permitted for this authentication.");
337 debug("Received request for X11 forwarding with auth spoofing.");
338 if (s->display != NULL)
339 packet_disconnect("Protocol error: X11 display already set.");
341 s->auth_proto = packet_get_string(&proto_len);
342 s->auth_data = packet_get_string(&data_len);
344 screen_flag = packet_get_protocol_flags() &
345 SSH_PROTOFLAG_SCREEN_NUMBER;
346 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
348 if (packet_remaining() == 4) {
350 debug2("Buggy client: "
351 "X11 screen flag missing");
352 packet_integrity_check(plen,
353 4 + proto_len + 4 + data_len + 4, type);
354 s->screen = packet_get_int();
356 packet_integrity_check(plen,
357 4 + proto_len + 4 + data_len, type);
360 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
362 if (s->display == NULL)
365 /* Setup to always have a local .Xauthority. */
366 xauthfile = xmalloc(MAXPATHLEN);
367 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
368 temporarily_use_uid(s->pw->pw_uid);
369 if (mkdtemp(xauthfile) == NULL) {
371 error("private X11 dir: mkdtemp %s failed: %s",
372 xauthfile, strerror(errno));
375 /* XXXX remove listening channels */
378 strlcat(xauthfile, "/cookies", MAXPATHLEN);
379 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
383 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
387 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
388 if (no_agent_forwarding_flag || compat13) {
389 debug("Authentication agent forwarding not permitted for this authentication.");
392 debug("Received authentication agent forwarding request.");
393 success = auth_input_request_forwarding(s->pw);
396 case SSH_CMSG_PORT_FORWARD_REQUEST:
397 if (no_port_forwarding_flag) {
398 debug("Port forwarding not permitted for this authentication.");
401 if (!options.allow_tcp_forwarding) {
402 debug("Port forwarding not permitted.");
405 debug("Received TCP/IP port forwarding request.");
406 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
410 case SSH_CMSG_MAX_PACKET_SIZE:
411 if (packet_set_maxsize(packet_get_int()) > 0)
415 case SSH_CMSG_EXEC_SHELL:
416 case SSH_CMSG_EXEC_CMD:
417 if (type == SSH_CMSG_EXEC_CMD) {
418 command = packet_get_string(&dlen);
419 debug("Exec command '%.500s'", command);
420 packet_integrity_check(plen, 4 + dlen, type);
423 packet_integrity_check(plen, 0, type);
425 if (forced_command != NULL) {
426 original_command = command;
427 command = forced_command;
428 debug("Forced command '%.500s'", forced_command);
431 do_exec_pty(s, command);
433 do_exec_no_pty(s, command);
437 /* Cleanup user's local Xauthority file. */
439 xauthfile_cleanup_proc(NULL);
444 * Any unknown messages in this phase are ignored,
445 * and a failure message is returned.
447 log("Unknown packet type received after authentication: %d", type);
449 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
453 /* Enable compression now that we have replied if appropriate. */
454 if (enable_compression_after_reply) {
455 enable_compression_after_reply = 0;
456 packet_start_compression(compression_level);
462 * This is called to fork and execute a command when we have no tty. This
463 * will call do_child from the child, and server_loop from the parent after
464 * setting up file descriptors and such.
467 do_exec_no_pty(Session *s, const char *command)
472 int pin[2], pout[2], perr[2];
473 /* Allocate pipes for communicating with the program. */
474 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
475 packet_disconnect("Could not create pipes: %.100s",
477 #else /* USE_PIPES */
478 int inout[2], err[2];
479 /* Uses socket pairs to communicate with the program. */
480 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
481 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
482 packet_disconnect("Could not create socket pairs: %.100s",
484 #endif /* USE_PIPES */
486 fatal("do_exec_no_pty: no session");
488 session_proctitle(s);
494 /* Fork the child. */
495 if ((pid = fork()) == 0) {
496 /* Child. Reinitialize the log since the pid has changed. */
497 log_init(__progname, options.log_level, options.log_facility, log_stderr);
499 signal(SIGPIPE, SIG_DFL);
502 * Create a new session and process group since the 4.4BSD
503 * setlogin() affects the entire process group.
506 error("setsid failed: %.100s", strerror(errno));
510 * Redirect stdin. We close the parent side of the socket
511 * pair, and make the child side the standard input.
514 if (dup2(pin[0], 0) < 0)
515 perror("dup2 stdin");
518 /* Redirect stdout. */
520 if (dup2(pout[1], 1) < 0)
521 perror("dup2 stdout");
524 /* Redirect stderr. */
526 if (dup2(perr[1], 2) < 0)
527 perror("dup2 stderr");
529 #else /* USE_PIPES */
531 * Redirect stdin, stdout, and stderr. Stdin and stdout will
532 * use the same socket, as some programs (particularly rdist)
533 * seem to depend on it.
537 if (dup2(inout[0], 0) < 0) /* stdin */
538 perror("dup2 stdin");
539 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
540 perror("dup2 stdout");
541 if (dup2(err[0], 2) < 0) /* stderr */
542 perror("dup2 stderr");
543 #endif /* USE_PIPES */
545 /* Do processing for the child (exec command etc). */
546 do_child(s, command);
551 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
554 packet_disconnect("fork failed: %.100s", strerror(errno));
556 /* Set interactive/non-interactive mode. */
557 packet_set_interactive(s->display != NULL);
559 /* We are the parent. Close the child sides of the pipes. */
565 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
567 /* Enter the interactive session. */
568 server_loop(pid, pin[1], pout[0], perr[0]);
569 /* server_loop has closed pin[1], pout[0], and perr[0]. */
571 #else /* USE_PIPES */
572 /* We are the parent. Close the child sides of the socket pairs. */
577 * Enter the interactive session. Note: server_loop must be able to
578 * handle the case that fdin and fdout are the same.
581 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
583 server_loop(pid, inout[1], inout[1], err[1]);
584 /* server_loop has closed inout[1] and err[1]. */
586 #endif /* USE_PIPES */
590 * This is called to fork and execute a command when we have a tty. This
591 * will call do_child from the child, and server_loop from the parent after
592 * setting up file descriptors, controlling tty, updating wtmp, utmp,
593 * lastlog, and other such operations.
596 do_exec_pty(Session *s, const char *command)
598 int fdout, ptyfd, ttyfd, ptymaster;
602 fatal("do_exec_pty: no session");
607 do_pam_session(s->pw->pw_name, s->tty);
611 /* Fork the child. */
612 if ((pid = fork()) == 0) {
613 /* Child. Reinitialize the log because the pid has changed. */
614 log_init(__progname, options.log_level, options.log_facility, log_stderr);
616 signal(SIGPIPE, SIG_DFL);
618 /* Close the master side of the pseudo tty. */
621 /* Make the pseudo tty our controlling tty. */
622 pty_make_controlling_tty(&ttyfd, s->tty);
624 /* Redirect stdin from the pseudo tty. */
625 if (dup2(ttyfd, fileno(stdin)) < 0)
626 error("dup2 stdin failed: %.100s", strerror(errno));
628 /* Redirect stdout to the pseudo tty. */
629 if (dup2(ttyfd, fileno(stdout)) < 0)
630 error("dup2 stdin failed: %.100s", strerror(errno));
632 /* Redirect stderr to the pseudo tty. */
633 if (dup2(ttyfd, fileno(stderr)) < 0)
634 error("dup2 stdin failed: %.100s", strerror(errno));
636 /* Close the extra descriptor for the pseudo tty. */
639 /* record login, etc. similar to login(1) */
640 if (!(options.use_login && command == NULL))
641 do_login(s, command);
643 /* Do common processing for the child, such as execing the command. */
644 do_child(s, command);
649 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
652 packet_disconnect("fork failed: %.100s", strerror(errno));
655 /* Parent. Close the slave side of the pseudo tty. */
659 * Create another descriptor of the pty master side for use as the
660 * standard input. We could use the original descriptor, but this
661 * simplifies code in server_loop. The descriptor is bidirectional.
665 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
667 /* we keep a reference to the pty master */
668 ptymaster = dup(ptyfd);
670 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
671 s->ptymaster = ptymaster;
673 /* Enter interactive session. */
674 packet_set_interactive(1);
676 session_set_fds(s, ptyfd, fdout, -1);
678 server_loop(pid, ptyfd, fdout, -1);
679 /* server_loop _has_ closed ptyfd and fdout. */
680 session_pty_cleanup(s);
685 get_remote_name_or_ip(void)
687 static const char *remote = "";
689 remote = get_canonical_hostname(options.reverse_mapping_check);
690 if (utmp_len == 0 || strlen(remote) > utmp_len)
691 remote = get_remote_ipaddr();
695 /* administrative, login(1)-like work */
697 do_login(Session *s, const char *command)
702 char hostname[MAXHOSTNAMELEN];
704 struct sockaddr_storage from;
706 time_t last_login_time;
707 struct passwd * pw = s->pw;
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 /* Get the time and hostname when the user last logged in. */
726 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
727 hostname, sizeof(hostname));
729 /* Record that there was a login on that tty from the remote host. */
730 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
731 get_remote_name_or_ip(), (struct sockaddr *)&from);
735 * If password change is needed, do it now.
736 * This needs to occur before the ~/.hushlogin check.
738 if (is_pam_password_change_required()) {
739 print_pam_messages();
744 /* Done if .hushlogin exists or a command given. */
747 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
748 #ifdef HAVE_LOGIN_CAP
749 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
751 if (stat(buf, &st) >= 0)
756 if (!is_pam_password_change_required())
757 print_pam_messages();
759 #ifdef WITH_AIXAUTHENTICATE
760 if (aixloginmsg && *aixloginmsg)
761 printf("%s\n", aixloginmsg);
762 #endif /* WITH_AIXAUTHENTICATE */
764 if (last_login_time != 0) {
765 time_string = ctime(&last_login_time);
766 if (strchr(time_string, '\n'))
767 *strchr(time_string, '\n') = 0;
768 if (strcmp(hostname, "") == 0)
769 printf("Last login: %s\r\n", time_string);
771 printf("Last login: %s from %s\r\n", time_string, hostname);
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))
789 * Sets the value of the given variable in the environment. If the variable
790 * already exists, its value is overriden.
793 child_set_env(char ***envp, u_int *envsizep, const char *name,
800 * Find the slot where the value should be stored. If the variable
801 * already exists, we reuse the slot; otherwise we append a new slot
802 * at the end of the array, expanding if necessary.
805 namelen = strlen(name);
806 for (i = 0; env[i]; i++)
807 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
810 /* Reuse the slot. */
813 /* New variable. Expand if necessary. */
814 if (i >= (*envsizep) - 1) {
816 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
818 /* Need to set the NULL pointer at end of array beyond the new slot. */
822 /* Allocate space and format the variable in the appropriate slot. */
823 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
824 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
828 * Reads environment variables from the given file and adds/overrides them
829 * into the environment. If the file does not exist, this does nothing.
830 * Otherwise, it must consist of empty lines, comments (line starts with '#')
831 * and assignments of the form name=value. No other forms are allowed.
834 read_environment_file(char ***env, u_int *envsize,
835 const char *filename)
841 f = fopen(filename, "r");
845 while (fgets(buf, sizeof(buf), f)) {
846 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
848 if (!*cp || *cp == '#' || *cp == '\n')
850 if (strchr(cp, '\n'))
851 *strchr(cp, '\n') = '\0';
852 value = strchr(cp, '=');
854 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
858 * Replace the equals sign by nul, and advance value to
863 child_set_env(env, envsize, cp, value);
870 * Sets any environment variables which have been specified by PAM
872 void do_pam_environment(char ***env, int *envsize)
874 char *equals, var_name[512], var_val[512];
878 if ((pam_env = fetch_pam_environment()) == NULL)
881 for(i = 0; pam_env[i] != NULL; i++) {
882 if ((equals = strstr(pam_env[i], "=")) == NULL)
885 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
886 memset(var_name, '\0', sizeof(var_name));
887 memset(var_val, '\0', sizeof(var_val));
889 strncpy(var_name, pam_env[i], equals - pam_env[i]);
890 strcpy(var_val, equals + 1);
892 debug3("PAM environment: %s=%s", var_name, var_val);
894 child_set_env(env, envsize, var_name, var_val);
901 void copy_environment(char ***env, int *envsize)
903 char *equals, var_name[512], var_val[512];
906 for(i = 0; environ[i] != NULL; i++) {
907 if ((equals = strstr(environ[i], "=")) == NULL)
910 if (strlen(environ[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, environ[i], equals - environ[i]);
915 strcpy(var_val, equals + 1);
917 debug3("Copy environment: %s=%s", var_name, var_val);
919 child_set_env(env, envsize, var_name, var_val);
925 #if defined(HAVE_GETUSERATTR)
927 * AIX-specific login initialisation
929 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
934 getrlimit(resource, &rlim);
937 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
939 rlim.rlim_cur = RLIM_INFINITY;
940 } else if (slim != 0) {
941 /* See the wackiness below */
942 if (rlim.rlim_cur == slim * mult)
945 rlim.rlim_cur = slim * mult;
950 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
952 rlim.rlim_max = RLIM_INFINITY;
953 } else if (hlim != 0) {
954 rlim.rlim_max = hlim * mult;
959 * XXX For cpu and fsize the soft limit is set to the hard limit
960 * if the hard limit is left at its default value and the soft limit
961 * is changed from its default value, either by requesting it
962 * (slim == 0) or by setting it to the current default. At least
963 * that's how rlogind does it. If you're confused you're not alone.
964 * Bug or feature? AIX 4.3.1.2
966 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
967 && hlim == 0 && slim != 0)
968 rlim.rlim_max = rlim.rlim_cur;
969 /* A specified hard limit limits the soft limit */
970 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
971 rlim.rlim_cur = rlim.rlim_max;
972 /* A soft limit can increase a hard limit */
973 else if (rlim.rlim_cur > rlim.rlim_max)
974 rlim.rlim_max = rlim.rlim_cur;
976 if (setrlimit(resource, &rlim) != 0)
977 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
980 void set_limits_from_userattr(char *user)
985 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
986 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
987 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
988 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
989 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
990 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
991 #if defined(S_UNOFILE)
992 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
995 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
996 /* Convert decimal to octal */
997 (void) snprintf(buf, sizeof(buf), "%d", mask);
998 if (sscanf(buf, "%o", &mask) == 1)
1002 #endif /* defined(HAVE_GETUSERATTR) */
1005 * Performs common processing for the child, such as setting up the
1006 * environment, closing extra file descriptors, setting the user and group
1007 * ids, and executing the command or shell.
1010 do_child(Session *s, const char *command)
1012 const char *shell, *hostname = NULL, *cp = NULL;
1013 struct passwd * pw = s->pw;
1019 extern char **environ;
1022 int do_xauth = s->auth_proto != NULL && s->auth_data != NULL;
1023 #ifdef WITH_IRIX_PROJECT
1025 #endif /* WITH_IRIX_PROJECT */
1026 #ifdef WITH_IRIX_JOBS
1029 #ifdef WITH_IRIX_ARRAY
1031 #endif /* WITH_IRIX_ARRAY */
1032 #endif /* WITH_IRIX_JOBS */
1034 /* login(1) is only called if we execute the login shell */
1035 if (options.use_login && command != NULL)
1036 options.use_login = 0;
1038 #ifndef USE_PAM /* pam_nologin handles this */
1039 if (!options.use_login) {
1040 # ifdef HAVE_LOGIN_CAP
1041 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1042 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1043 _PATH_NOLOGIN), "r");
1044 # else /* HAVE_LOGIN_CAP */
1046 f = fopen(_PATH_NOLOGIN, "r");
1047 # endif /* HAVE_LOGIN_CAP */
1049 /* /etc/nologin exists. Print its contents and exit. */
1050 while (fgets(buf, sizeof(buf), f))
1056 #endif /* USE_PAM */
1058 /* Set login name, uid, gid, and groups. */
1059 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1060 switch, so we let login(1) to this for us. */
1061 if (!options.use_login) {
1063 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1064 #else /* HAVE_OSF_SIA */
1068 if (getuid() == 0 || geteuid() == 0) {
1070 # ifdef HAVE_GETUSERATTR
1071 set_limits_from_userattr(pw->pw_name);
1072 # endif /* HAVE_GETUSERATTR */
1073 # ifdef HAVE_LOGIN_CAP
1074 if (setusercontext(lc, pw, pw->pw_uid,
1075 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1076 perror("unable to set user context");
1080 if (auth_approval(NULL, lc, pw->pw_name, "ssh") <= 0) {
1081 error("approval failure for %s", pw->pw_name);
1082 fprintf(stderr, "Approval failure");
1086 # else /* HAVE_LOGIN_CAP */
1087 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1088 /* Sets login uid for accounting */
1089 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1090 error("setluid: %s", strerror(errno));
1091 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1093 if (setlogin(pw->pw_name) < 0)
1094 error("setlogin failed: %s", strerror(errno));
1095 if (setgid(pw->pw_gid) < 0) {
1099 /* Initialize the group list. */
1100 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1101 perror("initgroups");
1105 # ifdef WITH_IRIX_JOBS
1106 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1108 fatal("Failed to create job container: %.100s",
1111 # endif /* WITH_IRIX_JOBS */
1112 # ifdef WITH_IRIX_ARRAY
1113 /* initialize array session */
1115 if (newarraysess() != 0)
1116 fatal("Failed to set up new array session: %.100s",
1119 # endif /* WITH_IRIX_ARRAY */
1120 # ifdef WITH_IRIX_PROJECT
1121 /* initialize irix project info */
1122 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1123 debug("Failed to get project id, using projid 0");
1126 if (setprid(projid))
1127 fatal("Failed to initialize project %d for %s: %.100s",
1128 (int)projid, pw->pw_name, strerror(errno));
1129 # endif /* WITH_IRIX_PROJECT */
1130 #ifdef WITH_IRIX_AUDIT
1131 if (sysconf(_SC_AUDIT)) {
1132 debug("Setting sat id to %d", (int) pw->pw_uid);
1133 if (satsetid(pw->pw_uid))
1134 debug("error setting satid: %.100s", strerror(errno));
1136 #endif /* WITH_IRIX_AUDIT */
1140 * AIX has a "usrinfo" area where logname and
1141 * other stuff is stored - a few applications
1142 * actually use this and die if it's not set
1146 cp = xmalloc(22 + strlen(s->tty) +
1147 2 * strlen(pw->pw_name));
1148 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1149 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1150 if (usrinfo(SETUINFO, cp, i) == -1)
1151 fatal("Couldn't set usrinfo: %s",
1153 debug3("AIX/UsrInfo: set len %d", i);
1157 /* Permanently switch to the desired uid. */
1158 permanently_set_uid(pw->pw_uid);
1159 # endif /* HAVE_LOGIN_CAP */
1161 #endif /* HAVE_OSF_SIA */
1166 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1167 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1170 * Get the shell from the password data. An empty shell field is
1171 * legal, and means /bin/sh.
1173 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1174 #ifdef HAVE_LOGIN_CAP
1175 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1179 /* Try to get AFS tokens for the local cell. */
1183 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1184 krb_afslog(cell, 0);
1190 /* Initialize the environment. */
1192 env = xmalloc(envsize * sizeof(char *));
1197 * The Windows environment contains some setting which are
1198 * important for a running system. They must not be dropped.
1200 copy_environment(&env, &envsize);
1203 if (!options.use_login) {
1204 /* Set basic environment. */
1205 child_set_env(&env, &envsize, "USER", pw->pw_name);
1206 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1207 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1208 #ifdef HAVE_LOGIN_CAP
1209 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1210 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1211 #else /* HAVE_LOGIN_CAP */
1212 # ifndef HAVE_CYGWIN
1214 * There's no standard path on Windows. The path contains
1215 * important components pointing to the system directories,
1216 * needed for loading shared libraries. So the path better
1217 * remains intact here.
1219 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1220 # endif /* HAVE_CYGWIN */
1221 #endif /* HAVE_LOGIN_CAP */
1223 snprintf(buf, sizeof buf, "%.200s/%.50s",
1224 _PATH_MAILDIR, pw->pw_name);
1225 child_set_env(&env, &envsize, "MAIL", buf);
1227 /* Normal systems set SHELL by default. */
1228 child_set_env(&env, &envsize, "SHELL", shell);
1231 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1233 /* Set custom environment options from RSA authentication. */
1234 while (custom_environment) {
1235 struct envstring *ce = custom_environment;
1238 for (i = 0; s[i] != '=' && s[i]; i++);
1241 child_set_env(&env, &envsize, s, s + i + 1);
1243 custom_environment = ce->next;
1248 snprintf(buf, sizeof buf, "%.50s %d %d",
1249 get_remote_ipaddr(), get_remote_port(), get_local_port());
1250 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1253 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1255 child_set_env(&env, &envsize, "TERM", s->term);
1257 child_set_env(&env, &envsize, "DISPLAY", s->display);
1258 if (original_command)
1259 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1263 if ((cp = getenv("AUTHSTATE")) != NULL)
1264 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1265 if ((cp = getenv("KRB5CCNAME")) != NULL)
1266 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1267 read_environment_file(&env, &envsize, "/etc/environment");
1272 extern char *ticket;
1275 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1280 /* Pull in any environment variables that may have been set by PAM. */
1281 do_pam_environment(&env, &envsize);
1282 #endif /* USE_PAM */
1285 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1286 if (auth_get_socket_name() != NULL)
1287 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1288 auth_get_socket_name());
1290 /* read $HOME/.ssh/environment. */
1291 if (!options.use_login) {
1292 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1294 read_environment_file(&env, &envsize, buf);
1297 /* dump the environment */
1298 fprintf(stderr, "Environment:\n");
1299 for (i = 0; env[i]; i++)
1300 fprintf(stderr, " %.200s\n", env[i]);
1302 /* we have to stash the hostname before we close our socket. */
1303 if (options.use_login)
1304 hostname = get_remote_name_or_ip();
1306 * Close the connection descriptors; note that this is the child, and
1307 * the server will still have the socket open, and it is important
1308 * that we do not shutdown it. Note that the descriptors cannot be
1309 * closed before building the environment, as we call
1310 * get_remote_ipaddr there.
1312 if (packet_get_connection_in() == packet_get_connection_out())
1313 close(packet_get_connection_in());
1315 close(packet_get_connection_in());
1316 close(packet_get_connection_out());
1319 * Close all descriptors related to channels. They will still remain
1320 * open in the parent.
1322 /* XXX better use close-on-exec? -markus */
1323 channel_close_all();
1326 * Close any extra file descriptors. Note that there may still be
1327 * descriptors left by system functions. They will be closed later.
1332 * Close any extra open file descriptors so that we don\'t have them
1333 * hanging around in clients. Note that we want to do this after
1334 * initgroups, because at least on Solaris 2.3 it leaves file
1337 for (i = 3; i < 64; i++)
1340 /* Change current directory to the user\'s home directory. */
1341 if (chdir(pw->pw_dir) < 0) {
1342 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1343 pw->pw_dir, strerror(errno));
1344 #ifdef HAVE_LOGIN_CAP
1345 if (login_getcapbool(lc, "requirehome", 0))
1351 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1352 * xauth are run in the proper environment.
1357 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1360 if (!options.use_login) {
1361 if (stat(_PATH_SSH_USER_RC, &st) >= 0) {
1363 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1365 f = popen(_PATH_BSHELL " " _PATH_SSH_USER_RC, "w");
1368 fprintf(f, "%s %s\n", s->auth_proto,
1372 fprintf(stderr, "Could not run %s\n",
1374 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1376 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1377 _PATH_SSH_SYSTEM_RC);
1379 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1382 fprintf(f, "%s %s\n", s->auth_proto,
1386 fprintf(stderr, "Could not run %s\n",
1387 _PATH_SSH_SYSTEM_RC);
1388 } else if (do_xauth && options.xauth_location != NULL) {
1389 /* Add authority data to .Xauthority if appropriate. */
1390 char *screen = strchr(s->display, ':');
1394 "Running %.100s add "
1395 "%.100s %.100s %.100s\n",
1396 options.xauth_location, s->display,
1397 s->auth_proto, s->auth_data);
1400 "Adding %.*s/unix%s %s %s\n",
1401 (int)(screen - s->display),
1403 s->auth_proto, s->auth_data);
1405 snprintf(cmd, sizeof cmd, "%s -q -",
1406 options.xauth_location);
1407 f = popen(cmd, "w");
1409 fprintf(f, "add %s %s %s\n", s->display,
1410 s->auth_proto, s->auth_data);
1412 fprintf(f, "add %.*s/unix%s %s %s\n",
1413 (int)(screen - s->display),
1419 fprintf(stderr, "Could not run %s\n",
1423 /* Get the last component of the shell name. */
1424 cp = strrchr(shell, '/');
1431 /* restore SIGPIPE for child */
1432 signal(SIGPIPE, SIG_DFL);
1435 * If we have no command, execute the shell. In this case, the shell
1436 * name to be passed in argv[0] is preceded by '-' to indicate that
1437 * this is a login shell.
1440 if (!options.use_login) {
1444 * Check for mail if we have a tty and it was enabled
1445 * in server options.
1447 if (s->ttyfd != -1 && options.check_mail) {
1449 struct stat mailstat;
1451 mailbox = getenv("MAIL");
1452 if (mailbox != NULL) {
1453 if (stat(mailbox, &mailstat) != 0 ||
1454 mailstat.st_size == 0)
1455 printf("No mail.\n");
1456 else if (mailstat.st_mtime < mailstat.st_atime)
1457 printf("You have mail.\n");
1459 printf("You have new mail.\n");
1462 /* Start the shell. Set initial character to '-'. */
1464 strncpy(buf + 1, cp, sizeof(buf) - 1);
1465 buf[sizeof(buf) - 1] = 0;
1467 /* Execute the shell. */
1470 execve(shell, argv, env);
1472 /* Executing the shell failed. */
1477 /* Launch login(1). */
1479 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1480 "-p", "-f", "--", pw->pw_name, NULL);
1482 /* Login couldn't be executed, die. */
1489 * Execute the command using the user's shell. This uses the -c
1490 * option to execute the command.
1492 argv[0] = (char *) cp;
1494 argv[2] = (char *) command;
1496 execve(shell, argv, env);
1505 static int did_init = 0;
1507 debug("session_new: init");
1508 for(i = 0; i < MAX_SESSIONS; i++) {
1509 sessions[i].used = 0;
1510 sessions[i].self = i;
1514 for(i = 0; i < MAX_SESSIONS; i++) {
1515 Session *s = &sessions[i];
1518 s->is_subsystem = 0;
1527 s->auth_data = NULL;
1528 s->auth_proto = NULL;
1531 debug("session_new: session %d", i);
1542 for(i = 0; i < MAX_SESSIONS; i++) {
1543 Session *s = &sessions[i];
1544 debug("dump: used %d session %d %p channel %d pid %d",
1554 session_open(int chanid)
1556 Session *s = session_new();
1557 debug("session_open: channel %d", chanid);
1559 error("no more sessions");
1562 s->pw = auth_get_user();
1564 fatal("no user for session %d", s->self);
1565 debug("session_open: session %d: link with channel %d", s->self, chanid);
1571 session_by_channel(int id)
1574 for(i = 0; i < MAX_SESSIONS; i++) {
1575 Session *s = &sessions[i];
1576 if (s->used && s->chanid == id) {
1577 debug("session_by_channel: session %d channel %d", i, id);
1581 debug("session_by_channel: unknown channel %d", id);
1587 session_by_pid(pid_t pid)
1590 debug("session_by_pid: pid %d", pid);
1591 for(i = 0; i < MAX_SESSIONS; i++) {
1592 Session *s = &sessions[i];
1593 if (s->used && s->pid == pid)
1596 error("session_by_pid: unknown pid %d", pid);
1602 session_window_change_req(Session *s)
1604 s->col = packet_get_int();
1605 s->row = packet_get_int();
1606 s->xpixel = packet_get_int();
1607 s->ypixel = packet_get_int();
1609 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1614 session_pty_req(Session *s)
1617 char *term_modes; /* encoded terminal modes */
1623 s->term = packet_get_string(&len);
1624 s->col = packet_get_int();
1625 s->row = packet_get_int();
1626 s->xpixel = packet_get_int();
1627 s->ypixel = packet_get_int();
1628 term_modes = packet_get_string(&len);
1631 if (strcmp(s->term, "") == 0) {
1635 /* Allocate a pty and open it. */
1636 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1641 error("session_pty_req: session %d alloc failed", s->self);
1645 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1647 * Add a cleanup function to clear the utmp entry and record logout
1648 * time in case we call fatal() (e.g., the connection gets closed).
1650 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1651 pty_setowner(s->pw, s->tty);
1652 /* Get window size from the packet. */
1653 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1655 session_proctitle(s);
1657 /* XXX parse and set terminal modes */
1663 session_subsystem_req(Session *s)
1667 char *subsys = packet_get_string(&len);
1671 log("subsystem request for %s", subsys);
1673 for (i = 0; i < options.num_subsystems; i++) {
1674 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1675 debug("subsystem: exec() %s", options.subsystem_command[i]);
1676 s->is_subsystem = 1;
1677 do_exec_no_pty(s, options.subsystem_command[i]);
1683 log("subsystem request for %s failed, subsystem not found", subsys);
1690 session_x11_req(Session *s)
1693 if (no_x11_forwarding_flag) {
1694 debug("X11 forwarding disabled in user configuration file.");
1697 if (!options.x11_forwarding) {
1698 debug("X11 forwarding disabled in server configuration file.");
1701 if (xauthfile != NULL) {
1702 debug("X11 fwd already started.");
1706 debug("Received request for X11 forwarding with auth spoofing.");
1707 if (s->display != NULL)
1708 packet_disconnect("Protocol error: X11 display already set.");
1710 s->single_connection = packet_get_char();
1711 s->auth_proto = packet_get_string(NULL);
1712 s->auth_data = packet_get_string(NULL);
1713 s->screen = packet_get_int();
1716 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1717 if (s->display == NULL) {
1718 xfree(s->auth_proto);
1719 xfree(s->auth_data);
1722 xauthfile = xmalloc(MAXPATHLEN);
1723 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1724 temporarily_use_uid(s->pw->pw_uid);
1725 if (mkdtemp(xauthfile) == NULL) {
1727 error("private X11 dir: mkdtemp %s failed: %s",
1728 xauthfile, strerror(errno));
1731 xfree(s->auth_proto);
1732 xfree(s->auth_data);
1733 /* XXXX remove listening channels */
1736 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1737 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1741 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1746 session_shell_req(Session *s)
1748 /* if forced_command == NULL, the shell is execed */
1749 char *shell = forced_command;
1752 do_exec_no_pty(s, shell);
1754 do_exec_pty(s, shell);
1759 session_exec_req(Session *s)
1762 char *command = packet_get_string(&len);
1764 if (forced_command) {
1765 original_command = command;
1766 command = forced_command;
1767 debug("Forced command '%.500s'", forced_command);
1770 do_exec_no_pty(s, command);
1772 do_exec_pty(s, command);
1773 if (forced_command == NULL)
1779 session_auth_agent_req(Session *s)
1781 static int called = 0;
1783 if (no_agent_forwarding_flag) {
1784 debug("session_auth_agent_req: no_agent_forwarding_flag");
1791 return auth_input_request_forwarding(s->pw);
1796 session_input_channel_req(int id, void *arg)
1805 rtype = packet_get_string(&len);
1806 reply = packet_get_char();
1808 s = session_by_channel(id);
1810 fatal("session_input_channel_req: channel %d: no session", id);
1811 c = channel_lookup(id);
1813 fatal("session_input_channel_req: channel %d: bad channel", id);
1815 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1816 s->self, id, rtype, reply);
1819 * a session is in LARVAL state until a shell, a command
1820 * or a subsystem is executed
1822 if (c->type == SSH_CHANNEL_LARVAL) {
1823 if (strcmp(rtype, "shell") == 0) {
1824 success = session_shell_req(s);
1825 } else if (strcmp(rtype, "exec") == 0) {
1826 success = session_exec_req(s);
1827 } else if (strcmp(rtype, "pty-req") == 0) {
1828 success = session_pty_req(s);
1829 } else if (strcmp(rtype, "x11-req") == 0) {
1830 success = session_x11_req(s);
1831 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1832 success = session_auth_agent_req(s);
1833 } else if (strcmp(rtype, "subsystem") == 0) {
1834 success = session_subsystem_req(s);
1837 if (strcmp(rtype, "window-change") == 0) {
1838 success = session_window_change_req(s);
1842 packet_start(success ?
1843 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1844 packet_put_int(c->remote_id);
1851 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1854 fatal("session_set_fds: called for proto != 2.0");
1856 * now that have a child and a pipe to the child,
1857 * we can activate our channel and register the fd's
1859 if (s->chanid == -1)
1860 fatal("no channel for session %d", s->self);
1861 channel_set_fds(s->chanid,
1863 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1868 session_pty_cleanup(Session *s)
1870 if (s == NULL || s->ttyfd == -1)
1873 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1875 /* Cancel the cleanup function. */
1876 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1878 /* Record that the user has logged out. */
1879 record_logout(s->pid, s->tty);
1881 /* Release the pseudo-tty. */
1882 pty_release(s->tty);
1885 * Close the server side of the socket pairs. We must do this after
1886 * the pty cleanup, so that another process doesn't get this pty
1887 * while we're still cleaning up.
1889 if (close(s->ptymaster) < 0)
1890 error("close(s->ptymaster): %s", strerror(errno));
1894 session_exit_message(Session *s, int status)
1898 fatal("session_close: no session");
1899 c = channel_lookup(s->chanid);
1901 fatal("session_close: session %d: no channel %d",
1902 s->self, s->chanid);
1903 debug("session_exit_message: session %d channel %d pid %d",
1904 s->self, s->chanid, s->pid);
1906 if (WIFEXITED(status)) {
1907 channel_request_start(s->chanid,
1909 packet_put_int(WEXITSTATUS(status));
1911 } else if (WIFSIGNALED(status)) {
1912 channel_request_start(s->chanid,
1914 packet_put_int(WTERMSIG(status));
1916 packet_put_char(WCOREDUMP(status));
1917 #else /* WCOREDUMP */
1919 #endif /* WCOREDUMP */
1920 packet_put_cstring("");
1921 packet_put_cstring("");
1924 /* Some weird exit cause. Just exit. */
1925 packet_disconnect("wait returned status %04x.", status);
1928 /* disconnect channel */
1929 debug("session_exit_message: release channel %d", s->chanid);
1930 channel_cancel_cleanup(s->chanid);
1932 * emulate a write failure with 'chan_write_failed', nobody will be
1933 * interested in data we write.
1934 * Note that we must not call 'chan_read_failed', since there could
1935 * be some more data waiting in the pipe.
1937 if (c->ostate != CHAN_OUTPUT_CLOSED)
1938 chan_write_failed(c);
1943 session_free(Session *s)
1945 debug("session_free: session %d pid %d", s->self, s->pid);
1951 xfree(s->auth_data);
1953 xfree(s->auth_proto);
1958 session_close(Session *s)
1960 session_pty_cleanup(s);
1962 session_proctitle(s);
1966 session_close_by_pid(pid_t pid, int status)
1968 Session *s = session_by_pid(pid);
1970 debug("session_close_by_pid: no session for pid %d", s->pid);
1973 if (s->chanid != -1)
1974 session_exit_message(s, status);
1979 * this is called when a channel dies before
1980 * the session 'child' itself dies
1983 session_close_by_channel(int id, void *arg)
1985 Session *s = session_by_channel(id);
1987 debug("session_close_by_channel: no session for channel %d", id);
1990 /* disconnect channel */
1991 channel_cancel_cleanup(s->chanid);
1994 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1996 /* close session immediately */
1999 /* notify child, delay session cleanup */
2000 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
2001 error("session_close_by_channel: kill %d: %s",
2002 s->pid, strerror(errno));
2007 session_tty_list(void)
2009 static char buf[1024];
2012 for(i = 0; i < MAX_SESSIONS; i++) {
2013 Session *s = &sessions[i];
2014 if (s->used && s->ttyfd != -1) {
2016 strlcat(buf, ",", sizeof buf);
2017 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2021 strlcpy(buf, "notty", sizeof buf);
2026 session_proctitle(Session *s)
2029 error("no user for session %d", s->self);
2031 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2035 do_authenticated2(Authctxt *authctxt)
2040 xauthfile_cleanup_proc(NULL);