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.43 2000/11/06 23:04:56 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 unsigned 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 unsigned 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 /* Set interactive/non-interactive mode. */
409 packet_set_interactive(have_pty || s->display != NULL,
412 if (type == SSH_CMSG_EXEC_CMD) {
413 command = packet_get_string(&dlen);
414 debug("Exec command '%.500s'", command);
415 packet_integrity_check(plen, 4 + dlen, type);
418 packet_integrity_check(plen, 0, type);
420 if (forced_command != NULL) {
421 original_command = command;
422 command = forced_command;
423 debug("Forced command '%.500s'", forced_command);
426 do_exec_pty(s, command, pw);
428 do_exec_no_pty(s, command, pw);
432 /* Cleanup user's local Xauthority file. */
434 xauthfile_cleanup_proc(NULL);
439 * Any unknown messages in this phase are ignored,
440 * and a failure message is returned.
442 log("Unknown packet type received after authentication: %d", type);
444 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
448 /* Enable compression now that we have replied if appropriate. */
449 if (enable_compression_after_reply) {
450 enable_compression_after_reply = 0;
451 packet_start_compression(compression_level);
457 * This is called to fork and execute a command when we have no tty. This
458 * will call do_child from the child, and server_loop from the parent after
459 * setting up file descriptors and such.
462 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
467 int pin[2], pout[2], perr[2];
468 /* Allocate pipes for communicating with the program. */
469 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
470 packet_disconnect("Could not create pipes: %.100s",
472 #else /* USE_PIPES */
473 int inout[2], err[2];
474 /* Uses socket pairs to communicate with the program. */
475 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
476 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
477 packet_disconnect("Could not create socket pairs: %.100s",
479 #endif /* USE_PIPES */
481 fatal("do_exec_no_pty: no session");
483 signal(SIGPIPE, SIG_DFL);
485 session_proctitle(s);
491 /* Fork the child. */
492 if ((pid = fork()) == 0) {
493 /* Child. Reinitialize the log since the pid has changed. */
494 log_init(__progname, options.log_level, options.log_facility, log_stderr);
497 * Create a new session and process group since the 4.4BSD
498 * setlogin() affects the entire process group.
501 error("setsid failed: %.100s", strerror(errno));
505 * Redirect stdin. We close the parent side of the socket
506 * pair, and make the child side the standard input.
509 if (dup2(pin[0], 0) < 0)
510 perror("dup2 stdin");
513 /* Redirect stdout. */
515 if (dup2(pout[1], 1) < 0)
516 perror("dup2 stdout");
519 /* Redirect stderr. */
521 if (dup2(perr[1], 2) < 0)
522 perror("dup2 stderr");
524 #else /* USE_PIPES */
526 * Redirect stdin, stdout, and stderr. Stdin and stdout will
527 * use the same socket, as some programs (particularly rdist)
528 * seem to depend on it.
532 if (dup2(inout[0], 0) < 0) /* stdin */
533 perror("dup2 stdin");
534 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
535 perror("dup2 stdout");
536 if (dup2(err[0], 2) < 0) /* stderr */
537 perror("dup2 stderr");
538 #endif /* USE_PIPES */
540 /* Do processing for the child (exec command etc). */
541 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
546 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
549 packet_disconnect("fork failed: %.100s", strerror(errno));
552 /* We are the parent. Close the child sides of the pipes. */
558 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
560 /* Enter the interactive session. */
561 server_loop(pid, pin[1], pout[0], perr[0]);
562 /* server_loop has closed pin[1], pout[1], and perr[1]. */
564 #else /* USE_PIPES */
565 /* We are the parent. Close the child sides of the socket pairs. */
570 * Enter the interactive session. Note: server_loop must be able to
571 * handle the case that fdin and fdout are the same.
574 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
576 server_loop(pid, inout[1], inout[1], err[1]);
577 /* server_loop has closed inout[1] and err[1]. */
579 #endif /* USE_PIPES */
583 * This is called to fork and execute a command when we have a tty. This
584 * will call do_child from the child, and server_loop from the parent after
585 * setting up file descriptors, controlling tty, updating wtmp, utmp,
586 * lastlog, and other such operations.
589 do_exec_pty(Session *s, const char *command, struct passwd * pw)
591 int fdout, ptyfd, ttyfd, ptymaster;
595 fatal("do_exec_pty: no session");
600 do_pam_session(pw->pw_name, s->tty);
604 /* Fork the child. */
605 if ((pid = fork()) == 0) {
606 /* Child. Reinitialize the log because the pid has changed. */
607 log_init(__progname, options.log_level, options.log_facility, log_stderr);
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. */
667 session_set_fds(s, ptyfd, fdout, -1);
669 server_loop(pid, ptyfd, fdout, -1);
670 /* server_loop _has_ closed ptyfd and fdout. */
671 session_pty_cleanup(s);
676 get_remote_name_or_ip(void)
678 static const char *remote = "";
680 remote = get_canonical_hostname();
681 if (utmp_len == 0 || strlen(remote) > utmp_len)
682 remote = get_remote_ipaddr();
686 /* administrative, login(1)-like work */
688 do_login(Session *s, const char *command)
693 char hostname[MAXHOSTNAMELEN];
695 struct sockaddr_storage from;
697 time_t last_login_time;
698 struct passwd * pw = s->pw;
699 pid_t pid = getpid();
702 * Get IP address of client. If the connection is not a socket, let
703 * the address be 0.0.0.0.
705 memset(&from, 0, sizeof(from));
706 if (packet_connection_is_on_socket()) {
707 fromlen = sizeof(from);
708 if (getpeername(packet_get_connection_in(),
709 (struct sockaddr *) & from, &fromlen) < 0) {
710 debug("getpeername: %.100s", strerror(errno));
715 /* Get the time and hostname when the user last logged in. */
717 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
718 hostname, sizeof(hostname));
720 /* Record that there was a login on that tty from the remote host. */
721 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
722 get_remote_name_or_ip(), (struct sockaddr *)&from);
726 * If password change is needed, do it now.
727 * This needs to occur before the ~/.hushlogin check.
729 if (pam_password_change_required()) {
730 print_pam_messages();
735 /* Done if .hushlogin exists or a command given. */
738 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
739 #ifdef HAVE_LOGIN_CAP
740 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
742 if (stat(buf, &st) >= 0)
747 if (!pam_password_change_required())
748 print_pam_messages();
750 #ifdef WITH_AIXAUTHENTICATE
751 if (aixloginmsg && *aixloginmsg)
752 printf("%s\n", aixloginmsg);
753 #endif /* WITH_AIXAUTHENTICATE */
755 if (last_login_time != 0) {
756 time_string = ctime(&last_login_time);
757 if (strchr(time_string, '\n'))
758 *strchr(time_string, '\n') = 0;
759 if (strcmp(hostname, "") == 0)
760 printf("Last login: %s\r\n", time_string);
762 printf("Last login: %s from %s\r\n", time_string, hostname);
764 if (options.print_motd) {
765 #ifdef HAVE_LOGIN_CAP
766 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
769 f = fopen("/etc/motd", "r");
772 while (fgets(buf, sizeof(buf), f))
780 * Sets the value of the given variable in the environment. If the variable
781 * already exists, its value is overriden.
784 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
787 unsigned int i, namelen;
791 * Find the slot where the value should be stored. If the variable
792 * already exists, we reuse the slot; otherwise we append a new slot
793 * at the end of the array, expanding if necessary.
796 namelen = strlen(name);
797 for (i = 0; env[i]; i++)
798 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
801 /* Reuse the slot. */
804 /* New variable. Expand if necessary. */
805 if (i >= (*envsizep) - 1) {
807 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
809 /* Need to set the NULL pointer at end of array beyond the new slot. */
813 /* Allocate space and format the variable in the appropriate slot. */
814 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
815 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
819 * Reads environment variables from the given file and adds/overrides them
820 * into the environment. If the file does not exist, this does nothing.
821 * Otherwise, it must consist of empty lines, comments (line starts with '#')
822 * and assignments of the form name=value. No other forms are allowed.
825 read_environment_file(char ***env, unsigned int *envsize,
826 const char *filename)
832 f = fopen(filename, "r");
836 while (fgets(buf, sizeof(buf), f)) {
837 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
839 if (!*cp || *cp == '#' || *cp == '\n')
841 if (strchr(cp, '\n'))
842 *strchr(cp, '\n') = '\0';
843 value = strchr(cp, '=');
845 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
849 * Replace the equals sign by nul, and advance value to
854 child_set_env(env, envsize, cp, value);
861 * Sets any environment variables which have been specified by PAM
863 void do_pam_environment(char ***env, int *envsize)
865 char *equals, var_name[512], var_val[512];
869 if ((pam_env = fetch_pam_environment()) == NULL)
872 for(i = 0; pam_env[i] != NULL; i++) {
873 if ((equals = strstr(pam_env[i], "=")) == NULL)
876 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
877 memset(var_name, '\0', sizeof(var_name));
878 memset(var_val, '\0', sizeof(var_val));
880 strncpy(var_name, pam_env[i], equals - pam_env[i]);
881 strcpy(var_val, equals + 1);
883 debug3("PAM environment: %s=%s", var_name, var_val);
885 child_set_env(env, envsize, var_name, var_val);
893 void copy_environment(char ***env, int *envsize)
895 char *equals, var_name[512], var_val[512];
898 for(i = 0; environ[i] != NULL; i++) {
899 if ((equals = strstr(environ[i], "=")) == NULL)
902 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
903 memset(var_name, '\0', sizeof(var_name));
904 memset(var_val, '\0', sizeof(var_val));
906 strncpy(var_name, environ[i], equals - environ[i]);
907 strcpy(var_val, equals + 1);
909 debug3("Copy environment: %s=%s", var_name, var_val);
911 child_set_env(env, envsize, var_name, var_val);
917 #if defined(HAVE_GETUSERATTR)
919 * AIX-specific login initialisation
921 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
926 getrlimit(resource, &rlim);
929 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
931 rlim.rlim_cur = RLIM_INFINITY;
932 } else if (slim != 0) {
933 /* See the wackiness below */
934 if (rlim.rlim_cur == slim * mult)
937 rlim.rlim_cur = slim * mult;
942 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
944 rlim.rlim_max = RLIM_INFINITY;
945 } else if (hlim != 0) {
946 rlim.rlim_max = hlim * mult;
951 * XXX For cpu and fsize the soft limit is set to the hard limit
952 * if the hard limit is left at its default value and the soft limit
953 * is changed from its default value, either by requesting it
954 * (slim == 0) or by setting it to the current default. At least
955 * that's how rlogind does it. If you're confused you're not alone.
956 * Bug or feature? AIX 4.3.1.2
958 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
959 && hlim == 0 && slim != 0)
960 rlim.rlim_max = rlim.rlim_cur;
961 /* A specified hard limit limits the soft limit */
962 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
963 rlim.rlim_cur = rlim.rlim_max;
964 /* A soft limit can increase a hard limit */
965 else if (rlim.rlim_cur > rlim.rlim_max)
966 rlim.rlim_max = rlim.rlim_cur;
968 if (setrlimit(resource, &rlim) != 0)
969 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
972 void set_limits_from_userattr(char *user)
977 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
978 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
979 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
980 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
981 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
982 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
983 #if defined(S_UNOFILE)
984 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
987 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
988 /* Convert decimal to octal */
989 (void) snprintf(buf, sizeof(buf), "%d", mask);
990 if (sscanf(buf, "%o", &mask) == 1)
994 #endif /* defined(HAVE_GETUSERATTR) */
997 * Performs common processing for the child, such as setting up the
998 * environment, closing extra file descriptors, setting the user and group
999 * ids, and executing the command or shell.
1002 do_child(const char *command, struct passwd * pw, const char *term,
1003 const char *display, const char *auth_proto,
1004 const char *auth_data, const char *ttyname)
1006 const char *shell, *hostname = NULL, *cp = NULL;
1010 unsigned int envsize, i;
1012 extern char **environ;
1015 #ifdef WITH_IRIX_PROJECT
1017 #endif /* WITH_IRIX_PROJECT */
1018 #ifdef WITH_IRIX_JOBS
1021 #ifdef WITH_IRIX_ARRAY
1023 #endif /* WITH_IRIX_ARRAY */
1024 #endif /* WITH_IRIX_JOBS */
1027 /* login(1) is only called if we execute the login shell */
1028 if (options.use_login && command != NULL)
1029 options.use_login = 0;
1031 #ifndef USE_PAM /* pam_nologin handles this */
1032 if (!options.use_login) {
1033 # ifdef HAVE_LOGIN_CAP
1034 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1035 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1036 _PATH_NOLOGIN), "r");
1037 # else /* HAVE_LOGIN_CAP */
1039 f = fopen(_PATH_NOLOGIN, "r");
1040 # endif /* HAVE_LOGIN_CAP */
1042 /* /etc/nologin exists. Print its contents and exit. */
1043 while (fgets(buf, sizeof(buf), f))
1049 #endif /* USE_PAM */
1051 /* Set login name, uid, gid, and groups. */
1052 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1053 switch, so we let login(1) to this for us. */
1054 if (!options.use_login) {
1056 extern char **saved_argv;
1057 extern int saved_argc;
1058 char *host = get_canonical_hostname ();
1060 if (sia_become_user(NULL, saved_argc, saved_argv, host,
1061 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
1063 perror("sia_become_user");
1066 if (setreuid(geteuid(), geteuid()) < 0) {
1070 #else /* HAVE_OSF_SIA */
1074 if (getuid() == 0 || geteuid() == 0) {
1076 # ifdef HAVE_GETUSERATTR
1077 set_limits_from_userattr(pw->pw_name);
1078 # endif /* HAVE_GETUSERATTR */
1079 # ifdef HAVE_LOGIN_CAP
1080 if (setusercontext(lc, pw, pw->pw_uid,
1081 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1082 perror("unable to set user context");
1085 # else /* HAVE_LOGIN_CAP */
1086 if (setlogin(pw->pw_name) < 0)
1087 error("setlogin failed: %s", strerror(errno));
1088 if (setgid(pw->pw_gid) < 0) {
1092 /* Initialize the group list. */
1093 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1094 perror("initgroups");
1098 # ifdef WITH_IRIX_JOBS
1099 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1101 fatal("Failed to create job container: %.100s",
1104 # endif /* WITH_IRIX_JOBS */
1105 # ifdef WITH_IRIX_ARRAY
1106 /* initialize array session */
1108 if (newarraysess() != 0)
1109 fatal("Failed to set up new array session: %.100s",
1112 # endif /* WITH_IRIX_ARRAY */
1113 # ifdef WITH_IRIX_PROJECT
1114 /* initialize irix project info */
1115 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1116 debug("Failed to get project id, using projid 0");
1119 if (setprid(projid))
1120 fatal("Failed to initialize project %d for %s: %.100s",
1121 (int)projid, pw->pw_name, strerror(errno));
1122 # endif /* WITH_IRIX_PROJECT */
1123 #ifdef WITH_IRIX_AUDIT
1124 if (sysconf(_SC_AUDIT)) {
1125 debug("Setting sat id to %d", (int) pw->pw_uid);
1126 if (satsetid(pw->pw_uid))
1127 debug("error setting satid: %.100s", strerror(errno));
1129 #endif /* WITH_IRIX_AUDIT */
1131 /* Permanently switch to the desired uid. */
1132 permanently_set_uid(pw->pw_uid);
1133 # endif /* HAVE_LOGIN_CAP */
1135 #endif /* HAVE_OSF_SIA */
1140 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1141 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1144 * Get the shell from the password data. An empty shell field is
1145 * legal, and means /bin/sh.
1147 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1148 #ifdef HAVE_LOGIN_CAP
1149 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1153 /* Try to get AFS tokens for the local cell. */
1157 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1158 krb_afslog(cell, 0);
1164 /* Initialize the environment. */
1166 env = xmalloc(envsize * sizeof(char *));
1171 * The Windows environment contains some setting which are
1172 * important for a running system. They must not be dropped.
1174 copy_environment(&env, &envsize);
1177 if (!options.use_login) {
1178 /* Set basic environment. */
1179 child_set_env(&env, &envsize, "USER", pw->pw_name);
1180 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1181 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1182 #ifdef HAVE_LOGIN_CAP
1183 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1184 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1185 #else /* HAVE_LOGIN_CAP */
1186 # ifndef HAVE_CYGWIN
1188 * There's no standard path on Windows. The path contains
1189 * important components pointing to the system directories,
1190 * needed for loading shared libraries. So the path better
1191 * remains intact here.
1193 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1194 # endif /* HAVE_CYGWIN */
1195 #endif /* HAVE_LOGIN_CAP */
1197 snprintf(buf, sizeof buf, "%.200s/%.50s",
1198 _PATH_MAILDIR, pw->pw_name);
1199 child_set_env(&env, &envsize, "MAIL", buf);
1201 /* Normal systems set SHELL by default. */
1202 child_set_env(&env, &envsize, "SHELL", shell);
1205 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1207 /* Set custom environment options from RSA authentication. */
1208 while (custom_environment) {
1209 struct envstring *ce = custom_environment;
1212 for (i = 0; s[i] != '=' && s[i]; i++);
1215 child_set_env(&env, &envsize, s, s + i + 1);
1217 custom_environment = ce->next;
1222 snprintf(buf, sizeof buf, "%.50s %d %d",
1223 get_remote_ipaddr(), get_remote_port(), get_local_port());
1224 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1227 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1229 child_set_env(&env, &envsize, "TERM", term);
1231 child_set_env(&env, &envsize, "DISPLAY", display);
1232 if (original_command)
1233 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1237 if ((cp = getenv("AUTHSTATE")) != NULL)
1238 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1239 if ((cp = getenv("KRB5CCNAME")) != NULL)
1240 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1241 read_environment_file(&env, &envsize, "/etc/environment");
1246 extern char *ticket;
1249 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1254 /* Pull in any environment variables that may have been set by PAM. */
1255 do_pam_environment(&env, &envsize);
1256 #endif /* USE_PAM */
1259 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1260 if (auth_get_socket_name() != NULL)
1261 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1262 auth_get_socket_name());
1264 /* read $HOME/.ssh/environment. */
1265 if (!options.use_login) {
1266 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1268 read_environment_file(&env, &envsize, buf);
1271 /* dump the environment */
1272 fprintf(stderr, "Environment:\n");
1273 for (i = 0; env[i]; i++)
1274 fprintf(stderr, " %.200s\n", env[i]);
1276 /* we have to stash the hostname before we close our socket. */
1277 if (options.use_login)
1278 hostname = get_remote_name_or_ip();
1280 * Close the connection descriptors; note that this is the child, and
1281 * the server will still have the socket open, and it is important
1282 * that we do not shutdown it. Note that the descriptors cannot be
1283 * closed before building the environment, as we call
1284 * get_remote_ipaddr there.
1286 if (packet_get_connection_in() == packet_get_connection_out())
1287 close(packet_get_connection_in());
1289 close(packet_get_connection_in());
1290 close(packet_get_connection_out());
1293 * Close all descriptors related to channels. They will still remain
1294 * open in the parent.
1296 /* XXX better use close-on-exec? -markus */
1297 channel_close_all();
1300 * Close any extra file descriptors. Note that there may still be
1301 * descriptors left by system functions. They will be closed later.
1306 * Close any extra open file descriptors so that we don\'t have them
1307 * hanging around in clients. Note that we want to do this after
1308 * initgroups, because at least on Solaris 2.3 it leaves file
1311 for (i = 3; i < 64; i++)
1314 /* Change current directory to the user\'s home directory. */
1315 if (chdir(pw->pw_dir) < 0) {
1316 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1317 pw->pw_dir, strerror(errno));
1318 #ifdef HAVE_LOGIN_CAP
1319 if (login_getcapbool(lc, "requirehome", 0))
1325 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1326 * xauth are run in the proper environment.
1331 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1334 if (!options.use_login) {
1335 if (stat(SSH_USER_RC, &st) >= 0) {
1337 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1339 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1341 if (auth_proto != NULL && auth_data != NULL)
1342 fprintf(f, "%s %s\n", auth_proto, auth_data);
1345 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1346 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1348 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1350 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1352 if (auth_proto != NULL && auth_data != NULL)
1353 fprintf(f, "%s %s\n", auth_proto, auth_data);
1356 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1357 } else if (options.xauth_location != NULL) {
1358 /* Add authority data to .Xauthority if appropriate. */
1359 if (auth_proto != NULL && auth_data != NULL) {
1360 char *screen = strchr(display, ':');
1363 "Running %.100s add %.100s %.100s %.100s\n",
1364 options.xauth_location, display,
1365 auth_proto, auth_data);
1366 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1369 "Adding %.*s/unix%s %s %s\n",
1370 (int)(screen-display), display,
1371 screen, auth_proto, auth_data);
1374 snprintf(cmd, sizeof cmd, "%s -q -",
1375 options.xauth_location);
1376 f = popen(cmd, "w");
1378 fprintf(f, "add %s %s %s\n", display,
1379 auth_proto, auth_data);
1380 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1382 fprintf(f, "add %.*s/unix%s %s %s\n",
1383 (int)(screen-display), display,
1384 screen, auth_proto, auth_data);
1388 fprintf(stderr, "Could not run %s\n",
1393 /* Get the last component of the shell name. */
1394 cp = strrchr(shell, '/');
1401 * If we have no command, execute the shell. In this case, the shell
1402 * name to be passed in argv[0] is preceded by '-' to indicate that
1403 * this is a login shell.
1406 if (!options.use_login) {
1410 * Check for mail if we have a tty and it was enabled
1411 * in server options.
1413 if (ttyname && options.check_mail) {
1415 struct stat mailstat;
1416 mailbox = getenv("MAIL");
1417 if (mailbox != NULL) {
1418 if (stat(mailbox, &mailstat) != 0 ||
1419 mailstat.st_size == 0)
1420 printf("No mail.\n");
1421 else if (mailstat.st_mtime < mailstat.st_atime)
1422 printf("You have mail.\n");
1424 printf("You have new mail.\n");
1427 /* Start the shell. Set initial character to '-'. */
1429 strncpy(buf + 1, cp, sizeof(buf) - 1);
1430 buf[sizeof(buf) - 1] = 0;
1432 /* Execute the shell. */
1435 execve(shell, argv, env);
1437 /* Executing the shell failed. */
1442 /* Launch login(1). */
1444 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1445 "-p", "-f", "--", pw->pw_name, NULL);
1447 /* Login couldn't be executed, die. */
1454 * Execute the command using the user's shell. This uses the -c
1455 * option to execute the command.
1457 argv[0] = (char *) cp;
1459 argv[2] = (char *) command;
1461 execve(shell, argv, env);
1470 static int did_init = 0;
1472 debug("session_new: init");
1473 for(i = 0; i < MAX_SESSIONS; i++) {
1474 sessions[i].used = 0;
1475 sessions[i].self = i;
1479 for(i = 0; i < MAX_SESSIONS; i++) {
1480 Session *s = &sessions[i];
1491 s->auth_data = NULL;
1492 s->auth_proto = NULL;
1495 debug("session_new: session %d", i);
1506 for(i = 0; i < MAX_SESSIONS; i++) {
1507 Session *s = &sessions[i];
1508 debug("dump: used %d session %d %p channel %d pid %d",
1518 session_open(int chanid)
1520 Session *s = session_new();
1521 debug("session_open: channel %d", chanid);
1523 error("no more sessions");
1526 s->pw = auth_get_user();
1528 fatal("no user for session %i", s->self);
1529 debug("session_open: session %d: link with channel %d", s->self, chanid);
1535 session_by_channel(int id)
1538 for(i = 0; i < MAX_SESSIONS; i++) {
1539 Session *s = &sessions[i];
1540 if (s->used && s->chanid == id) {
1541 debug("session_by_channel: session %d channel %d", i, id);
1545 debug("session_by_channel: unknown channel %d", id);
1551 session_by_pid(pid_t pid)
1554 debug("session_by_pid: pid %d", pid);
1555 for(i = 0; i < MAX_SESSIONS; i++) {
1556 Session *s = &sessions[i];
1557 if (s->used && s->pid == pid)
1560 error("session_by_pid: unknown pid %d", pid);
1566 session_window_change_req(Session *s)
1568 s->col = packet_get_int();
1569 s->row = packet_get_int();
1570 s->xpixel = packet_get_int();
1571 s->ypixel = packet_get_int();
1573 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1578 session_pty_req(Session *s)
1581 char *term_modes; /* encoded terminal modes */
1587 s->term = packet_get_string(&len);
1588 s->col = packet_get_int();
1589 s->row = packet_get_int();
1590 s->xpixel = packet_get_int();
1591 s->ypixel = packet_get_int();
1592 term_modes = packet_get_string(&len);
1595 if (strcmp(s->term, "") == 0) {
1599 /* Allocate a pty and open it. */
1600 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1605 error("session_pty_req: session %d alloc failed", s->self);
1609 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1611 * Add a cleanup function to clear the utmp entry and record logout
1612 * time in case we call fatal() (e.g., the connection gets closed).
1614 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1615 pty_setowner(s->pw, s->tty);
1616 /* Get window size from the packet. */
1617 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1619 session_proctitle(s);
1621 /* XXX parse and set terminal modes */
1627 session_subsystem_req(Session *s)
1631 char *subsys = packet_get_string(&len);
1635 log("subsystem request for %s", subsys);
1637 for (i = 0; i < options.num_subsystems; i++) {
1638 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1639 debug("subsystem: exec() %s", options.subsystem_command[i]);
1640 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1646 log("subsystem request for %s failed, subsystem not found", subsys);
1653 session_x11_req(Session *s)
1656 if (no_x11_forwarding_flag) {
1657 debug("X11 forwarding disabled in user configuration file.");
1660 if (!options.x11_forwarding) {
1661 debug("X11 forwarding disabled in server configuration file.");
1664 if (xauthfile != NULL) {
1665 debug("X11 fwd already started.");
1669 debug("Received request for X11 forwarding with auth spoofing.");
1670 if (s->display != NULL)
1671 packet_disconnect("Protocol error: X11 display already set.");
1673 s->single_connection = packet_get_char();
1674 s->auth_proto = packet_get_string(NULL);
1675 s->auth_data = packet_get_string(NULL);
1676 s->screen = packet_get_int();
1679 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1680 if (s->display == NULL) {
1681 xfree(s->auth_proto);
1682 xfree(s->auth_data);
1685 xauthfile = xmalloc(MAXPATHLEN);
1686 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1687 temporarily_use_uid(s->pw->pw_uid);
1688 if (mkdtemp(xauthfile) == NULL) {
1690 error("private X11 dir: mkdtemp %s failed: %s",
1691 xauthfile, strerror(errno));
1694 xfree(s->auth_proto);
1695 xfree(s->auth_data);
1696 /* XXXX remove listening channels */
1699 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1700 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1704 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1709 session_shell_req(Session *s)
1711 /* if forced_command == NULL, the shell is execed */
1712 char *shell = forced_command;
1716 do_exec_no_pty(s, shell, s->pw);
1718 do_exec_pty(s, shell, s->pw);
1723 session_exec_req(Session *s)
1726 char *command = packet_get_string(&len);
1728 if (forced_command) {
1729 original_command = command;
1730 command = forced_command;
1731 debug("Forced command '%.500s'", forced_command);
1735 do_exec_no_pty(s, command, s->pw);
1737 do_exec_pty(s, command, s->pw);
1738 if (forced_command == NULL)
1744 session_auth_agent_req(Session *s)
1746 static int called = 0;
1752 return auth_input_request_forwarding(s->pw);
1757 session_input_channel_req(int id, void *arg)
1766 rtype = packet_get_string(&len);
1767 reply = packet_get_char();
1769 s = session_by_channel(id);
1771 fatal("session_input_channel_req: channel %d: no session", id);
1772 c = channel_lookup(id);
1774 fatal("session_input_channel_req: channel %d: bad channel", id);
1776 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1777 s->self, id, rtype, reply);
1780 * a session is in LARVAL state until a shell
1781 * or programm is executed
1783 if (c->type == SSH_CHANNEL_LARVAL) {
1784 if (strcmp(rtype, "shell") == 0) {
1785 success = session_shell_req(s);
1786 } else if (strcmp(rtype, "exec") == 0) {
1787 success = session_exec_req(s);
1788 } else if (strcmp(rtype, "pty-req") == 0) {
1789 success = session_pty_req(s);
1790 } else if (strcmp(rtype, "x11-req") == 0) {
1791 success = session_x11_req(s);
1792 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1793 success = session_auth_agent_req(s);
1794 } else if (strcmp(rtype, "subsystem") == 0) {
1795 success = session_subsystem_req(s);
1798 if (strcmp(rtype, "window-change") == 0) {
1799 success = session_window_change_req(s);
1803 packet_start(success ?
1804 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1805 packet_put_int(c->remote_id);
1812 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1815 fatal("session_set_fds: called for proto != 2.0");
1817 * now that have a child and a pipe to the child,
1818 * we can activate our channel and register the fd's
1820 if (s->chanid == -1)
1821 fatal("no channel for session %d", s->self);
1822 channel_set_fds(s->chanid,
1824 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1829 session_pty_cleanup(Session *s)
1831 if (s == NULL || s->ttyfd == -1)
1834 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1836 /* Cancel the cleanup function. */
1837 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1839 /* Record that the user has logged out. */
1840 record_logout(s->pid, s->tty);
1842 /* Release the pseudo-tty. */
1843 pty_release(s->tty);
1846 * Close the server side of the socket pairs. We must do this after
1847 * the pty cleanup, so that another process doesn't get this pty
1848 * while we're still cleaning up.
1850 if (close(s->ptymaster) < 0)
1851 error("close(s->ptymaster): %s", strerror(errno));
1855 session_exit_message(Session *s, int status)
1859 fatal("session_close: no session");
1860 c = channel_lookup(s->chanid);
1862 fatal("session_close: session %d: no channel %d",
1863 s->self, s->chanid);
1864 debug("session_exit_message: session %d channel %d pid %d",
1865 s->self, s->chanid, s->pid);
1867 if (WIFEXITED(status)) {
1868 channel_request_start(s->chanid,
1870 packet_put_int(WEXITSTATUS(status));
1872 } else if (WIFSIGNALED(status)) {
1873 channel_request_start(s->chanid,
1875 packet_put_int(WTERMSIG(status));
1877 packet_put_char(WCOREDUMP(status));
1878 #else /* WCOREDUMP */
1880 #endif /* WCOREDUMP */
1881 packet_put_cstring("");
1882 packet_put_cstring("");
1885 /* Some weird exit cause. Just exit. */
1886 packet_disconnect("wait returned status %04x.", status);
1889 /* disconnect channel */
1890 debug("session_exit_message: release channel %d", s->chanid);
1891 channel_cancel_cleanup(s->chanid);
1893 * emulate a write failure with 'chan_write_failed', nobody will be
1894 * interested in data we write.
1895 * Note that we must not call 'chan_read_failed', since there could
1896 * be some more data waiting in the pipe.
1897 * djm - This is no longer true as we have allowed one pass through
1898 * the select loop before killing the connection
1900 if (c->ostate != CHAN_OUTPUT_CLOSED)
1901 chan_write_failed(c);
1902 if (c->istate != CHAN_INPUT_CLOSED)
1903 chan_read_failed(c);
1908 session_free(Session *s)
1910 debug("session_free: session %d pid %d", s->self, s->pid);
1916 xfree(s->auth_data);
1918 xfree(s->auth_proto);
1923 session_close(Session *s)
1925 session_pty_cleanup(s);
1927 session_proctitle(s);
1931 session_close_by_pid(pid_t pid, int status)
1933 Session *s = session_by_pid(pid);
1935 debug("session_close_by_pid: no session for pid %d", s->pid);
1938 if (s->chanid != -1)
1939 session_exit_message(s, status);
1944 * this is called when a channel dies before
1945 * the session 'child' itself dies
1948 session_close_by_channel(int id, void *arg)
1950 Session *s = session_by_channel(id);
1952 debug("session_close_by_channel: no session for channel %d", id);
1955 /* disconnect channel */
1956 channel_cancel_cleanup(s->chanid);
1959 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1961 /* close session immediately */
1964 /* notify child, delay session cleanup */
1966 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1967 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1968 error("session_close_by_channel: kill %d: %s",
1969 s->pid, strerror(errno));
1974 session_tty_list(void)
1976 static char buf[1024];
1979 for(i = 0; i < MAX_SESSIONS; i++) {
1980 Session *s = &sessions[i];
1981 if (s->used && s->ttyfd != -1) {
1983 strlcat(buf, ",", sizeof buf);
1984 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1988 strlcpy(buf, "notty", sizeof buf);
1993 session_proctitle(Session *s)
1996 error("no user for session %d", s->self);
1998 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2002 do_authenticated2(void)
2004 #ifdef HAVE_LOGIN_CAP
2009 * Cancel the alarm we set to limit the time taken for
2013 if (startup_pipe != -1) {
2014 close(startup_pipe);
2017 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
2018 pw = auth_get_user();
2019 if ((lc = login_getclass(pw->pw_class)) == NULL) {
2020 error("unable to get login class");
2026 xauthfile_cleanup_proc(NULL);