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.48 2001/01/13 18:43:31 markus Exp $");
53 #include "auth-options.h"
55 #ifdef WITH_IRIX_PROJECT
57 #endif /* WITH_IRIX_PROJECT */
59 #include <sys/resource.h>
61 #ifdef WITH_IRIX_AUDIT
63 #endif /* WITH_IRIX_AUDIT */
65 #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"
92 #include <login_cap.h>
98 typedef struct Session Session;
107 int ptyfd, ttyfd, ptymaster;
108 int row, col, xpixel, ypixel;
115 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, struct passwd * pw);
127 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
128 void do_login(Session *s, const char *command);
131 do_child(const char *command, struct passwd * pw, const char *term,
132 const char *display, const char *auth_proto,
133 const char *auth_data, const char *ttyname);
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 * Remove local Xauthority file.
167 xauthfile_cleanup_proc(void *ignore)
169 debug("xauthfile_cleanup_proc called");
171 if (xauthfile != NULL) {
174 p = strrchr(xauthfile, '/');
185 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
186 * dropped connection).
189 pty_cleanup_proc(void *session)
193 fatal("pty_cleanup_proc: no session");
194 debug("pty_cleanup_proc: %s", s->tty);
197 /* Record that the user has logged out. */
198 record_logout(s->pid, s->tty);
201 /* Release the pseudo-tty. */
206 * Prepares for an interactive session. This is called after the user has
207 * been successfully authenticated. During this message exchange, pseudo
208 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
209 * are requested, etc.
212 do_authenticated(struct passwd * pw)
216 int compression_level = 0, enable_compression_after_reply = 0;
221 u_int proto_len, data_len, dlen;
224 * Cancel the alarm we set to limit the time taken for
228 if (startup_pipe != -1) {
234 * Inform the channel mechanism that we are the server side and that
235 * the client may request to connect to any port at all. (The user
236 * could do it anyway, and we wouldn\'t know what is permitted except
237 * by the client telling us, so we can equally well trust the client
238 * not to request anything bogus.)
240 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
241 channel_permit_all_opens();
246 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
247 if ((lc = login_getclass(pw->pw_class)) == NULL) {
248 error("unable to get login class");
254 * We stay in this loop until the client requests to execute a shell
260 /* Get a packet from the client. */
261 type = packet_read(&plen);
263 /* Process the packet. */
265 case SSH_CMSG_REQUEST_COMPRESSION:
266 packet_integrity_check(plen, 4, type);
267 compression_level = packet_get_int();
268 if (compression_level < 1 || compression_level > 9) {
269 packet_send_debug("Received illegal compression level %d.",
273 /* Enable compression after we have responded with SUCCESS. */
274 enable_compression_after_reply = 1;
278 case SSH_CMSG_REQUEST_PTY:
280 debug("Allocating a pty not permitted for this authentication.");
284 packet_disconnect("Protocol error: you already have a pty.");
286 debug("Allocating pty.");
288 /* Allocate a pty and open it. */
289 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
291 error("Failed to allocate pty.");
294 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
295 pty_setowner(pw, s->tty);
297 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
298 s->term = packet_get_string(&dlen);
299 packet_integrity_check(dlen, strlen(s->term), type);
300 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
301 /* Remaining bytes */
302 n_bytes = plen - (4 + dlen + 4 * 4);
304 if (strcmp(s->term, "") == 0) {
308 /* Get window size from the packet. */
309 s->row = packet_get_int();
310 s->col = packet_get_int();
311 s->xpixel = packet_get_int();
312 s->ypixel = packet_get_int();
313 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
315 /* Get tty modes from the packet. */
316 tty_parse_modes(s->ttyfd, &n_bytes);
317 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
319 session_proctitle(s);
321 /* Indicate that we now have a pty. */
326 case SSH_CMSG_X11_REQUEST_FORWARDING:
327 if (!options.x11_forwarding) {
328 packet_send_debug("X11 forwarding disabled in server configuration file.");
331 if (!options.xauth_location) {
332 packet_send_debug("No xauth program; cannot forward with spoofing.");
335 if (no_x11_forwarding_flag) {
336 packet_send_debug("X11 forwarding not permitted for this authentication.");
339 debug("Received request for X11 forwarding with auth spoofing.");
340 if (s->display != NULL)
341 packet_disconnect("Protocol error: X11 display already set.");
343 s->auth_proto = packet_get_string(&proto_len);
344 s->auth_data = packet_get_string(&data_len);
345 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
347 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
348 s->screen = packet_get_int();
351 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
353 if (s->display == NULL)
356 /* Setup to always have a local .Xauthority. */
357 xauthfile = xmalloc(MAXPATHLEN);
358 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
359 temporarily_use_uid(pw->pw_uid);
360 if (mkdtemp(xauthfile) == NULL) {
362 error("private X11 dir: mkdtemp %s failed: %s",
363 xauthfile, strerror(errno));
366 /* XXXX remove listening channels */
369 strlcat(xauthfile, "/cookies", MAXPATHLEN);
370 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
374 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
378 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
379 if (no_agent_forwarding_flag || compat13) {
380 debug("Authentication agent forwarding not permitted for this authentication.");
383 debug("Received authentication agent forwarding request.");
384 success = auth_input_request_forwarding(pw);
387 case SSH_CMSG_PORT_FORWARD_REQUEST:
388 if (no_port_forwarding_flag) {
389 debug("Port forwarding not permitted for this authentication.");
392 if (!options.allow_tcp_forwarding) {
393 debug("Port forwarding not permitted.");
396 debug("Received TCP/IP port forwarding request.");
397 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
401 case SSH_CMSG_MAX_PACKET_SIZE:
402 if (packet_set_maxsize(packet_get_int()) > 0)
406 case SSH_CMSG_EXEC_SHELL:
407 case SSH_CMSG_EXEC_CMD:
408 if (type == SSH_CMSG_EXEC_CMD) {
409 command = packet_get_string(&dlen);
410 debug("Exec command '%.500s'", command);
411 packet_integrity_check(plen, 4 + dlen, type);
414 packet_integrity_check(plen, 0, type);
416 if (forced_command != NULL) {
417 original_command = command;
418 command = forced_command;
419 debug("Forced command '%.500s'", forced_command);
422 do_exec_pty(s, command, pw);
424 do_exec_no_pty(s, command, pw);
428 /* Cleanup user's local Xauthority file. */
430 xauthfile_cleanup_proc(NULL);
435 * Any unknown messages in this phase are ignored,
436 * and a failure message is returned.
438 log("Unknown packet type received after authentication: %d", type);
440 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
444 /* Enable compression now that we have replied if appropriate. */
445 if (enable_compression_after_reply) {
446 enable_compression_after_reply = 0;
447 packet_start_compression(compression_level);
453 * This is called to fork and execute a command when we have no tty. This
454 * will call do_child from the child, and server_loop from the parent after
455 * setting up file descriptors and such.
458 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
463 int pin[2], pout[2], perr[2];
464 /* Allocate pipes for communicating with the program. */
465 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
466 packet_disconnect("Could not create pipes: %.100s",
468 #else /* USE_PIPES */
469 int inout[2], err[2];
470 /* Uses socket pairs to communicate with the program. */
471 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
472 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
473 packet_disconnect("Could not create socket pairs: %.100s",
475 #endif /* USE_PIPES */
477 fatal("do_exec_no_pty: no session");
479 session_proctitle(s);
485 /* Fork the child. */
486 if ((pid = fork()) == 0) {
487 /* Child. Reinitialize the log since the pid has changed. */
488 log_init(__progname, options.log_level, options.log_facility, log_stderr);
490 signal(SIGPIPE, SIG_DFL);
493 * Create a new session and process group since the 4.4BSD
494 * setlogin() affects the entire process group.
497 error("setsid failed: %.100s", strerror(errno));
501 * Redirect stdin. We close the parent side of the socket
502 * pair, and make the child side the standard input.
505 if (dup2(pin[0], 0) < 0)
506 perror("dup2 stdin");
509 /* Redirect stdout. */
511 if (dup2(pout[1], 1) < 0)
512 perror("dup2 stdout");
515 /* Redirect stderr. */
517 if (dup2(perr[1], 2) < 0)
518 perror("dup2 stderr");
520 #else /* USE_PIPES */
522 * Redirect stdin, stdout, and stderr. Stdin and stdout will
523 * use the same socket, as some programs (particularly rdist)
524 * seem to depend on it.
528 if (dup2(inout[0], 0) < 0) /* stdin */
529 perror("dup2 stdin");
530 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
531 perror("dup2 stdout");
532 if (dup2(err[0], 2) < 0) /* stderr */
533 perror("dup2 stderr");
534 #endif /* USE_PIPES */
536 /* Do processing for the child (exec command etc). */
537 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
542 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
545 packet_disconnect("fork failed: %.100s", strerror(errno));
547 /* Set interactive/non-interactive mode. */
548 packet_set_interactive(s->display != NULL);
550 /* We are the parent. Close the child sides of the pipes. */
556 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
558 /* Enter the interactive session. */
559 server_loop(pid, pin[1], pout[0], perr[0]);
560 /* server_loop has closed pin[1], pout[1], and perr[1]. */
562 #else /* USE_PIPES */
563 /* We are the parent. Close the child sides of the socket pairs. */
568 * Enter the interactive session. Note: server_loop must be able to
569 * handle the case that fdin and fdout are the same.
572 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
574 server_loop(pid, inout[1], inout[1], err[1]);
575 /* server_loop has closed inout[1] and err[1]. */
577 #endif /* USE_PIPES */
581 * This is called to fork and execute a command when we have a tty. This
582 * will call do_child from the child, and server_loop from the parent after
583 * setting up file descriptors, controlling tty, updating wtmp, utmp,
584 * lastlog, and other such operations.
587 do_exec_pty(Session *s, const char *command, struct passwd * pw)
589 int fdout, ptyfd, ttyfd, ptymaster;
593 fatal("do_exec_pty: no session");
598 do_pam_session(pw->pw_name, s->tty);
602 /* Fork the child. */
603 if ((pid = fork()) == 0) {
604 /* Child. Reinitialize the log because the pid has changed. */
605 log_init(__progname, options.log_level, options.log_facility, log_stderr);
607 signal(SIGPIPE, SIG_DFL);
609 /* Close the master side of the pseudo tty. */
612 /* Make the pseudo tty our controlling tty. */
613 pty_make_controlling_tty(&ttyfd, s->tty);
615 /* Redirect stdin from the pseudo tty. */
616 if (dup2(ttyfd, fileno(stdin)) < 0)
617 error("dup2 stdin failed: %.100s", strerror(errno));
619 /* Redirect stdout to the pseudo tty. */
620 if (dup2(ttyfd, fileno(stdout)) < 0)
621 error("dup2 stdin failed: %.100s", strerror(errno));
623 /* Redirect stderr to the pseudo tty. */
624 if (dup2(ttyfd, fileno(stderr)) < 0)
625 error("dup2 stdin failed: %.100s", strerror(errno));
627 /* Close the extra descriptor for the pseudo tty. */
630 /* record login, etc. similar to login(1) */
631 if (!(options.use_login && command == NULL))
632 do_login(s, command);
634 /* Do common processing for the child, such as execing the command. */
635 do_child(command, pw, s->term, s->display, s->auth_proto,
636 s->auth_data, s->tty);
641 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
644 packet_disconnect("fork failed: %.100s", strerror(errno));
647 /* Parent. Close the slave side of the pseudo tty. */
651 * Create another descriptor of the pty master side for use as the
652 * standard input. We could use the original descriptor, but this
653 * simplifies code in server_loop. The descriptor is bidirectional.
657 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
659 /* we keep a reference to the pty master */
660 ptymaster = dup(ptyfd);
662 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
663 s->ptymaster = ptymaster;
665 /* Enter interactive session. */
666 packet_set_interactive(1);
668 session_set_fds(s, ptyfd, fdout, -1);
670 server_loop(pid, ptyfd, fdout, -1);
671 /* server_loop _has_ closed ptyfd and fdout. */
672 session_pty_cleanup(s);
677 get_remote_name_or_ip(void)
679 static const char *remote = "";
681 remote = get_canonical_hostname();
682 if (utmp_len == 0 || strlen(remote) > utmp_len)
683 remote = get_remote_ipaddr();
687 /* administrative, login(1)-like work */
689 do_login(Session *s, const char *command)
694 char hostname[MAXHOSTNAMELEN];
696 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. */
718 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
719 hostname, sizeof(hostname));
721 /* Record that there was a login on that tty from the remote host. */
722 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
723 get_remote_name_or_ip(), (struct sockaddr *)&from);
727 * If password change is needed, do it now.
728 * This needs to occur before the ~/.hushlogin check.
730 if (pam_password_change_required()) {
731 print_pam_messages();
736 /* Done if .hushlogin exists or a command given. */
739 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
740 #ifdef HAVE_LOGIN_CAP
741 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
743 if (stat(buf, &st) >= 0)
748 if (!pam_password_change_required())
749 print_pam_messages();
751 #ifdef WITH_AIXAUTHENTICATE
752 if (aixloginmsg && *aixloginmsg)
753 printf("%s\n", aixloginmsg);
754 #endif /* WITH_AIXAUTHENTICATE */
756 if (last_login_time != 0) {
757 time_string = ctime(&last_login_time);
758 if (strchr(time_string, '\n'))
759 *strchr(time_string, '\n') = 0;
760 if (strcmp(hostname, "") == 0)
761 printf("Last login: %s\r\n", time_string);
763 printf("Last login: %s from %s\r\n", time_string, hostname);
765 if (options.print_motd) {
766 #ifdef HAVE_LOGIN_CAP
767 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
770 f = fopen("/etc/motd", "r");
773 while (fgets(buf, sizeof(buf), f))
781 * Sets the value of the given variable in the environment. If the variable
782 * already exists, its value is overriden.
785 child_set_env(char ***envp, u_int *envsizep, const char *name,
792 * Find the slot where the value should be stored. If the variable
793 * already exists, we reuse the slot; otherwise we append a new slot
794 * at the end of the array, expanding if necessary.
797 namelen = strlen(name);
798 for (i = 0; env[i]; i++)
799 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
802 /* Reuse the slot. */
805 /* New variable. Expand if necessary. */
806 if (i >= (*envsizep) - 1) {
808 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
810 /* Need to set the NULL pointer at end of array beyond the new slot. */
814 /* Allocate space and format the variable in the appropriate slot. */
815 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
816 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
820 * Reads environment variables from the given file and adds/overrides them
821 * into the environment. If the file does not exist, this does nothing.
822 * Otherwise, it must consist of empty lines, comments (line starts with '#')
823 * and assignments of the form name=value. No other forms are allowed.
826 read_environment_file(char ***env, u_int *envsize,
827 const char *filename)
833 f = fopen(filename, "r");
837 while (fgets(buf, sizeof(buf), f)) {
838 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
840 if (!*cp || *cp == '#' || *cp == '\n')
842 if (strchr(cp, '\n'))
843 *strchr(cp, '\n') = '\0';
844 value = strchr(cp, '=');
846 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
850 * Replace the equals sign by nul, and advance value to
855 child_set_env(env, envsize, cp, value);
862 * Sets any environment variables which have been specified by PAM
864 void do_pam_environment(char ***env, int *envsize)
866 char *equals, var_name[512], var_val[512];
870 if ((pam_env = fetch_pam_environment()) == NULL)
873 for(i = 0; pam_env[i] != NULL; i++) {
874 if ((equals = strstr(pam_env[i], "=")) == NULL)
877 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
878 memset(var_name, '\0', sizeof(var_name));
879 memset(var_val, '\0', sizeof(var_val));
881 strncpy(var_name, pam_env[i], equals - pam_env[i]);
882 strcpy(var_val, equals + 1);
884 debug3("PAM environment: %s=%s", var_name, var_val);
886 child_set_env(env, envsize, var_name, var_val);
894 void copy_environment(char ***env, int *envsize)
896 char *equals, var_name[512], var_val[512];
899 for(i = 0; environ[i] != NULL; i++) {
900 if ((equals = strstr(environ[i], "=")) == NULL)
903 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
904 memset(var_name, '\0', sizeof(var_name));
905 memset(var_val, '\0', sizeof(var_val));
907 strncpy(var_name, environ[i], equals - environ[i]);
908 strcpy(var_val, equals + 1);
910 debug3("Copy environment: %s=%s", var_name, var_val);
912 child_set_env(env, envsize, var_name, var_val);
918 #if defined(HAVE_GETUSERATTR)
920 * AIX-specific login initialisation
922 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
927 getrlimit(resource, &rlim);
930 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
932 rlim.rlim_cur = RLIM_INFINITY;
933 } else if (slim != 0) {
934 /* See the wackiness below */
935 if (rlim.rlim_cur == slim * mult)
938 rlim.rlim_cur = slim * mult;
943 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
945 rlim.rlim_max = RLIM_INFINITY;
946 } else if (hlim != 0) {
947 rlim.rlim_max = hlim * mult;
952 * XXX For cpu and fsize the soft limit is set to the hard limit
953 * if the hard limit is left at its default value and the soft limit
954 * is changed from its default value, either by requesting it
955 * (slim == 0) or by setting it to the current default. At least
956 * that's how rlogind does it. If you're confused you're not alone.
957 * Bug or feature? AIX 4.3.1.2
959 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
960 && hlim == 0 && slim != 0)
961 rlim.rlim_max = rlim.rlim_cur;
962 /* A specified hard limit limits the soft limit */
963 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
964 rlim.rlim_cur = rlim.rlim_max;
965 /* A soft limit can increase a hard limit */
966 else if (rlim.rlim_cur > rlim.rlim_max)
967 rlim.rlim_max = rlim.rlim_cur;
969 if (setrlimit(resource, &rlim) != 0)
970 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
973 void set_limits_from_userattr(char *user)
978 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
979 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
980 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
981 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
982 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
983 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
984 #if defined(S_UNOFILE)
985 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
988 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
989 /* Convert decimal to octal */
990 (void) snprintf(buf, sizeof(buf), "%d", mask);
991 if (sscanf(buf, "%o", &mask) == 1)
995 #endif /* defined(HAVE_GETUSERATTR) */
998 * Performs common processing for the child, such as setting up the
999 * environment, closing extra file descriptors, setting the user and group
1000 * ids, and executing the command or shell.
1003 do_child(const char *command, struct passwd * pw, const char *term,
1004 const char *display, const char *auth_proto,
1005 const char *auth_data, const char *ttyname)
1007 const char *shell, *hostname = NULL, *cp = NULL;
1013 extern char **environ;
1016 #ifdef WITH_IRIX_PROJECT
1018 #endif /* WITH_IRIX_PROJECT */
1019 #ifdef WITH_IRIX_JOBS
1022 #ifdef WITH_IRIX_ARRAY
1024 #endif /* WITH_IRIX_ARRAY */
1025 #endif /* WITH_IRIX_JOBS */
1028 /* login(1) is only called if we execute the login shell */
1029 if (options.use_login && command != NULL)
1030 options.use_login = 0;
1032 #ifndef USE_PAM /* pam_nologin handles this */
1033 if (!options.use_login) {
1034 # ifdef HAVE_LOGIN_CAP
1035 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1036 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1037 _PATH_NOLOGIN), "r");
1038 # else /* HAVE_LOGIN_CAP */
1040 f = fopen(_PATH_NOLOGIN, "r");
1041 # endif /* HAVE_LOGIN_CAP */
1043 /* /etc/nologin exists. Print its contents and exit. */
1044 while (fgets(buf, sizeof(buf), f))
1050 #endif /* USE_PAM */
1052 /* Set login name, uid, gid, and groups. */
1053 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1054 switch, so we let login(1) to this for us. */
1055 if (!options.use_login) {
1057 extern char **saved_argv;
1058 extern int saved_argc;
1059 char *host = get_canonical_hostname ();
1061 if (sia_become_user(NULL, saved_argc, saved_argv, host,
1062 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
1064 perror("sia_become_user");
1067 if (setreuid(geteuid(), geteuid()) < 0) {
1071 #else /* HAVE_OSF_SIA */
1075 if (getuid() == 0 || geteuid() == 0) {
1077 # ifdef HAVE_GETUSERATTR
1078 set_limits_from_userattr(pw->pw_name);
1079 # endif /* HAVE_GETUSERATTR */
1080 # ifdef HAVE_LOGIN_CAP
1081 if (setusercontext(lc, pw, pw->pw_uid,
1082 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1083 perror("unable to set user context");
1086 # else /* HAVE_LOGIN_CAP */
1087 if (setlogin(pw->pw_name) < 0)
1088 error("setlogin failed: %s", strerror(errno));
1089 if (setgid(pw->pw_gid) < 0) {
1093 /* Initialize the group list. */
1094 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1095 perror("initgroups");
1099 # ifdef WITH_IRIX_JOBS
1100 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1102 fatal("Failed to create job container: %.100s",
1105 # endif /* WITH_IRIX_JOBS */
1106 # ifdef WITH_IRIX_ARRAY
1107 /* initialize array session */
1109 if (newarraysess() != 0)
1110 fatal("Failed to set up new array session: %.100s",
1113 # endif /* WITH_IRIX_ARRAY */
1114 # ifdef WITH_IRIX_PROJECT
1115 /* initialize irix project info */
1116 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1117 debug("Failed to get project id, using projid 0");
1120 if (setprid(projid))
1121 fatal("Failed to initialize project %d for %s: %.100s",
1122 (int)projid, pw->pw_name, strerror(errno));
1123 # endif /* WITH_IRIX_PROJECT */
1124 #ifdef WITH_IRIX_AUDIT
1125 if (sysconf(_SC_AUDIT)) {
1126 debug("Setting sat id to %d", (int) pw->pw_uid);
1127 if (satsetid(pw->pw_uid))
1128 debug("error setting satid: %.100s", strerror(errno));
1130 #endif /* WITH_IRIX_AUDIT */
1132 /* Permanently switch to the desired uid. */
1133 permanently_set_uid(pw->pw_uid);
1134 # endif /* HAVE_LOGIN_CAP */
1136 #endif /* HAVE_OSF_SIA */
1141 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1142 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1145 * Get the shell from the password data. An empty shell field is
1146 * legal, and means /bin/sh.
1148 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1149 #ifdef HAVE_LOGIN_CAP
1150 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1154 /* Try to get AFS tokens for the local cell. */
1158 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1159 krb_afslog(cell, 0);
1165 /* Initialize the environment. */
1167 env = xmalloc(envsize * sizeof(char *));
1172 * The Windows environment contains some setting which are
1173 * important for a running system. They must not be dropped.
1175 copy_environment(&env, &envsize);
1178 if (!options.use_login) {
1179 /* Set basic environment. */
1180 child_set_env(&env, &envsize, "USER", pw->pw_name);
1181 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1182 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1183 #ifdef HAVE_LOGIN_CAP
1184 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1185 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1186 #else /* HAVE_LOGIN_CAP */
1187 # ifndef HAVE_CYGWIN
1189 * There's no standard path on Windows. The path contains
1190 * important components pointing to the system directories,
1191 * needed for loading shared libraries. So the path better
1192 * remains intact here.
1194 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1195 # endif /* HAVE_CYGWIN */
1196 #endif /* HAVE_LOGIN_CAP */
1198 snprintf(buf, sizeof buf, "%.200s/%.50s",
1199 _PATH_MAILDIR, pw->pw_name);
1200 child_set_env(&env, &envsize, "MAIL", buf);
1202 /* Normal systems set SHELL by default. */
1203 child_set_env(&env, &envsize, "SHELL", shell);
1206 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1208 /* Set custom environment options from RSA authentication. */
1209 while (custom_environment) {
1210 struct envstring *ce = custom_environment;
1213 for (i = 0; s[i] != '=' && s[i]; i++);
1216 child_set_env(&env, &envsize, s, s + i + 1);
1218 custom_environment = ce->next;
1223 snprintf(buf, sizeof buf, "%.50s %d %d",
1224 get_remote_ipaddr(), get_remote_port(), get_local_port());
1225 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1228 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1230 child_set_env(&env, &envsize, "TERM", term);
1232 child_set_env(&env, &envsize, "DISPLAY", display);
1233 if (original_command)
1234 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1238 if ((cp = getenv("AUTHSTATE")) != NULL)
1239 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1240 if ((cp = getenv("KRB5CCNAME")) != NULL)
1241 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1242 read_environment_file(&env, &envsize, "/etc/environment");
1247 extern char *ticket;
1250 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1255 /* Pull in any environment variables that may have been set by PAM. */
1256 do_pam_environment(&env, &envsize);
1257 #endif /* USE_PAM */
1260 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1261 if (auth_get_socket_name() != NULL)
1262 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1263 auth_get_socket_name());
1265 /* read $HOME/.ssh/environment. */
1266 if (!options.use_login) {
1267 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1269 read_environment_file(&env, &envsize, buf);
1272 /* dump the environment */
1273 fprintf(stderr, "Environment:\n");
1274 for (i = 0; env[i]; i++)
1275 fprintf(stderr, " %.200s\n", env[i]);
1277 /* we have to stash the hostname before we close our socket. */
1278 if (options.use_login)
1279 hostname = get_remote_name_or_ip();
1281 * Close the connection descriptors; note that this is the child, and
1282 * the server will still have the socket open, and it is important
1283 * that we do not shutdown it. Note that the descriptors cannot be
1284 * closed before building the environment, as we call
1285 * get_remote_ipaddr there.
1287 if (packet_get_connection_in() == packet_get_connection_out())
1288 close(packet_get_connection_in());
1290 close(packet_get_connection_in());
1291 close(packet_get_connection_out());
1294 * Close all descriptors related to channels. They will still remain
1295 * open in the parent.
1297 /* XXX better use close-on-exec? -markus */
1298 channel_close_all();
1301 * Close any extra file descriptors. Note that there may still be
1302 * descriptors left by system functions. They will be closed later.
1307 * Close any extra open file descriptors so that we don\'t have them
1308 * hanging around in clients. Note that we want to do this after
1309 * initgroups, because at least on Solaris 2.3 it leaves file
1312 for (i = 3; i < 64; i++)
1315 /* Change current directory to the user\'s home directory. */
1316 if (chdir(pw->pw_dir) < 0) {
1317 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1318 pw->pw_dir, strerror(errno));
1319 #ifdef HAVE_LOGIN_CAP
1320 if (login_getcapbool(lc, "requirehome", 0))
1326 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1327 * xauth are run in the proper environment.
1332 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1335 if (!options.use_login) {
1336 if (stat(SSH_USER_RC, &st) >= 0) {
1338 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, SSH_USER_RC);
1340 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1342 if (auth_proto != NULL && auth_data != NULL)
1343 fprintf(f, "%s %s\n", auth_proto, auth_data);
1346 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1347 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1349 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, SSH_SYSTEM_RC);
1351 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1353 if (auth_proto != NULL && auth_data != NULL)
1354 fprintf(f, "%s %s\n", auth_proto, auth_data);
1357 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1358 } else if (options.xauth_location != NULL) {
1359 /* Add authority data to .Xauthority if appropriate. */
1360 if (auth_proto != NULL && auth_data != NULL) {
1361 char *screen = strchr(display, ':');
1364 "Running %.100s add %.100s %.100s %.100s\n",
1365 options.xauth_location, display,
1366 auth_proto, auth_data);
1367 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1370 "Adding %.*s/unix%s %s %s\n",
1371 (int)(screen-display), display,
1372 screen, auth_proto, auth_data);
1375 snprintf(cmd, sizeof cmd, "%s -q -",
1376 options.xauth_location);
1377 f = popen(cmd, "w");
1379 fprintf(f, "add %s %s %s\n", display,
1380 auth_proto, auth_data);
1381 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1383 fprintf(f, "add %.*s/unix%s %s %s\n",
1384 (int)(screen-display), display,
1385 screen, auth_proto, auth_data);
1389 fprintf(stderr, "Could not run %s\n",
1394 /* Get the last component of the shell name. */
1395 cp = strrchr(shell, '/');
1402 * If we have no command, execute the shell. In this case, the shell
1403 * name to be passed in argv[0] is preceded by '-' to indicate that
1404 * this is a login shell.
1407 if (!options.use_login) {
1411 * Check for mail if we have a tty and it was enabled
1412 * in server options.
1414 if (ttyname && options.check_mail) {
1416 struct stat mailstat;
1417 mailbox = getenv("MAIL");
1418 if (mailbox != NULL) {
1419 if (stat(mailbox, &mailstat) != 0 ||
1420 mailstat.st_size == 0)
1421 printf("No mail.\n");
1422 else if (mailstat.st_mtime < mailstat.st_atime)
1423 printf("You have mail.\n");
1425 printf("You have new mail.\n");
1428 /* Start the shell. Set initial character to '-'. */
1430 strncpy(buf + 1, cp, sizeof(buf) - 1);
1431 buf[sizeof(buf) - 1] = 0;
1433 /* Execute the shell. */
1436 execve(shell, argv, env);
1438 /* Executing the shell failed. */
1443 /* Launch login(1). */
1445 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1446 "-p", "-f", "--", pw->pw_name, NULL);
1448 /* Login couldn't be executed, die. */
1455 * Execute the command using the user's shell. This uses the -c
1456 * option to execute the command.
1458 argv[0] = (char *) cp;
1460 argv[2] = (char *) command;
1462 execve(shell, argv, env);
1471 static int did_init = 0;
1473 debug("session_new: init");
1474 for(i = 0; i < MAX_SESSIONS; i++) {
1475 sessions[i].used = 0;
1476 sessions[i].self = i;
1480 for(i = 0; i < MAX_SESSIONS; i++) {
1481 Session *s = &sessions[i];
1492 s->auth_data = NULL;
1493 s->auth_proto = NULL;
1496 debug("session_new: session %d", i);
1507 for(i = 0; i < MAX_SESSIONS; i++) {
1508 Session *s = &sessions[i];
1509 debug("dump: used %d session %d %p channel %d pid %d",
1519 session_open(int chanid)
1521 Session *s = session_new();
1522 debug("session_open: channel %d", chanid);
1524 error("no more sessions");
1527 s->pw = auth_get_user();
1529 fatal("no user for session %i", s->self);
1530 debug("session_open: session %d: link with channel %d", s->self, chanid);
1536 session_by_channel(int id)
1539 for(i = 0; i < MAX_SESSIONS; i++) {
1540 Session *s = &sessions[i];
1541 if (s->used && s->chanid == id) {
1542 debug("session_by_channel: session %d channel %d", i, id);
1546 debug("session_by_channel: unknown channel %d", id);
1552 session_by_pid(pid_t pid)
1555 debug("session_by_pid: pid %d", pid);
1556 for(i = 0; i < MAX_SESSIONS; i++) {
1557 Session *s = &sessions[i];
1558 if (s->used && s->pid == pid)
1561 error("session_by_pid: unknown pid %d", pid);
1567 session_window_change_req(Session *s)
1569 s->col = packet_get_int();
1570 s->row = packet_get_int();
1571 s->xpixel = packet_get_int();
1572 s->ypixel = packet_get_int();
1574 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1579 session_pty_req(Session *s)
1582 char *term_modes; /* encoded terminal modes */
1588 s->term = packet_get_string(&len);
1589 s->col = packet_get_int();
1590 s->row = packet_get_int();
1591 s->xpixel = packet_get_int();
1592 s->ypixel = packet_get_int();
1593 term_modes = packet_get_string(&len);
1596 if (strcmp(s->term, "") == 0) {
1600 /* Allocate a pty and open it. */
1601 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1606 error("session_pty_req: session %d alloc failed", s->self);
1610 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1612 * Add a cleanup function to clear the utmp entry and record logout
1613 * time in case we call fatal() (e.g., the connection gets closed).
1615 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1616 pty_setowner(s->pw, s->tty);
1617 /* Get window size from the packet. */
1618 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1620 session_proctitle(s);
1622 /* XXX parse and set terminal modes */
1628 session_subsystem_req(Session *s)
1632 char *subsys = packet_get_string(&len);
1636 log("subsystem request for %s", subsys);
1638 for (i = 0; i < options.num_subsystems; i++) {
1639 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1640 debug("subsystem: exec() %s", options.subsystem_command[i]);
1641 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1647 log("subsystem request for %s failed, subsystem not found", subsys);
1654 session_x11_req(Session *s)
1657 if (no_x11_forwarding_flag) {
1658 debug("X11 forwarding disabled in user configuration file.");
1661 if (!options.x11_forwarding) {
1662 debug("X11 forwarding disabled in server configuration file.");
1665 if (xauthfile != NULL) {
1666 debug("X11 fwd already started.");
1670 debug("Received request for X11 forwarding with auth spoofing.");
1671 if (s->display != NULL)
1672 packet_disconnect("Protocol error: X11 display already set.");
1674 s->single_connection = packet_get_char();
1675 s->auth_proto = packet_get_string(NULL);
1676 s->auth_data = packet_get_string(NULL);
1677 s->screen = packet_get_int();
1680 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1681 if (s->display == NULL) {
1682 xfree(s->auth_proto);
1683 xfree(s->auth_data);
1686 xauthfile = xmalloc(MAXPATHLEN);
1687 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1688 temporarily_use_uid(s->pw->pw_uid);
1689 if (mkdtemp(xauthfile) == NULL) {
1691 error("private X11 dir: mkdtemp %s failed: %s",
1692 xauthfile, strerror(errno));
1695 xfree(s->auth_proto);
1696 xfree(s->auth_data);
1697 /* XXXX remove listening channels */
1700 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1701 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1705 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1710 session_shell_req(Session *s)
1712 /* if forced_command == NULL, the shell is execed */
1713 char *shell = forced_command;
1717 do_exec_no_pty(s, shell, s->pw);
1719 do_exec_pty(s, shell, s->pw);
1724 session_exec_req(Session *s)
1727 char *command = packet_get_string(&len);
1729 if (forced_command) {
1730 original_command = command;
1731 command = forced_command;
1732 debug("Forced command '%.500s'", forced_command);
1736 do_exec_no_pty(s, command, s->pw);
1738 do_exec_pty(s, command, s->pw);
1739 if (forced_command == NULL)
1745 session_auth_agent_req(Session *s)
1747 static int called = 0;
1749 if (no_agent_forwarding_flag) {
1750 debug("session_auth_agent_req: no_agent_forwarding_flag");
1757 return auth_input_request_forwarding(s->pw);
1762 session_input_channel_req(int id, void *arg)
1771 rtype = packet_get_string(&len);
1772 reply = packet_get_char();
1774 s = session_by_channel(id);
1776 fatal("session_input_channel_req: channel %d: no session", id);
1777 c = channel_lookup(id);
1779 fatal("session_input_channel_req: channel %d: bad channel", id);
1781 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1782 s->self, id, rtype, reply);
1785 * a session is in LARVAL state until a shell
1786 * or programm is executed
1788 if (c->type == SSH_CHANNEL_LARVAL) {
1789 if (strcmp(rtype, "shell") == 0) {
1790 success = session_shell_req(s);
1791 } else if (strcmp(rtype, "exec") == 0) {
1792 success = session_exec_req(s);
1793 } else if (strcmp(rtype, "pty-req") == 0) {
1794 success = session_pty_req(s);
1795 } else if (strcmp(rtype, "x11-req") == 0) {
1796 success = session_x11_req(s);
1797 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1798 success = session_auth_agent_req(s);
1799 } else if (strcmp(rtype, "subsystem") == 0) {
1800 success = session_subsystem_req(s);
1803 if (strcmp(rtype, "window-change") == 0) {
1804 success = session_window_change_req(s);
1808 packet_start(success ?
1809 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1810 packet_put_int(c->remote_id);
1817 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1820 fatal("session_set_fds: called for proto != 2.0");
1822 * now that have a child and a pipe to the child,
1823 * we can activate our channel and register the fd's
1825 if (s->chanid == -1)
1826 fatal("no channel for session %d", s->self);
1827 channel_set_fds(s->chanid,
1829 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1834 session_pty_cleanup(Session *s)
1836 if (s == NULL || s->ttyfd == -1)
1839 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1841 /* Cancel the cleanup function. */
1842 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1844 /* Record that the user has logged out. */
1845 record_logout(s->pid, s->tty);
1847 /* Release the pseudo-tty. */
1848 pty_release(s->tty);
1851 * Close the server side of the socket pairs. We must do this after
1852 * the pty cleanup, so that another process doesn't get this pty
1853 * while we're still cleaning up.
1855 if (close(s->ptymaster) < 0)
1856 error("close(s->ptymaster): %s", strerror(errno));
1860 session_exit_message(Session *s, int status)
1864 fatal("session_close: no session");
1865 c = channel_lookup(s->chanid);
1867 fatal("session_close: session %d: no channel %d",
1868 s->self, s->chanid);
1869 debug("session_exit_message: session %d channel %d pid %d",
1870 s->self, s->chanid, s->pid);
1872 if (WIFEXITED(status)) {
1873 channel_request_start(s->chanid,
1875 packet_put_int(WEXITSTATUS(status));
1877 } else if (WIFSIGNALED(status)) {
1878 channel_request_start(s->chanid,
1880 packet_put_int(WTERMSIG(status));
1882 packet_put_char(WCOREDUMP(status));
1883 #else /* WCOREDUMP */
1885 #endif /* WCOREDUMP */
1886 packet_put_cstring("");
1887 packet_put_cstring("");
1890 /* Some weird exit cause. Just exit. */
1891 packet_disconnect("wait returned status %04x.", status);
1894 /* disconnect channel */
1895 debug("session_exit_message: release channel %d", s->chanid);
1896 channel_cancel_cleanup(s->chanid);
1898 * emulate a write failure with 'chan_write_failed', nobody will be
1899 * interested in data we write.
1900 * Note that we must not call 'chan_read_failed', since there could
1901 * be some more data waiting in the pipe.
1903 if (c->ostate != CHAN_OUTPUT_CLOSED)
1904 chan_write_failed(c);
1909 session_free(Session *s)
1911 debug("session_free: session %d pid %d", s->self, s->pid);
1917 xfree(s->auth_data);
1919 xfree(s->auth_proto);
1924 session_close(Session *s)
1926 session_pty_cleanup(s);
1928 session_proctitle(s);
1932 session_close_by_pid(pid_t pid, int status)
1934 Session *s = session_by_pid(pid);
1936 debug("session_close_by_pid: no session for pid %d", s->pid);
1939 if (s->chanid != -1)
1940 session_exit_message(s, status);
1945 * this is called when a channel dies before
1946 * the session 'child' itself dies
1949 session_close_by_channel(int id, void *arg)
1951 Session *s = session_by_channel(id);
1953 debug("session_close_by_channel: no session for channel %d", id);
1956 /* disconnect channel */
1957 channel_cancel_cleanup(s->chanid);
1960 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1962 /* close session immediately */
1965 /* notify child, delay session cleanup */
1967 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1968 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1969 error("session_close_by_channel: kill %d: %s",
1970 s->pid, strerror(errno));
1975 session_tty_list(void)
1977 static char buf[1024];
1980 for(i = 0; i < MAX_SESSIONS; i++) {
1981 Session *s = &sessions[i];
1982 if (s->used && s->ttyfd != -1) {
1984 strlcat(buf, ",", sizeof buf);
1985 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1989 strlcpy(buf, "notty", sizeof buf);
1994 session_proctitle(Session *s)
1997 error("no user for session %d", s->self);
1999 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2003 do_authenticated2(void)
2005 #ifdef HAVE_LOGIN_CAP
2010 * Cancel the alarm we set to limit the time taken for
2014 if (startup_pipe != -1) {
2015 close(startup_pipe);
2018 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
2019 pw = auth_get_user();
2020 if ((lc = login_getclass(pw->pw_class)) == NULL) {
2021 error("unable to get login class");
2027 xauthfile_cleanup_proc(NULL);