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.52 2001/02/03 10:08:37 markus Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
60 #ifdef WITH_IRIX_PROJECT
62 #endif /* WITH_IRIX_PROJECT */
64 #include <sys/resource.h>
66 #ifdef WITH_IRIX_AUDIT
68 #endif /* WITH_IRIX_AUDIT */
70 #if defined(HAVE_USERSEC_H)
81 #include <sys/cygwin.h>
82 #define is_winnt (GetVersion() < 0x80000000)
86 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
87 # define S_UFSIZE_HARD S_UFSIZE "_hard"
88 # define S_UCPU_HARD S_UCPU "_hard"
89 # define S_UDATA_HARD S_UDATA "_hard"
90 # define S_USTACK_HARD S_USTACK "_hard"
91 # define S_URSS_HARD S_URSS "_hard"
92 # define S_UCORE_HARD S_UCORE "_hard"
93 # define S_UNOFILE_HARD S_UNOFILE "_hard"
97 #include <login_cap.h>
103 typedef struct Session Session;
112 int ptyfd, ttyfd, ptymaster;
113 int row, col, xpixel, ypixel;
120 int single_connection;
127 Session *session_new(void);
128 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
129 void session_pty_cleanup(Session *s);
130 void session_proctitle(Session *s);
131 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
132 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
133 void do_login(Session *s, const char *command);
136 do_child(const char *command, struct passwd * pw, const char *term,
137 const char *display, const char *auth_proto,
138 const char *auth_data, const char *ttyname);
141 extern ServerOptions options;
142 extern char *__progname;
143 extern int log_stderr;
144 extern int debug_flag;
145 extern u_int utmp_len;
147 extern int startup_pipe;
149 /* Local Xauthority file. */
150 static char *xauthfile;
152 /* original command from peer. */
153 char *original_command = NULL;
156 #define MAX_SESSIONS 10
157 Session sessions[MAX_SESSIONS];
159 #ifdef WITH_AIXAUTHENTICATE
160 /* AIX's lastlogin message, set in auth1.c */
162 #endif /* WITH_AIXAUTHENTICATE */
164 #ifdef HAVE_LOGIN_CAP
165 static login_cap_t *lc;
169 * Remove local Xauthority file.
172 xauthfile_cleanup_proc(void *ignore)
174 debug("xauthfile_cleanup_proc called");
176 if (xauthfile != NULL) {
179 p = strrchr(xauthfile, '/');
190 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
191 * dropped connection).
194 pty_cleanup_proc(void *session)
198 fatal("pty_cleanup_proc: no session");
199 debug("pty_cleanup_proc: %s", s->tty);
202 /* Record that the user has logged out. */
203 record_logout(s->pid, s->tty);
206 /* Release the pseudo-tty. */
211 * Prepares for an interactive session. This is called after the user has
212 * been successfully authenticated. During this message exchange, pseudo
213 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
214 * are requested, etc.
217 do_authenticated(struct passwd * pw)
221 int compression_level = 0, enable_compression_after_reply = 0;
226 u_int proto_len, data_len, dlen;
229 * Cancel the alarm we set to limit the time taken for
233 if (startup_pipe != -1) {
239 * Inform the channel mechanism that we are the server side and that
240 * the client may request to connect to any port at all. (The user
241 * could do it anyway, and we wouldn\'t know what is permitted except
242 * by the client telling us, so we can equally well trust the client
243 * not to request anything bogus.)
245 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
246 channel_permit_all_opens();
251 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
252 if ((lc = login_getclass(pw->pw_class)) == NULL) {
253 error("unable to get login class");
259 * We stay in this loop until the client requests to execute a shell
265 /* Get a packet from the client. */
266 type = packet_read(&plen);
268 /* Process the packet. */
270 case SSH_CMSG_REQUEST_COMPRESSION:
271 packet_integrity_check(plen, 4, type);
272 compression_level = packet_get_int();
273 if (compression_level < 1 || compression_level > 9) {
274 packet_send_debug("Received illegal compression level %d.",
278 /* Enable compression after we have responded with SUCCESS. */
279 enable_compression_after_reply = 1;
283 case SSH_CMSG_REQUEST_PTY:
285 debug("Allocating a pty not permitted for this authentication.");
289 packet_disconnect("Protocol error: you already have a pty.");
291 debug("Allocating pty.");
293 /* Allocate a pty and open it. */
294 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
296 error("Failed to allocate pty.");
299 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
300 pty_setowner(pw, s->tty);
302 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
303 s->term = packet_get_string(&dlen);
304 packet_integrity_check(dlen, strlen(s->term), type);
305 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
306 /* Remaining bytes */
307 n_bytes = plen - (4 + dlen + 4 * 4);
309 if (strcmp(s->term, "") == 0) {
313 /* Get window size from the packet. */
314 s->row = packet_get_int();
315 s->col = packet_get_int();
316 s->xpixel = packet_get_int();
317 s->ypixel = packet_get_int();
318 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
320 /* Get tty modes from the packet. */
321 tty_parse_modes(s->ttyfd, &n_bytes);
322 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
324 session_proctitle(s);
326 /* Indicate that we now have a pty. */
331 case SSH_CMSG_X11_REQUEST_FORWARDING:
332 if (!options.x11_forwarding) {
333 packet_send_debug("X11 forwarding disabled in server configuration file.");
336 if (!options.xauth_location) {
337 packet_send_debug("No xauth program; cannot forward with spoofing.");
340 if (no_x11_forwarding_flag) {
341 packet_send_debug("X11 forwarding not permitted for this authentication.");
344 debug("Received request for X11 forwarding with auth spoofing.");
345 if (s->display != NULL)
346 packet_disconnect("Protocol error: X11 display already set.");
348 s->auth_proto = packet_get_string(&proto_len);
349 s->auth_data = packet_get_string(&data_len);
350 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
352 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
353 s->screen = packet_get_int();
356 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
358 if (s->display == NULL)
361 /* Setup to always have a local .Xauthority. */
362 xauthfile = xmalloc(MAXPATHLEN);
363 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
364 temporarily_use_uid(pw->pw_uid);
365 if (mkdtemp(xauthfile) == NULL) {
367 error("private X11 dir: mkdtemp %s failed: %s",
368 xauthfile, strerror(errno));
371 /* XXXX remove listening channels */
374 strlcat(xauthfile, "/cookies", MAXPATHLEN);
375 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
379 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
383 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
384 if (no_agent_forwarding_flag || compat13) {
385 debug("Authentication agent forwarding not permitted for this authentication.");
388 debug("Received authentication agent forwarding request.");
389 success = auth_input_request_forwarding(pw);
392 case SSH_CMSG_PORT_FORWARD_REQUEST:
393 if (no_port_forwarding_flag) {
394 debug("Port forwarding not permitted for this authentication.");
397 if (!options.allow_tcp_forwarding) {
398 debug("Port forwarding not permitted.");
401 debug("Received TCP/IP port forwarding request.");
402 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
406 case SSH_CMSG_MAX_PACKET_SIZE:
407 if (packet_set_maxsize(packet_get_int()) > 0)
411 case SSH_CMSG_EXEC_SHELL:
412 case SSH_CMSG_EXEC_CMD:
413 if (type == SSH_CMSG_EXEC_CMD) {
414 command = packet_get_string(&dlen);
415 debug("Exec command '%.500s'", command);
416 packet_integrity_check(plen, 4 + dlen, type);
419 packet_integrity_check(plen, 0, type);
421 if (forced_command != NULL) {
422 original_command = command;
423 command = forced_command;
424 debug("Forced command '%.500s'", forced_command);
427 do_exec_pty(s, command, pw);
429 do_exec_no_pty(s, command, pw);
433 /* Cleanup user's local Xauthority file. */
435 xauthfile_cleanup_proc(NULL);
440 * Any unknown messages in this phase are ignored,
441 * and a failure message is returned.
443 log("Unknown packet type received after authentication: %d", type);
445 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
449 /* Enable compression now that we have replied if appropriate. */
450 if (enable_compression_after_reply) {
451 enable_compression_after_reply = 0;
452 packet_start_compression(compression_level);
458 * This is called to fork and execute a command when we have no tty. This
459 * will call do_child from the child, and server_loop from the parent after
460 * setting up file descriptors and such.
463 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
468 int pin[2], pout[2], perr[2];
469 /* Allocate pipes for communicating with the program. */
470 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
471 packet_disconnect("Could not create pipes: %.100s",
473 #else /* USE_PIPES */
474 int inout[2], err[2];
475 /* Uses socket pairs to communicate with the program. */
476 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
477 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
478 packet_disconnect("Could not create socket pairs: %.100s",
480 #endif /* USE_PIPES */
482 fatal("do_exec_no_pty: no session");
484 session_proctitle(s);
490 /* Fork the child. */
491 if ((pid = fork()) == 0) {
492 /* Child. Reinitialize the log since the pid has changed. */
493 log_init(__progname, options.log_level, options.log_facility, log_stderr);
495 signal(SIGPIPE, SIG_DFL);
498 * Create a new session and process group since the 4.4BSD
499 * setlogin() affects the entire process group.
502 error("setsid failed: %.100s", strerror(errno));
506 * Redirect stdin. We close the parent side of the socket
507 * pair, and make the child side the standard input.
510 if (dup2(pin[0], 0) < 0)
511 perror("dup2 stdin");
514 /* Redirect stdout. */
516 if (dup2(pout[1], 1) < 0)
517 perror("dup2 stdout");
520 /* Redirect stderr. */
522 if (dup2(perr[1], 2) < 0)
523 perror("dup2 stderr");
525 #else /* USE_PIPES */
527 * Redirect stdin, stdout, and stderr. Stdin and stdout will
528 * use the same socket, as some programs (particularly rdist)
529 * seem to depend on it.
533 if (dup2(inout[0], 0) < 0) /* stdin */
534 perror("dup2 stdin");
535 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
536 perror("dup2 stdout");
537 if (dup2(err[0], 2) < 0) /* stderr */
538 perror("dup2 stderr");
539 #endif /* USE_PIPES */
541 /* Do processing for the child (exec command etc). */
542 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
547 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
550 packet_disconnect("fork failed: %.100s", strerror(errno));
552 /* Set interactive/non-interactive mode. */
553 packet_set_interactive(s->display != NULL);
555 /* We are the parent. Close the child sides of the pipes. */
561 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
563 /* Enter the interactive session. */
564 server_loop(pid, pin[1], pout[0], perr[0]);
565 /* server_loop has closed pin[1], pout[1], and perr[1]. */
567 #else /* USE_PIPES */
568 /* We are the parent. Close the child sides of the socket pairs. */
573 * Enter the interactive session. Note: server_loop must be able to
574 * handle the case that fdin and fdout are the same.
577 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
579 server_loop(pid, inout[1], inout[1], err[1]);
580 /* server_loop has closed inout[1] and err[1]. */
582 #endif /* USE_PIPES */
586 * This is called to fork and execute a command when we have a tty. This
587 * will call do_child from the child, and server_loop from the parent after
588 * setting up file descriptors, controlling tty, updating wtmp, utmp,
589 * lastlog, and other such operations.
592 do_exec_pty(Session *s, const char *command, struct passwd * pw)
594 int fdout, ptyfd, ttyfd, ptymaster;
598 fatal("do_exec_pty: no session");
603 do_pam_session(pw->pw_name, s->tty);
607 /* Fork the child. */
608 if ((pid = fork()) == 0) {
609 /* Child. Reinitialize the log because the pid has changed. */
610 log_init(__progname, options.log_level, options.log_facility, log_stderr);
612 signal(SIGPIPE, SIG_DFL);
614 /* Close the master side of the pseudo tty. */
617 /* Make the pseudo tty our controlling tty. */
618 pty_make_controlling_tty(&ttyfd, s->tty);
620 /* Redirect stdin from the pseudo tty. */
621 if (dup2(ttyfd, fileno(stdin)) < 0)
622 error("dup2 stdin failed: %.100s", strerror(errno));
624 /* Redirect stdout to the pseudo tty. */
625 if (dup2(ttyfd, fileno(stdout)) < 0)
626 error("dup2 stdin failed: %.100s", strerror(errno));
628 /* Redirect stderr to the pseudo tty. */
629 if (dup2(ttyfd, fileno(stderr)) < 0)
630 error("dup2 stdin failed: %.100s", strerror(errno));
632 /* Close the extra descriptor for the pseudo tty. */
635 /* record login, etc. similar to login(1) */
636 if (!(options.use_login && command == NULL))
637 do_login(s, command);
639 /* Do common processing for the child, such as execing the command. */
640 do_child(command, pw, s->term, s->display, s->auth_proto,
641 s->auth_data, s->tty);
646 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
649 packet_disconnect("fork failed: %.100s", strerror(errno));
652 /* Parent. Close the slave side of the pseudo tty. */
656 * Create another descriptor of the pty master side for use as the
657 * standard input. We could use the original descriptor, but this
658 * simplifies code in server_loop. The descriptor is bidirectional.
662 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
664 /* we keep a reference to the pty master */
665 ptymaster = dup(ptyfd);
667 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
668 s->ptymaster = ptymaster;
670 /* Enter interactive session. */
671 packet_set_interactive(1);
673 session_set_fds(s, ptyfd, fdout, -1);
675 server_loop(pid, ptyfd, fdout, -1);
676 /* server_loop _has_ closed ptyfd and fdout. */
677 session_pty_cleanup(s);
682 get_remote_name_or_ip(void)
684 static const char *remote = "";
686 remote = get_canonical_hostname(options.reverse_mapping_check);
687 if (utmp_len == 0 || strlen(remote) > utmp_len)
688 remote = get_remote_ipaddr();
692 /* administrative, login(1)-like work */
694 do_login(Session *s, const char *command)
699 char hostname[MAXHOSTNAMELEN];
701 struct sockaddr_storage from;
703 time_t last_login_time;
704 struct passwd * pw = s->pw;
705 pid_t pid = getpid();
708 * Get IP address of client. If the connection is not a socket, let
709 * the address be 0.0.0.0.
711 memset(&from, 0, sizeof(from));
712 if (packet_connection_is_on_socket()) {
713 fromlen = sizeof(from);
714 if (getpeername(packet_get_connection_in(),
715 (struct sockaddr *) & from, &fromlen) < 0) {
716 debug("getpeername: %.100s", strerror(errno));
721 /* Get the time and hostname when the user last logged in. */
723 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
724 hostname, sizeof(hostname));
726 /* Record that there was a login on that tty from the remote host. */
727 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
728 get_remote_name_or_ip(), (struct sockaddr *)&from);
732 * If password change is needed, do it now.
733 * This needs to occur before the ~/.hushlogin check.
735 if (pam_password_change_required()) {
736 print_pam_messages();
741 /* Done if .hushlogin exists or a command given. */
744 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
745 #ifdef HAVE_LOGIN_CAP
746 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
748 if (stat(buf, &st) >= 0)
753 if (!pam_password_change_required())
754 print_pam_messages();
756 #ifdef WITH_AIXAUTHENTICATE
757 if (aixloginmsg && *aixloginmsg)
758 printf("%s\n", aixloginmsg);
759 #endif /* WITH_AIXAUTHENTICATE */
761 if (last_login_time != 0) {
762 time_string = ctime(&last_login_time);
763 if (strchr(time_string, '\n'))
764 *strchr(time_string, '\n') = 0;
765 if (strcmp(hostname, "") == 0)
766 printf("Last login: %s\r\n", time_string);
768 printf("Last login: %s from %s\r\n", time_string, hostname);
770 if (options.print_motd) {
771 #ifdef HAVE_LOGIN_CAP
772 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
775 f = fopen("/etc/motd", "r");
778 while (fgets(buf, sizeof(buf), f))
786 * Sets the value of the given variable in the environment. If the variable
787 * already exists, its value is overriden.
790 child_set_env(char ***envp, u_int *envsizep, const char *name,
797 * Find the slot where the value should be stored. If the variable
798 * already exists, we reuse the slot; otherwise we append a new slot
799 * at the end of the array, expanding if necessary.
802 namelen = strlen(name);
803 for (i = 0; env[i]; i++)
804 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
807 /* Reuse the slot. */
810 /* New variable. Expand if necessary. */
811 if (i >= (*envsizep) - 1) {
813 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
815 /* Need to set the NULL pointer at end of array beyond the new slot. */
819 /* Allocate space and format the variable in the appropriate slot. */
820 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
821 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
825 * Reads environment variables from the given file and adds/overrides them
826 * into the environment. If the file does not exist, this does nothing.
827 * Otherwise, it must consist of empty lines, comments (line starts with '#')
828 * and assignments of the form name=value. No other forms are allowed.
831 read_environment_file(char ***env, u_int *envsize,
832 const char *filename)
838 f = fopen(filename, "r");
842 while (fgets(buf, sizeof(buf), f)) {
843 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
845 if (!*cp || *cp == '#' || *cp == '\n')
847 if (strchr(cp, '\n'))
848 *strchr(cp, '\n') = '\0';
849 value = strchr(cp, '=');
851 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
855 * Replace the equals sign by nul, and advance value to
860 child_set_env(env, envsize, cp, value);
867 * Sets any environment variables which have been specified by PAM
869 void do_pam_environment(char ***env, int *envsize)
871 char *equals, var_name[512], var_val[512];
875 if ((pam_env = fetch_pam_environment()) == NULL)
878 for(i = 0; pam_env[i] != NULL; i++) {
879 if ((equals = strstr(pam_env[i], "=")) == NULL)
882 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
883 memset(var_name, '\0', sizeof(var_name));
884 memset(var_val, '\0', sizeof(var_val));
886 strncpy(var_name, pam_env[i], equals - pam_env[i]);
887 strcpy(var_val, equals + 1);
889 debug3("PAM environment: %s=%s", var_name, var_val);
891 child_set_env(env, envsize, var_name, var_val);
899 void copy_environment(char ***env, int *envsize)
901 char *equals, var_name[512], var_val[512];
904 for(i = 0; environ[i] != NULL; i++) {
905 if ((equals = strstr(environ[i], "=")) == NULL)
908 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
909 memset(var_name, '\0', sizeof(var_name));
910 memset(var_val, '\0', sizeof(var_val));
912 strncpy(var_name, environ[i], equals - environ[i]);
913 strcpy(var_val, equals + 1);
915 debug3("Copy environment: %s=%s", var_name, var_val);
917 child_set_env(env, envsize, var_name, var_val);
923 #if defined(HAVE_GETUSERATTR)
925 * AIX-specific login initialisation
927 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
932 getrlimit(resource, &rlim);
935 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
937 rlim.rlim_cur = RLIM_INFINITY;
938 } else if (slim != 0) {
939 /* See the wackiness below */
940 if (rlim.rlim_cur == slim * mult)
943 rlim.rlim_cur = slim * mult;
948 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
950 rlim.rlim_max = RLIM_INFINITY;
951 } else if (hlim != 0) {
952 rlim.rlim_max = hlim * mult;
957 * XXX For cpu and fsize the soft limit is set to the hard limit
958 * if the hard limit is left at its default value and the soft limit
959 * is changed from its default value, either by requesting it
960 * (slim == 0) or by setting it to the current default. At least
961 * that's how rlogind does it. If you're confused you're not alone.
962 * Bug or feature? AIX 4.3.1.2
964 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
965 && hlim == 0 && slim != 0)
966 rlim.rlim_max = rlim.rlim_cur;
967 /* A specified hard limit limits the soft limit */
968 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
969 rlim.rlim_cur = rlim.rlim_max;
970 /* A soft limit can increase a hard limit */
971 else if (rlim.rlim_cur > rlim.rlim_max)
972 rlim.rlim_max = rlim.rlim_cur;
974 if (setrlimit(resource, &rlim) != 0)
975 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
978 void set_limits_from_userattr(char *user)
983 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
984 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
985 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
986 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
987 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
988 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
989 #if defined(S_UNOFILE)
990 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
993 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
994 /* Convert decimal to octal */
995 (void) snprintf(buf, sizeof(buf), "%d", mask);
996 if (sscanf(buf, "%o", &mask) == 1)
1000 #endif /* defined(HAVE_GETUSERATTR) */
1003 * Performs common processing for the child, such as setting up the
1004 * environment, closing extra file descriptors, setting the user and group
1005 * ids, and executing the command or shell.
1008 do_child(const char *command, struct passwd * pw, const char *term,
1009 const char *display, const char *auth_proto,
1010 const char *auth_data, const char *ttyname)
1012 const char *shell, *hostname = NULL, *cp = NULL;
1018 extern char **environ;
1021 #ifdef WITH_IRIX_PROJECT
1023 #endif /* WITH_IRIX_PROJECT */
1024 #ifdef WITH_IRIX_JOBS
1027 #ifdef WITH_IRIX_ARRAY
1029 #endif /* WITH_IRIX_ARRAY */
1030 #endif /* WITH_IRIX_JOBS */
1033 /* login(1) is only called if we execute the login shell */
1034 if (options.use_login && command != NULL)
1035 options.use_login = 0;
1037 #ifndef USE_PAM /* pam_nologin handles this */
1038 if (!options.use_login) {
1039 # ifdef HAVE_LOGIN_CAP
1040 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1041 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1042 _PATH_NOLOGIN), "r");
1043 # else /* HAVE_LOGIN_CAP */
1045 f = fopen(_PATH_NOLOGIN, "r");
1046 # endif /* HAVE_LOGIN_CAP */
1048 /* /etc/nologin exists. Print its contents and exit. */
1049 while (fgets(buf, sizeof(buf), f))
1055 #endif /* USE_PAM */
1057 /* Set login name, uid, gid, and groups. */
1058 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1059 switch, so we let login(1) to this for us. */
1060 if (!options.use_login) {
1062 extern char **saved_argv;
1063 extern int saved_argc;
1064 char *host = get_canonical_hostname(options.reverse_mapping_check);
1066 if (sia_become_user(NULL, saved_argc, saved_argv, host,
1067 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
1069 perror("sia_become_user");
1072 if (setreuid(geteuid(), geteuid()) < 0) {
1076 #else /* HAVE_OSF_SIA */
1080 if (getuid() == 0 || geteuid() == 0) {
1082 # ifdef HAVE_GETUSERATTR
1083 set_limits_from_userattr(pw->pw_name);
1084 # endif /* HAVE_GETUSERATTR */
1085 # ifdef HAVE_LOGIN_CAP
1086 if (setusercontext(lc, pw, pw->pw_uid,
1087 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1088 perror("unable to set user context");
1091 # else /* HAVE_LOGIN_CAP */
1092 if (setlogin(pw->pw_name) < 0)
1093 error("setlogin failed: %s", strerror(errno));
1094 if (setgid(pw->pw_gid) < 0) {
1098 /* Initialize the group list. */
1099 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1100 perror("initgroups");
1104 # ifdef WITH_IRIX_JOBS
1105 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1107 fatal("Failed to create job container: %.100s",
1110 # endif /* WITH_IRIX_JOBS */
1111 # ifdef WITH_IRIX_ARRAY
1112 /* initialize array session */
1114 if (newarraysess() != 0)
1115 fatal("Failed to set up new array session: %.100s",
1118 # endif /* WITH_IRIX_ARRAY */
1119 # ifdef WITH_IRIX_PROJECT
1120 /* initialize irix project info */
1121 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1122 debug("Failed to get project id, using projid 0");
1125 if (setprid(projid))
1126 fatal("Failed to initialize project %d for %s: %.100s",
1127 (int)projid, pw->pw_name, strerror(errno));
1128 # endif /* WITH_IRIX_PROJECT */
1129 #ifdef WITH_IRIX_AUDIT
1130 if (sysconf(_SC_AUDIT)) {
1131 debug("Setting sat id to %d", (int) pw->pw_uid);
1132 if (satsetid(pw->pw_uid))
1133 debug("error setting satid: %.100s", strerror(errno));
1135 #endif /* WITH_IRIX_AUDIT */
1137 /* Permanently switch to the desired uid. */
1138 permanently_set_uid(pw->pw_uid);
1139 # endif /* HAVE_LOGIN_CAP */
1141 #endif /* HAVE_OSF_SIA */
1146 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1147 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1150 * Get the shell from the password data. An empty shell field is
1151 * legal, and means /bin/sh.
1153 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1154 #ifdef HAVE_LOGIN_CAP
1155 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1159 /* Try to get AFS tokens for the local cell. */
1163 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1164 krb_afslog(cell, 0);
1170 /* Initialize the environment. */
1172 env = xmalloc(envsize * sizeof(char *));
1177 * The Windows environment contains some setting which are
1178 * important for a running system. They must not be dropped.
1180 copy_environment(&env, &envsize);
1183 if (!options.use_login) {
1184 /* Set basic environment. */
1185 child_set_env(&env, &envsize, "USER", pw->pw_name);
1186 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1187 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1188 #ifdef HAVE_LOGIN_CAP
1189 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1190 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1191 #else /* HAVE_LOGIN_CAP */
1192 # ifndef HAVE_CYGWIN
1194 * There's no standard path on Windows. The path contains
1195 * important components pointing to the system directories,
1196 * needed for loading shared libraries. So the path better
1197 * remains intact here.
1199 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1200 # endif /* HAVE_CYGWIN */
1201 #endif /* HAVE_LOGIN_CAP */
1203 snprintf(buf, sizeof buf, "%.200s/%.50s",
1204 _PATH_MAILDIR, pw->pw_name);
1205 child_set_env(&env, &envsize, "MAIL", buf);
1207 /* Normal systems set SHELL by default. */
1208 child_set_env(&env, &envsize, "SHELL", shell);
1211 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1213 /* Set custom environment options from RSA authentication. */
1214 while (custom_environment) {
1215 struct envstring *ce = custom_environment;
1218 for (i = 0; s[i] != '=' && s[i]; i++);
1221 child_set_env(&env, &envsize, s, s + i + 1);
1223 custom_environment = ce->next;
1228 snprintf(buf, sizeof buf, "%.50s %d %d",
1229 get_remote_ipaddr(), get_remote_port(), get_local_port());
1230 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1233 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1235 child_set_env(&env, &envsize, "TERM", term);
1237 child_set_env(&env, &envsize, "DISPLAY", display);
1238 if (original_command)
1239 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1243 if ((cp = getenv("AUTHSTATE")) != NULL)
1244 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1245 if ((cp = getenv("KRB5CCNAME")) != NULL)
1246 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1247 read_environment_file(&env, &envsize, "/etc/environment");
1252 extern char *ticket;
1255 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1260 /* Pull in any environment variables that may have been set by PAM. */
1261 do_pam_environment(&env, &envsize);
1262 #endif /* USE_PAM */
1265 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1266 if (auth_get_socket_name() != NULL)
1267 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1268 auth_get_socket_name());
1270 /* read $HOME/.ssh/environment. */
1271 if (!options.use_login) {
1272 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1274 read_environment_file(&env, &envsize, buf);
1277 /* dump the environment */
1278 fprintf(stderr, "Environment:\n");
1279 for (i = 0; env[i]; i++)
1280 fprintf(stderr, " %.200s\n", env[i]);
1282 /* we have to stash the hostname before we close our socket. */
1283 if (options.use_login)
1284 hostname = get_remote_name_or_ip();
1286 * Close the connection descriptors; note that this is the child, and
1287 * the server will still have the socket open, and it is important
1288 * that we do not shutdown it. Note that the descriptors cannot be
1289 * closed before building the environment, as we call
1290 * get_remote_ipaddr there.
1292 if (packet_get_connection_in() == packet_get_connection_out())
1293 close(packet_get_connection_in());
1295 close(packet_get_connection_in());
1296 close(packet_get_connection_out());
1299 * Close all descriptors related to channels. They will still remain
1300 * open in the parent.
1302 /* XXX better use close-on-exec? -markus */
1303 channel_close_all();
1306 * Close any extra file descriptors. Note that there may still be
1307 * descriptors left by system functions. They will be closed later.
1312 * Close any extra open file descriptors so that we don\'t have them
1313 * hanging around in clients. Note that we want to do this after
1314 * initgroups, because at least on Solaris 2.3 it leaves file
1317 for (i = 3; i < 64; i++)
1320 /* Change current directory to the user\'s home directory. */
1321 if (chdir(pw->pw_dir) < 0) {
1322 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1323 pw->pw_dir, strerror(errno));
1324 #ifdef HAVE_LOGIN_CAP
1325 if (login_getcapbool(lc, "requirehome", 0))
1331 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1332 * xauth are run in the proper environment.
1337 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1340 if (!options.use_login) {
1341 if (stat(_PATH_SSH_USER_RC, &st) >= 0) {
1343 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, _PATH_SSH_USER_RC);
1345 f = popen(_PATH_BSHELL " " _PATH_SSH_USER_RC, "w");
1347 if (auth_proto != NULL && auth_data != NULL)
1348 fprintf(f, "%s %s\n", auth_proto, auth_data);
1351 fprintf(stderr, "Could not run %s\n", _PATH_SSH_USER_RC);
1352 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1354 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, _PATH_SSH_SYSTEM_RC);
1356 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1358 if (auth_proto != NULL && auth_data != NULL)
1359 fprintf(f, "%s %s\n", auth_proto, auth_data);
1362 fprintf(stderr, "Could not run %s\n", _PATH_SSH_SYSTEM_RC);
1363 } else if (options.xauth_location != NULL) {
1364 /* Add authority data to .Xauthority if appropriate. */
1365 if (auth_proto != NULL && auth_data != NULL) {
1366 char *screen = strchr(display, ':');
1369 "Running %.100s add %.100s %.100s %.100s\n",
1370 options.xauth_location, display,
1371 auth_proto, auth_data);
1372 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1375 "Adding %.*s/unix%s %s %s\n",
1376 (int)(screen-display), display,
1377 screen, auth_proto, auth_data);
1380 snprintf(cmd, sizeof cmd, "%s -q -",
1381 options.xauth_location);
1382 f = popen(cmd, "w");
1384 fprintf(f, "add %s %s %s\n", display,
1385 auth_proto, auth_data);
1386 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1388 fprintf(f, "add %.*s/unix%s %s %s\n",
1389 (int)(screen-display), display,
1390 screen, auth_proto, auth_data);
1394 fprintf(stderr, "Could not run %s\n",
1399 /* Get the last component of the shell name. */
1400 cp = strrchr(shell, '/');
1407 * If we have no command, execute the shell. In this case, the shell
1408 * name to be passed in argv[0] is preceded by '-' to indicate that
1409 * this is a login shell.
1412 if (!options.use_login) {
1416 * Check for mail if we have a tty and it was enabled
1417 * in server options.
1419 if (ttyname && options.check_mail) {
1421 struct stat mailstat;
1422 mailbox = getenv("MAIL");
1423 if (mailbox != NULL) {
1424 if (stat(mailbox, &mailstat) != 0 ||
1425 mailstat.st_size == 0)
1426 printf("No mail.\n");
1427 else if (mailstat.st_mtime < mailstat.st_atime)
1428 printf("You have mail.\n");
1430 printf("You have new mail.\n");
1433 /* Start the shell. Set initial character to '-'. */
1435 strncpy(buf + 1, cp, sizeof(buf) - 1);
1436 buf[sizeof(buf) - 1] = 0;
1438 /* Execute the shell. */
1441 execve(shell, argv, env);
1443 /* Executing the shell failed. */
1448 /* Launch login(1). */
1450 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1451 "-p", "-f", "--", pw->pw_name, NULL);
1453 /* Login couldn't be executed, die. */
1460 * Execute the command using the user's shell. This uses the -c
1461 * option to execute the command.
1463 argv[0] = (char *) cp;
1465 argv[2] = (char *) command;
1467 execve(shell, argv, env);
1476 static int did_init = 0;
1478 debug("session_new: init");
1479 for(i = 0; i < MAX_SESSIONS; i++) {
1480 sessions[i].used = 0;
1481 sessions[i].self = i;
1485 for(i = 0; i < MAX_SESSIONS; i++) {
1486 Session *s = &sessions[i];
1497 s->auth_data = NULL;
1498 s->auth_proto = NULL;
1501 debug("session_new: session %d", i);
1512 for(i = 0; i < MAX_SESSIONS; i++) {
1513 Session *s = &sessions[i];
1514 debug("dump: used %d session %d %p channel %d pid %d",
1524 session_open(int chanid)
1526 Session *s = session_new();
1527 debug("session_open: channel %d", chanid);
1529 error("no more sessions");
1532 s->pw = auth_get_user();
1534 fatal("no user for session %i", s->self);
1535 debug("session_open: session %d: link with channel %d", s->self, chanid);
1541 session_by_channel(int id)
1544 for(i = 0; i < MAX_SESSIONS; i++) {
1545 Session *s = &sessions[i];
1546 if (s->used && s->chanid == id) {
1547 debug("session_by_channel: session %d channel %d", i, id);
1551 debug("session_by_channel: unknown channel %d", id);
1557 session_by_pid(pid_t pid)
1560 debug("session_by_pid: pid %d", pid);
1561 for(i = 0; i < MAX_SESSIONS; i++) {
1562 Session *s = &sessions[i];
1563 if (s->used && s->pid == pid)
1566 error("session_by_pid: unknown pid %d", pid);
1572 session_window_change_req(Session *s)
1574 s->col = packet_get_int();
1575 s->row = packet_get_int();
1576 s->xpixel = packet_get_int();
1577 s->ypixel = packet_get_int();
1579 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1584 session_pty_req(Session *s)
1587 char *term_modes; /* encoded terminal modes */
1593 s->term = packet_get_string(&len);
1594 s->col = packet_get_int();
1595 s->row = packet_get_int();
1596 s->xpixel = packet_get_int();
1597 s->ypixel = packet_get_int();
1598 term_modes = packet_get_string(&len);
1601 if (strcmp(s->term, "") == 0) {
1605 /* Allocate a pty and open it. */
1606 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1611 error("session_pty_req: session %d alloc failed", s->self);
1615 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1617 * Add a cleanup function to clear the utmp entry and record logout
1618 * time in case we call fatal() (e.g., the connection gets closed).
1620 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1621 pty_setowner(s->pw, s->tty);
1622 /* Get window size from the packet. */
1623 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1625 session_proctitle(s);
1627 /* XXX parse and set terminal modes */
1633 session_subsystem_req(Session *s)
1637 char *subsys = packet_get_string(&len);
1641 log("subsystem request for %s", subsys);
1643 for (i = 0; i < options.num_subsystems; i++) {
1644 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1645 debug("subsystem: exec() %s", options.subsystem_command[i]);
1646 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1652 log("subsystem request for %s failed, subsystem not found", subsys);
1659 session_x11_req(Session *s)
1662 if (no_x11_forwarding_flag) {
1663 debug("X11 forwarding disabled in user configuration file.");
1666 if (!options.x11_forwarding) {
1667 debug("X11 forwarding disabled in server configuration file.");
1670 if (xauthfile != NULL) {
1671 debug("X11 fwd already started.");
1675 debug("Received request for X11 forwarding with auth spoofing.");
1676 if (s->display != NULL)
1677 packet_disconnect("Protocol error: X11 display already set.");
1679 s->single_connection = packet_get_char();
1680 s->auth_proto = packet_get_string(NULL);
1681 s->auth_data = packet_get_string(NULL);
1682 s->screen = packet_get_int();
1685 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1686 if (s->display == NULL) {
1687 xfree(s->auth_proto);
1688 xfree(s->auth_data);
1691 xauthfile = xmalloc(MAXPATHLEN);
1692 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1693 temporarily_use_uid(s->pw->pw_uid);
1694 if (mkdtemp(xauthfile) == NULL) {
1696 error("private X11 dir: mkdtemp %s failed: %s",
1697 xauthfile, strerror(errno));
1700 xfree(s->auth_proto);
1701 xfree(s->auth_data);
1702 /* XXXX remove listening channels */
1705 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1706 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1710 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1715 session_shell_req(Session *s)
1717 /* if forced_command == NULL, the shell is execed */
1718 char *shell = forced_command;
1722 do_exec_no_pty(s, shell, s->pw);
1724 do_exec_pty(s, shell, s->pw);
1729 session_exec_req(Session *s)
1732 char *command = packet_get_string(&len);
1734 if (forced_command) {
1735 original_command = command;
1736 command = forced_command;
1737 debug("Forced command '%.500s'", forced_command);
1741 do_exec_no_pty(s, command, s->pw);
1743 do_exec_pty(s, command, s->pw);
1744 if (forced_command == NULL)
1750 session_auth_agent_req(Session *s)
1752 static int called = 0;
1754 if (no_agent_forwarding_flag) {
1755 debug("session_auth_agent_req: no_agent_forwarding_flag");
1762 return auth_input_request_forwarding(s->pw);
1767 session_input_channel_req(int id, void *arg)
1776 rtype = packet_get_string(&len);
1777 reply = packet_get_char();
1779 s = session_by_channel(id);
1781 fatal("session_input_channel_req: channel %d: no session", id);
1782 c = channel_lookup(id);
1784 fatal("session_input_channel_req: channel %d: bad channel", id);
1786 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1787 s->self, id, rtype, reply);
1790 * a session is in LARVAL state until a shell
1791 * or programm is executed
1793 if (c->type == SSH_CHANNEL_LARVAL) {
1794 if (strcmp(rtype, "shell") == 0) {
1795 success = session_shell_req(s);
1796 } else if (strcmp(rtype, "exec") == 0) {
1797 success = session_exec_req(s);
1798 } else if (strcmp(rtype, "pty-req") == 0) {
1799 success = session_pty_req(s);
1800 } else if (strcmp(rtype, "x11-req") == 0) {
1801 success = session_x11_req(s);
1802 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1803 success = session_auth_agent_req(s);
1804 } else if (strcmp(rtype, "subsystem") == 0) {
1805 success = session_subsystem_req(s);
1808 if (strcmp(rtype, "window-change") == 0) {
1809 success = session_window_change_req(s);
1813 packet_start(success ?
1814 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1815 packet_put_int(c->remote_id);
1822 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1825 fatal("session_set_fds: called for proto != 2.0");
1827 * now that have a child and a pipe to the child,
1828 * we can activate our channel and register the fd's
1830 if (s->chanid == -1)
1831 fatal("no channel for session %d", s->self);
1832 channel_set_fds(s->chanid,
1834 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1839 session_pty_cleanup(Session *s)
1841 if (s == NULL || s->ttyfd == -1)
1844 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1846 /* Cancel the cleanup function. */
1847 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1849 /* Record that the user has logged out. */
1850 record_logout(s->pid, s->tty);
1852 /* Release the pseudo-tty. */
1853 pty_release(s->tty);
1856 * Close the server side of the socket pairs. We must do this after
1857 * the pty cleanup, so that another process doesn't get this pty
1858 * while we're still cleaning up.
1860 if (close(s->ptymaster) < 0)
1861 error("close(s->ptymaster): %s", strerror(errno));
1865 session_exit_message(Session *s, int status)
1869 fatal("session_close: no session");
1870 c = channel_lookup(s->chanid);
1872 fatal("session_close: session %d: no channel %d",
1873 s->self, s->chanid);
1874 debug("session_exit_message: session %d channel %d pid %d",
1875 s->self, s->chanid, s->pid);
1877 if (WIFEXITED(status)) {
1878 channel_request_start(s->chanid,
1880 packet_put_int(WEXITSTATUS(status));
1882 } else if (WIFSIGNALED(status)) {
1883 channel_request_start(s->chanid,
1885 packet_put_int(WTERMSIG(status));
1887 packet_put_char(WCOREDUMP(status));
1888 #else /* WCOREDUMP */
1890 #endif /* WCOREDUMP */
1891 packet_put_cstring("");
1892 packet_put_cstring("");
1895 /* Some weird exit cause. Just exit. */
1896 packet_disconnect("wait returned status %04x.", status);
1899 /* disconnect channel */
1900 debug("session_exit_message: release channel %d", s->chanid);
1901 channel_cancel_cleanup(s->chanid);
1903 * emulate a write failure with 'chan_write_failed', nobody will be
1904 * interested in data we write.
1905 * Note that we must not call 'chan_read_failed', since there could
1906 * be some more data waiting in the pipe.
1908 if (c->ostate != CHAN_OUTPUT_CLOSED)
1909 chan_write_failed(c);
1914 session_free(Session *s)
1916 debug("session_free: session %d pid %d", s->self, s->pid);
1922 xfree(s->auth_data);
1924 xfree(s->auth_proto);
1929 session_close(Session *s)
1931 session_pty_cleanup(s);
1933 session_proctitle(s);
1937 session_close_by_pid(pid_t pid, int status)
1939 Session *s = session_by_pid(pid);
1941 debug("session_close_by_pid: no session for pid %d", s->pid);
1944 if (s->chanid != -1)
1945 session_exit_message(s, status);
1950 * this is called when a channel dies before
1951 * the session 'child' itself dies
1954 session_close_by_channel(int id, void *arg)
1956 Session *s = session_by_channel(id);
1958 debug("session_close_by_channel: no session for channel %d", id);
1961 /* disconnect channel */
1962 channel_cancel_cleanup(s->chanid);
1965 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1967 /* close session immediately */
1970 /* notify child, delay session cleanup */
1972 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1973 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1974 error("session_close_by_channel: kill %d: %s",
1975 s->pid, strerror(errno));
1980 session_tty_list(void)
1982 static char buf[1024];
1985 for(i = 0; i < MAX_SESSIONS; i++) {
1986 Session *s = &sessions[i];
1987 if (s->used && s->ttyfd != -1) {
1989 strlcat(buf, ",", sizeof buf);
1990 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1994 strlcpy(buf, "notty", sizeof buf);
1999 session_proctitle(Session *s)
2002 error("no user for session %d", s->self);
2004 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2008 do_authenticated2(Authctxt *authctxt)
2012 * Cancel the alarm we set to limit the time taken for
2016 if (startup_pipe != -1) {
2017 close(startup_pipe);
2020 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
2021 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
2022 error("unable to get login class");
2028 xauthfile_cleanup_proc(NULL);