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.84 2001/06/11 10:18:24 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #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)
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"
98 typedef struct Session Session;
106 int ptyfd, ttyfd, ptymaster;
107 int row, col, xpixel, ypixel;
114 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 int session_setup_x11fwd(Session *s);
127 void session_close(Session *s);
128 void do_exec_pty(Session *s, const char *command);
129 void do_exec_no_pty(Session *s, const char *command);
130 void do_login(Session *s, const char *command);
131 #ifdef LOGIN_NEEDS_UTMPX
132 void do_pre_login(Session *s);
134 void do_child(Session *s, const char *command);
136 int check_quietlogin(Session *s, const char *command);
137 void xauthfile_cleanup_proc(void *pw);
139 void do_authenticated1(Authctxt *authctxt);
140 void do_authenticated2(Authctxt *authctxt);
143 extern ServerOptions options;
144 extern char *__progname;
145 extern int log_stderr;
146 extern int debug_flag;
147 extern u_int utmp_len;
148 extern int startup_pipe;
149 extern void destroy_sensitive_data(void);
151 /* Local Xauthority file. */
152 static char *xauthfile;
154 /* original command from peer. */
155 char *original_command = NULL;
158 #define MAX_SESSIONS 10
159 Session sessions[MAX_SESSIONS];
161 #ifdef WITH_AIXAUTHENTICATE
162 /* AIX's lastlogin message, set in auth1.c */
164 #endif /* WITH_AIXAUTHENTICATE */
166 #ifdef HAVE_LOGIN_CAP
167 static login_cap_t *lc;
171 do_authenticated(Authctxt *authctxt)
174 * Cancel the alarm we set to limit the time taken for
178 if (startup_pipe != -1) {
182 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
183 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
184 error("unable to get login class");
188 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
189 packet_disconnect("Approval failure for %s",
190 authctxt->pw->pw_name);
194 /* setup the channel layer */
195 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
196 channel_permit_all_opens();
199 do_authenticated2(authctxt);
201 do_authenticated1(authctxt);
203 /* remote user's local Xauthority file and agent socket */
205 xauthfile_cleanup_proc(authctxt->pw);
206 if (auth_get_socket_name())
207 auth_sock_cleanup_proc(authctxt->pw);
211 * Remove local Xauthority file.
214 xauthfile_cleanup_proc(void *_pw)
216 struct passwd *pw = _pw;
219 debug("xauthfile_cleanup_proc called");
220 if (xauthfile != NULL) {
221 temporarily_use_uid(pw);
223 p = strrchr(xauthfile, '/');
235 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
236 * dropped connection).
239 pty_cleanup_proc(void *session)
243 fatal("pty_cleanup_proc: no session");
244 debug("pty_cleanup_proc: %s", s->tty);
247 /* Record that the user has logged out. */
248 record_logout(s->pid, s->tty);
251 /* Release the pseudo-tty. */
256 * Prepares for an interactive session. This is called after the user has
257 * been successfully authenticated. During this message exchange, pseudo
258 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
259 * are requested, etc.
262 do_authenticated1(Authctxt *authctxt)
266 int success, type, n_bytes, plen, screen_flag, have_pty = 0;
267 int compression_level = 0, enable_compression_after_reply = 0;
268 u_int proto_len, data_len, dlen;
271 s->pw = authctxt->pw;
274 * We stay in this loop until the client requests to execute a shell
280 /* Get a packet from the client. */
281 type = packet_read(&plen);
283 /* Process the packet. */
285 case SSH_CMSG_REQUEST_COMPRESSION:
286 packet_integrity_check(plen, 4, type);
287 compression_level = packet_get_int();
288 if (compression_level < 1 || compression_level > 9) {
289 packet_send_debug("Received illegal compression level %d.",
293 /* Enable compression after we have responded with SUCCESS. */
294 enable_compression_after_reply = 1;
298 case SSH_CMSG_REQUEST_PTY:
300 debug("Allocating a pty not permitted for this authentication.");
304 packet_disconnect("Protocol error: you already have a pty.");
306 debug("Allocating pty.");
308 /* Allocate a pty and open it. */
309 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
311 error("Failed to allocate pty.");
314 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
315 pty_setowner(s->pw, s->tty);
317 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
318 s->term = packet_get_string(&dlen);
319 packet_integrity_check(dlen, strlen(s->term), type);
320 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
321 /* Remaining bytes */
322 n_bytes = plen - (4 + dlen + 4 * 4);
324 if (strcmp(s->term, "") == 0) {
328 /* Get window size from the packet. */
329 s->row = packet_get_int();
330 s->col = packet_get_int();
331 s->xpixel = packet_get_int();
332 s->ypixel = packet_get_int();
333 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
335 /* Get tty modes from the packet. */
336 tty_parse_modes(s->ttyfd, &n_bytes);
337 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
339 session_proctitle(s);
341 /* Indicate that we now have a pty. */
346 case SSH_CMSG_X11_REQUEST_FORWARDING:
347 s->auth_proto = packet_get_string(&proto_len);
348 s->auth_data = packet_get_string(&data_len);
350 screen_flag = packet_get_protocol_flags() &
351 SSH_PROTOFLAG_SCREEN_NUMBER;
352 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
354 if (packet_remaining() == 4) {
356 debug2("Buggy client: "
357 "X11 screen flag missing");
358 s->screen = packet_get_int();
363 success = session_setup_x11fwd(s);
365 xfree(s->auth_proto);
367 s->auth_proto = NULL;
372 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
373 if (no_agent_forwarding_flag || compat13) {
374 debug("Authentication agent forwarding not permitted for this authentication.");
377 debug("Received authentication agent forwarding request.");
378 success = auth_input_request_forwarding(s->pw);
381 case SSH_CMSG_PORT_FORWARD_REQUEST:
382 if (no_port_forwarding_flag) {
383 debug("Port forwarding not permitted for this authentication.");
386 if (!options.allow_tcp_forwarding) {
387 debug("Port forwarding not permitted.");
390 debug("Received TCP/IP port forwarding request.");
391 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
395 case SSH_CMSG_MAX_PACKET_SIZE:
396 if (packet_set_maxsize(packet_get_int()) > 0)
400 case SSH_CMSG_EXEC_SHELL:
401 case SSH_CMSG_EXEC_CMD:
402 if (type == SSH_CMSG_EXEC_CMD) {
403 command = packet_get_string(&dlen);
404 debug("Exec command '%.500s'", command);
405 packet_integrity_check(plen, 4 + dlen, type);
408 packet_integrity_check(plen, 0, type);
410 if (forced_command != NULL) {
411 original_command = command;
412 command = forced_command;
413 debug("Forced command '%.500s'", forced_command);
416 do_exec_pty(s, command);
418 do_exec_no_pty(s, command);
426 * Any unknown messages in this phase are ignored,
427 * and a failure message is returned.
429 log("Unknown packet type received after authentication: %d", type);
431 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
435 /* Enable compression now that we have replied if appropriate. */
436 if (enable_compression_after_reply) {
437 enable_compression_after_reply = 0;
438 packet_start_compression(compression_level);
444 * This is called to fork and execute a command when we have no tty. This
445 * will call do_child from the child, and server_loop from the parent after
446 * setting up file descriptors and such.
449 do_exec_no_pty(Session *s, const char *command)
454 int pin[2], pout[2], perr[2];
455 /* Allocate pipes for communicating with the program. */
456 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
457 packet_disconnect("Could not create pipes: %.100s",
459 #else /* USE_PIPES */
460 int inout[2], err[2];
461 /* Uses socket pairs to communicate with the program. */
462 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
463 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
464 packet_disconnect("Could not create socket pairs: %.100s",
466 #endif /* USE_PIPES */
468 fatal("do_exec_no_pty: no session");
470 session_proctitle(s);
476 /* Fork the child. */
477 if ((pid = fork()) == 0) {
478 /* Child. Reinitialize the log since the pid has changed. */
479 log_init(__progname, options.log_level, options.log_facility, log_stderr);
482 * Create a new session and process group since the 4.4BSD
483 * setlogin() affects the entire process group.
486 error("setsid failed: %.100s", strerror(errno));
490 * Redirect stdin. We close the parent side of the socket
491 * pair, and make the child side the standard input.
494 if (dup2(pin[0], 0) < 0)
495 perror("dup2 stdin");
498 /* Redirect stdout. */
500 if (dup2(pout[1], 1) < 0)
501 perror("dup2 stdout");
504 /* Redirect stderr. */
506 if (dup2(perr[1], 2) < 0)
507 perror("dup2 stderr");
509 #else /* USE_PIPES */
511 * Redirect stdin, stdout, and stderr. Stdin and stdout will
512 * use the same socket, as some programs (particularly rdist)
513 * seem to depend on it.
517 if (dup2(inout[0], 0) < 0) /* stdin */
518 perror("dup2 stdin");
519 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
520 perror("dup2 stdout");
521 if (dup2(err[0], 2) < 0) /* stderr */
522 perror("dup2 stderr");
523 #endif /* USE_PIPES */
525 /* Do processing for the child (exec command etc). */
526 do_child(s, command);
531 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
534 packet_disconnect("fork failed: %.100s", strerror(errno));
536 /* Set interactive/non-interactive mode. */
537 packet_set_interactive(s->display != NULL);
539 /* We are the parent. Close the child sides of the pipes. */
545 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
547 /* Enter the interactive session. */
548 server_loop(pid, pin[1], pout[0], perr[0]);
549 /* server_loop has closed pin[1], pout[0], and perr[0]. */
551 #else /* USE_PIPES */
552 /* We are the parent. Close the child sides of the socket pairs. */
557 * Enter the interactive session. Note: server_loop must be able to
558 * handle the case that fdin and fdout are the same.
561 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
563 server_loop(pid, inout[1], inout[1], err[1]);
564 /* server_loop has closed inout[1] and err[1]. */
566 #endif /* USE_PIPES */
570 * This is called to fork and execute a command when we have a tty. This
571 * will call do_child from the child, and server_loop from the parent after
572 * setting up file descriptors, controlling tty, updating wtmp, utmp,
573 * lastlog, and other such operations.
576 do_exec_pty(Session *s, const char *command)
578 int fdout, ptyfd, ttyfd, ptymaster;
582 fatal("do_exec_pty: no session");
587 do_pam_session(s->pw->pw_name, s->tty);
591 /* Fork the child. */
592 if ((pid = fork()) == 0) {
593 /* Child. Reinitialize the log because the pid has changed. */
594 log_init(__progname, options.log_level, options.log_facility, log_stderr);
596 /* Close the master side of the pseudo tty. */
599 /* Make the pseudo tty our controlling tty. */
600 pty_make_controlling_tty(&ttyfd, s->tty);
602 /* Redirect stdin from the pseudo tty. */
603 if (dup2(ttyfd, fileno(stdin)) < 0)
604 error("dup2 stdin failed: %.100s", strerror(errno));
606 /* Redirect stdout to the pseudo tty. */
607 if (dup2(ttyfd, fileno(stdout)) < 0)
608 error("dup2 stdin failed: %.100s", strerror(errno));
610 /* Redirect stderr to the pseudo tty. */
611 if (dup2(ttyfd, fileno(stderr)) < 0)
612 error("dup2 stdin failed: %.100s", strerror(errno));
614 /* Close the extra descriptor for the pseudo tty. */
617 /* record login, etc. similar to login(1) */
619 if (!(options.use_login && command == NULL))
620 do_login(s, command);
621 # ifdef LOGIN_NEEDS_UTMPX
627 /* Do common processing for the child, such as execing the command. */
628 do_child(s, command);
633 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
636 packet_disconnect("fork failed: %.100s", strerror(errno));
639 /* Parent. Close the slave side of the pseudo tty. */
643 * Create another descriptor of the pty master side for use as the
644 * standard input. We could use the original descriptor, but this
645 * simplifies code in server_loop. The descriptor is bidirectional.
649 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
651 /* we keep a reference to the pty master */
652 ptymaster = dup(ptyfd);
654 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
655 s->ptymaster = ptymaster;
657 /* Enter interactive session. */
658 packet_set_interactive(1);
660 session_set_fds(s, ptyfd, fdout, -1);
662 server_loop(pid, ptyfd, fdout, -1);
663 /* server_loop _has_ closed ptyfd and fdout. */
667 #ifdef LOGIN_NEEDS_UTMPX
669 do_pre_login(Session *s)
672 struct sockaddr_storage from;
673 pid_t pid = getpid();
676 * Get IP address of client. If the connection is not a socket, let
677 * the address be 0.0.0.0.
679 memset(&from, 0, sizeof(from));
680 if (packet_connection_is_on_socket()) {
681 fromlen = sizeof(from);
682 if (getpeername(packet_get_connection_in(),
683 (struct sockaddr *) & from, &fromlen) < 0) {
684 debug("getpeername: %.100s", strerror(errno));
689 record_utmp_only(pid, s->tty, s->pw->pw_name,
690 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
691 (struct sockaddr *)&from);
695 /* administrative, login(1)-like work */
697 do_login(Session *s, const char *command)
700 char hostname[MAXHOSTNAMELEN];
702 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. */
722 if (options.print_lastlog) {
724 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
725 hostname, sizeof(hostname));
728 /* Record that there was a login on that tty from the remote host. */
729 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
730 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
731 (struct sockaddr *)&from);
735 * If password change is needed, do it now.
736 * This needs to occur before the ~/.hushlogin check.
738 if (is_pam_password_change_required()) {
739 print_pam_messages();
744 if (check_quietlogin(s, command))
748 if (!is_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 (options.print_lastlog && 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);
770 * Display the message of the day.
778 if (options.print_motd) {
779 #ifdef HAVE_LOGIN_CAP
780 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
783 f = fopen("/etc/motd", "r");
786 while (fgets(buf, sizeof(buf), f))
795 * Check for quiet login, either .hushlogin or command given.
798 check_quietlogin(Session *s, const char *command)
801 struct passwd * pw = s->pw;
804 /* Return 1 if .hushlogin exists or a command given. */
807 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
808 #ifdef HAVE_LOGIN_CAP
809 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
812 if (stat(buf, &st) >= 0)
819 * Sets the value of the given variable in the environment. If the variable
820 * already exists, its value is overriden.
823 child_set_env(char ***envp, u_int *envsizep, const char *name,
830 * Find the slot where the value should be stored. If the variable
831 * already exists, we reuse the slot; otherwise we append a new slot
832 * at the end of the array, expanding if necessary.
835 namelen = strlen(name);
836 for (i = 0; env[i]; i++)
837 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
840 /* Reuse the slot. */
843 /* New variable. Expand if necessary. */
844 if (i >= (*envsizep) - 1) {
846 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
848 /* Need to set the NULL pointer at end of array beyond the new slot. */
852 /* Allocate space and format the variable in the appropriate slot. */
853 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
854 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
858 * Reads environment variables from the given file and adds/overrides them
859 * into the environment. If the file does not exist, this does nothing.
860 * Otherwise, it must consist of empty lines, comments (line starts with '#')
861 * and assignments of the form name=value. No other forms are allowed.
864 read_environment_file(char ***env, u_int *envsize,
865 const char *filename)
871 f = fopen(filename, "r");
875 while (fgets(buf, sizeof(buf), f)) {
876 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
878 if (!*cp || *cp == '#' || *cp == '\n')
880 if (strchr(cp, '\n'))
881 *strchr(cp, '\n') = '\0';
882 value = strchr(cp, '=');
884 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
888 * Replace the equals sign by nul, and advance value to
893 child_set_env(env, envsize, cp, value);
900 * Sets any environment variables which have been specified by PAM
902 void do_pam_environment(char ***env, int *envsize)
904 char *equals, var_name[512], var_val[512];
908 if ((pam_env = fetch_pam_environment()) == NULL)
911 for(i = 0; pam_env[i] != NULL; i++) {
912 if ((equals = strstr(pam_env[i], "=")) == NULL)
915 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
916 memset(var_name, '\0', sizeof(var_name));
917 memset(var_val, '\0', sizeof(var_val));
919 strncpy(var_name, pam_env[i], equals - pam_env[i]);
920 strcpy(var_val, equals + 1);
922 debug3("PAM environment: %s=%s", var_name, var_val);
924 child_set_env(env, envsize, var_name, var_val);
931 void copy_environment(char ***env, int *envsize)
933 char *equals, var_name[512], var_val[512];
936 for(i = 0; environ[i] != NULL; i++) {
937 if ((equals = strstr(environ[i], "=")) == NULL)
940 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
941 memset(var_name, '\0', sizeof(var_name));
942 memset(var_val, '\0', sizeof(var_val));
944 strncpy(var_name, environ[i], equals - environ[i]);
945 strcpy(var_val, equals + 1);
947 debug3("Copy environment: %s=%s", var_name, var_val);
949 child_set_env(env, envsize, var_name, var_val);
955 #if defined(HAVE_GETUSERATTR)
957 * AIX-specific login initialisation
959 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
964 getrlimit(resource, &rlim);
967 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
969 rlim.rlim_cur = RLIM_INFINITY;
970 } else if (slim != 0) {
971 /* See the wackiness below */
972 if (rlim.rlim_cur == slim * mult)
975 rlim.rlim_cur = slim * mult;
980 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
982 rlim.rlim_max = RLIM_INFINITY;
983 } else if (hlim != 0) {
984 rlim.rlim_max = hlim * mult;
989 * XXX For cpu and fsize the soft limit is set to the hard limit
990 * if the hard limit is left at its default value and the soft limit
991 * is changed from its default value, either by requesting it
992 * (slim == 0) or by setting it to the current default. At least
993 * that's how rlogind does it. If you're confused you're not alone.
994 * Bug or feature? AIX 4.3.1.2
996 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
997 && hlim == 0 && slim != 0)
998 rlim.rlim_max = rlim.rlim_cur;
999 /* A specified hard limit limits the soft limit */
1000 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
1001 rlim.rlim_cur = rlim.rlim_max;
1002 /* A soft limit can increase a hard limit */
1003 else if (rlim.rlim_cur > rlim.rlim_max)
1004 rlim.rlim_max = rlim.rlim_cur;
1006 if (setrlimit(resource, &rlim) != 0)
1007 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
1010 void set_limits_from_userattr(char *user)
1015 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
1016 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
1017 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
1018 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
1019 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
1020 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1021 #if defined(S_UNOFILE)
1022 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1025 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1026 /* Convert decimal to octal */
1027 (void) snprintf(buf, sizeof(buf), "%d", mask);
1028 if (sscanf(buf, "%o", &mask) == 1)
1032 #endif /* defined(HAVE_GETUSERATTR) */
1035 * Performs common processing for the child, such as setting up the
1036 * environment, closing extra file descriptors, setting the user and group
1037 * ids, and executing the command or shell.
1040 do_child(Session *s, const char *command)
1042 const char *shell, *hostname = NULL, *cp = NULL;
1043 struct passwd * pw = s->pw;
1049 extern char **environ;
1053 #ifdef WITH_IRIX_PROJECT
1055 #endif /* WITH_IRIX_PROJECT */
1056 #ifdef WITH_IRIX_JOBS
1059 #ifdef WITH_IRIX_ARRAY
1061 #endif /* WITH_IRIX_ARRAY */
1062 #endif /* WITH_IRIX_JOBS */
1065 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1067 /* remove hostkey from the child's memory */
1068 destroy_sensitive_data();
1070 /* login(1) is only called if we execute the login shell */
1071 if (options.use_login && command != NULL)
1072 options.use_login = 0;
1074 #if !defined(USE_PAM) && !defined(HAVE_OSF_SIA)
1075 if (!options.use_login) {
1076 # ifdef HAVE_LOGIN_CAP
1077 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1078 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1079 _PATH_NOLOGIN), "r");
1080 # else /* HAVE_LOGIN_CAP */
1082 f = fopen(_PATH_NOLOGIN, "r");
1083 # endif /* HAVE_LOGIN_CAP */
1085 /* /etc/nologin exists. Print its contents and exit. */
1086 while (fgets(buf, sizeof(buf), f))
1092 #endif /* USE_PAM || HAVE_OSF_SIA */
1094 /* Set login name, uid, gid, and groups. */
1095 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1096 switch, so we let login(1) to this for us. */
1097 if (!options.use_login) {
1099 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1100 if (!check_quietlogin(s, command))
1102 #else /* HAVE_OSF_SIA */
1106 if (getuid() == 0 || geteuid() == 0) {
1108 # ifdef HAVE_GETUSERATTR
1109 set_limits_from_userattr(pw->pw_name);
1110 # endif /* HAVE_GETUSERATTR */
1111 # ifdef HAVE_LOGIN_CAP
1112 if (setusercontext(lc, pw, pw->pw_uid,
1113 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1114 perror("unable to set user context");
1117 # else /* HAVE_LOGIN_CAP */
1118 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1119 /* Sets login uid for accounting */
1120 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1121 error("setluid: %s", strerror(errno));
1122 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1124 if (setlogin(pw->pw_name) < 0)
1125 error("setlogin failed: %s", strerror(errno));
1126 if (setgid(pw->pw_gid) < 0) {
1130 /* Initialize the group list. */
1131 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1132 perror("initgroups");
1138 * PAM credentials may take the form of
1139 * supplementary groups. These will have been
1140 * wiped by the above initgroups() call.
1141 * Reestablish them here.
1144 # endif /* USE_PAM */
1145 # ifdef WITH_IRIX_JOBS
1146 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1148 fatal("Failed to create job container: %.100s",
1151 # endif /* WITH_IRIX_JOBS */
1152 # ifdef WITH_IRIX_ARRAY
1153 /* initialize array session */
1155 if (newarraysess() != 0)
1156 fatal("Failed to set up new array session: %.100s",
1159 # endif /* WITH_IRIX_ARRAY */
1160 # ifdef WITH_IRIX_PROJECT
1161 /* initialize irix project info */
1162 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1163 debug("Failed to get project id, using projid 0");
1166 if (setprid(projid))
1167 fatal("Failed to initialize project %d for %s: %.100s",
1168 (int)projid, pw->pw_name, strerror(errno));
1169 # endif /* WITH_IRIX_PROJECT */
1170 #ifdef WITH_IRIX_AUDIT
1171 if (sysconf(_SC_AUDIT)) {
1172 debug("Setting sat id to %d", (int) pw->pw_uid);
1173 if (satsetid(pw->pw_uid))
1174 debug("error setting satid: %.100s", strerror(errno));
1176 #endif /* WITH_IRIX_AUDIT */
1180 * AIX has a "usrinfo" area where logname and
1181 * other stuff is stored - a few applications
1182 * actually use this and die if it's not set
1186 cp = xmalloc(22 + strlen(s->tty) +
1187 2 * strlen(pw->pw_name));
1188 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1189 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1190 if (usrinfo(SETUINFO, cp, i) == -1)
1191 fatal("Couldn't set usrinfo: %s",
1193 debug3("AIX/UsrInfo: set len %d", i);
1197 /* Permanently switch to the desired uid. */
1198 permanently_set_uid(pw);
1199 # endif /* HAVE_LOGIN_CAP */
1201 #endif /* HAVE_OSF_SIA */
1206 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1207 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1210 * Get the shell from the password data. An empty shell field is
1211 * legal, and means /bin/sh.
1213 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1214 #ifdef HAVE_LOGIN_CAP
1215 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1219 /* Try to get AFS tokens for the local cell. */
1223 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1224 krb_afslog(cell, 0);
1230 /* Initialize the environment. */
1232 env = xmalloc(envsize * sizeof(char *));
1237 * The Windows environment contains some setting which are
1238 * important for a running system. They must not be dropped.
1240 copy_environment(&env, &envsize);
1243 if (!options.use_login) {
1244 /* Set basic environment. */
1245 child_set_env(&env, &envsize, "USER", pw->pw_name);
1246 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1247 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1248 #ifdef HAVE_LOGIN_CAP
1249 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1250 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1251 #else /* HAVE_LOGIN_CAP */
1252 # ifndef HAVE_CYGWIN
1254 * There's no standard path on Windows. The path contains
1255 * important components pointing to the system directories,
1256 * needed for loading shared libraries. So the path better
1257 * remains intact here.
1259 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1260 # endif /* HAVE_CYGWIN */
1261 #endif /* HAVE_LOGIN_CAP */
1263 snprintf(buf, sizeof buf, "%.200s/%.50s",
1264 _PATH_MAILDIR, pw->pw_name);
1265 child_set_env(&env, &envsize, "MAIL", buf);
1267 /* Normal systems set SHELL by default. */
1268 child_set_env(&env, &envsize, "SHELL", shell);
1271 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1273 /* Set custom environment options from RSA authentication. */
1274 while (custom_environment) {
1275 struct envstring *ce = custom_environment;
1278 for (i = 0; s[i] != '=' && s[i]; i++);
1281 child_set_env(&env, &envsize, s, s + i + 1);
1283 custom_environment = ce->next;
1288 snprintf(buf, sizeof buf, "%.50s %d %d",
1289 get_remote_ipaddr(), get_remote_port(), get_local_port());
1290 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1293 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1295 child_set_env(&env, &envsize, "TERM", s->term);
1297 child_set_env(&env, &envsize, "DISPLAY", s->display);
1298 if (original_command)
1299 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1303 if ((cp = getenv("AUTHSTATE")) != NULL)
1304 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1305 if ((cp = getenv("KRB5CCNAME")) != NULL)
1306 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1307 read_environment_file(&env, &envsize, "/etc/environment");
1312 extern char *ticket;
1315 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1320 /* Pull in any environment variables that may have been set by PAM. */
1321 do_pam_environment(&env, &envsize);
1322 #endif /* USE_PAM */
1325 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1326 if (auth_get_socket_name() != NULL)
1327 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1328 auth_get_socket_name());
1330 /* read $HOME/.ssh/environment. */
1331 if (!options.use_login) {
1332 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1334 read_environment_file(&env, &envsize, buf);
1337 /* dump the environment */
1338 fprintf(stderr, "Environment:\n");
1339 for (i = 0; env[i]; i++)
1340 fprintf(stderr, " %.200s\n", env[i]);
1342 /* we have to stash the hostname before we close our socket. */
1343 if (options.use_login)
1344 hostname = get_remote_name_or_ip(utmp_len,
1345 options.reverse_mapping_check);
1347 * Close the connection descriptors; note that this is the child, and
1348 * the server will still have the socket open, and it is important
1349 * that we do not shutdown it. Note that the descriptors cannot be
1350 * closed before building the environment, as we call
1351 * get_remote_ipaddr there.
1353 if (packet_get_connection_in() == packet_get_connection_out())
1354 close(packet_get_connection_in());
1356 close(packet_get_connection_in());
1357 close(packet_get_connection_out());
1360 * Close all descriptors related to channels. They will still remain
1361 * open in the parent.
1363 /* XXX better use close-on-exec? -markus */
1364 channel_close_all();
1367 * Close any extra file descriptors. Note that there may still be
1368 * descriptors left by system functions. They will be closed later.
1373 * Close any extra open file descriptors so that we don\'t have them
1374 * hanging around in clients. Note that we want to do this after
1375 * initgroups, because at least on Solaris 2.3 it leaves file
1378 for (i = 3; i < 64; i++)
1381 /* Change current directory to the user\'s home directory. */
1382 if (chdir(pw->pw_dir) < 0) {
1383 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1384 pw->pw_dir, strerror(errno));
1385 #ifdef HAVE_LOGIN_CAP
1386 if (login_getcapbool(lc, "requirehome", 0))
1392 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1393 * xauth are run in the proper environment.
1398 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1401 if (!options.use_login) {
1402 /* ignore _PATH_SSH_USER_RC for subsystems */
1403 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1404 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1405 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1407 fprintf(stderr, "Running %s\n", cmd);
1408 f = popen(cmd, "w");
1411 fprintf(f, "%s %s\n", s->auth_proto,
1415 fprintf(stderr, "Could not run %s\n",
1417 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1419 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1420 _PATH_SSH_SYSTEM_RC);
1421 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1424 fprintf(f, "%s %s\n", s->auth_proto,
1428 fprintf(stderr, "Could not run %s\n",
1429 _PATH_SSH_SYSTEM_RC);
1430 } else if (do_xauth && options.xauth_location != NULL) {
1431 /* Add authority data to .Xauthority if appropriate. */
1432 char *screen = strchr(s->display, ':');
1436 "Running %.100s add "
1437 "%.100s %.100s %.100s\n",
1438 options.xauth_location, s->display,
1439 s->auth_proto, s->auth_data);
1442 "Adding %.*s/unix%s %s %s\n",
1443 (int)(screen - s->display),
1445 s->auth_proto, s->auth_data);
1447 snprintf(cmd, sizeof cmd, "%s -q -",
1448 options.xauth_location);
1449 f = popen(cmd, "w");
1451 fprintf(f, "add %s %s %s\n", s->display,
1452 s->auth_proto, s->auth_data);
1454 fprintf(f, "add %.*s/unix%s %s %s\n",
1455 (int)(screen - s->display),
1461 fprintf(stderr, "Could not run %s\n",
1465 /* Get the last component of the shell name. */
1466 cp = strrchr(shell, '/');
1473 /* restore SIGPIPE for child */
1474 signal(SIGPIPE, SIG_DFL);
1477 * If we have no command, execute the shell. In this case, the shell
1478 * name to be passed in argv[0] is preceded by '-' to indicate that
1479 * this is a login shell.
1482 if (!options.use_login) {
1486 * Check for mail if we have a tty and it was enabled
1487 * in server options.
1489 if (s->ttyfd != -1 && options.check_mail) {
1491 struct stat mailstat;
1493 mailbox = getenv("MAIL");
1494 if (mailbox != NULL) {
1495 if (stat(mailbox, &mailstat) != 0 ||
1496 mailstat.st_size == 0)
1497 printf("No mail.\n");
1498 else if (mailstat.st_mtime < mailstat.st_atime)
1499 printf("You have mail.\n");
1501 printf("You have new mail.\n");
1504 /* Start the shell. Set initial character to '-'. */
1506 strncpy(buf + 1, cp, sizeof(buf) - 1);
1507 buf[sizeof(buf) - 1] = 0;
1509 /* Execute the shell. */
1512 execve(shell, argv, env);
1514 /* Executing the shell failed. */
1519 /* Launch login(1). */
1521 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1522 #ifdef LOGIN_NEEDS_TERM
1523 s->term? s->term : "unknown",
1525 "-p", "-f", "--", pw->pw_name, NULL);
1527 /* Login couldn't be executed, die. */
1534 * Execute the command using the user's shell. This uses the -c
1535 * option to execute the command.
1537 argv[0] = (char *) cp;
1539 argv[2] = (char *) command;
1541 execve(shell, argv, env);
1550 static int did_init = 0;
1552 debug("session_new: init");
1553 for(i = 0; i < MAX_SESSIONS; i++) {
1554 sessions[i].used = 0;
1555 sessions[i].self = i;
1559 for(i = 0; i < MAX_SESSIONS; i++) {
1560 Session *s = &sessions[i];
1562 memset(s, 0, sizeof(*s));
1567 debug("session_new: session %d", i);
1578 for(i = 0; i < MAX_SESSIONS; i++) {
1579 Session *s = &sessions[i];
1580 debug("dump: used %d session %d %p channel %d pid %d",
1590 session_open(int chanid)
1592 Session *s = session_new();
1593 debug("session_open: channel %d", chanid);
1595 error("no more sessions");
1598 s->pw = auth_get_user();
1600 fatal("no user for session %d", s->self);
1601 debug("session_open: session %d: link with channel %d", s->self, chanid);
1607 session_by_channel(int id)
1610 for(i = 0; i < MAX_SESSIONS; i++) {
1611 Session *s = &sessions[i];
1612 if (s->used && s->chanid == id) {
1613 debug("session_by_channel: session %d channel %d", i, id);
1617 debug("session_by_channel: unknown channel %d", id);
1623 session_by_pid(pid_t pid)
1626 debug("session_by_pid: pid %d", pid);
1627 for(i = 0; i < MAX_SESSIONS; i++) {
1628 Session *s = &sessions[i];
1629 if (s->used && s->pid == pid)
1632 error("session_by_pid: unknown pid %d", pid);
1638 session_window_change_req(Session *s)
1640 s->col = packet_get_int();
1641 s->row = packet_get_int();
1642 s->xpixel = packet_get_int();
1643 s->ypixel = packet_get_int();
1645 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1650 session_pty_req(Session *s)
1659 s->term = packet_get_string(&len);
1660 s->col = packet_get_int();
1661 s->row = packet_get_int();
1662 s->xpixel = packet_get_int();
1663 s->ypixel = packet_get_int();
1665 if (strcmp(s->term, "") == 0) {
1669 /* Allocate a pty and open it. */
1670 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1675 error("session_pty_req: session %d alloc failed", s->self);
1678 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1680 * Add a cleanup function to clear the utmp entry and record logout
1681 * time in case we call fatal() (e.g., the connection gets closed).
1683 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1684 pty_setowner(s->pw, s->tty);
1685 /* Get window size from the packet. */
1686 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1688 /* Get tty modes from the packet. */
1689 tty_parse_modes(s->ttyfd, &n_bytes);
1692 session_proctitle(s);
1698 session_subsystem_req(Session *s)
1702 char *subsys = packet_get_string(&len);
1706 log("subsystem request for %s", subsys);
1708 for (i = 0; i < options.num_subsystems; i++) {
1709 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1710 debug("subsystem: exec() %s", options.subsystem_command[i]);
1711 s->is_subsystem = 1;
1712 do_exec_no_pty(s, options.subsystem_command[i]);
1718 log("subsystem request for %s failed, subsystem not found", subsys);
1725 session_x11_req(Session *s)
1729 s->single_connection = packet_get_char();
1730 s->auth_proto = packet_get_string(NULL);
1731 s->auth_data = packet_get_string(NULL);
1732 s->screen = packet_get_int();
1735 success = session_setup_x11fwd(s);
1737 xfree(s->auth_proto);
1738 xfree(s->auth_data);
1739 s->auth_proto = NULL;
1740 s->auth_data = NULL;
1746 session_shell_req(Session *s)
1748 /* if forced_command == NULL, the shell is execed */
1749 char *shell = forced_command;
1752 do_exec_no_pty(s, shell);
1754 do_exec_pty(s, shell);
1759 session_exec_req(Session *s)
1762 char *command = packet_get_string(&len);
1764 if (forced_command) {
1765 original_command = command;
1766 command = forced_command;
1767 debug("Forced command '%.500s'", forced_command);
1770 do_exec_no_pty(s, command);
1772 do_exec_pty(s, command);
1773 if (forced_command == NULL)
1779 session_auth_agent_req(Session *s)
1781 static int called = 0;
1783 if (no_agent_forwarding_flag) {
1784 debug("session_auth_agent_req: no_agent_forwarding_flag");
1791 return auth_input_request_forwarding(s->pw);
1796 session_input_channel_req(int id, void *arg)
1805 rtype = packet_get_string(&len);
1806 reply = packet_get_char();
1808 s = session_by_channel(id);
1810 fatal("session_input_channel_req: channel %d: no session", id);
1811 c = channel_lookup(id);
1813 fatal("session_input_channel_req: channel %d: bad channel", id);
1815 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1816 s->self, id, rtype, reply);
1819 * a session is in LARVAL state until a shell, a command
1820 * or a subsystem is executed
1822 if (c->type == SSH_CHANNEL_LARVAL) {
1823 if (strcmp(rtype, "shell") == 0) {
1824 success = session_shell_req(s);
1825 } else if (strcmp(rtype, "exec") == 0) {
1826 success = session_exec_req(s);
1827 } else if (strcmp(rtype, "pty-req") == 0) {
1828 success = session_pty_req(s);
1829 } else if (strcmp(rtype, "x11-req") == 0) {
1830 success = session_x11_req(s);
1831 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1832 success = session_auth_agent_req(s);
1833 } else if (strcmp(rtype, "subsystem") == 0) {
1834 success = session_subsystem_req(s);
1837 if (strcmp(rtype, "window-change") == 0) {
1838 success = session_window_change_req(s);
1842 packet_start(success ?
1843 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1844 packet_put_int(c->remote_id);
1851 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1854 fatal("session_set_fds: called for proto != 2.0");
1856 * now that have a child and a pipe to the child,
1857 * we can activate our channel and register the fd's
1859 if (s->chanid == -1)
1860 fatal("no channel for session %d", s->self);
1861 channel_set_fds(s->chanid,
1863 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1868 session_pty_cleanup(Session *s)
1870 if (s == NULL || s->ttyfd == -1)
1873 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1875 /* Cancel the cleanup function. */
1876 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1878 /* Record that the user has logged out. */
1879 record_logout(s->pid, s->tty);
1881 /* Release the pseudo-tty. */
1882 pty_release(s->tty);
1885 * Close the server side of the socket pairs. We must do this after
1886 * the pty cleanup, so that another process doesn't get this pty
1887 * while we're still cleaning up.
1889 if (close(s->ptymaster) < 0)
1890 error("close(s->ptymaster): %s", strerror(errno));
1894 session_exit_message(Session *s, int status)
1898 fatal("session_close: no session");
1899 c = channel_lookup(s->chanid);
1901 fatal("session_close: session %d: no channel %d",
1902 s->self, s->chanid);
1903 debug("session_exit_message: session %d channel %d pid %d",
1904 s->self, s->chanid, s->pid);
1906 if (WIFEXITED(status)) {
1907 channel_request_start(s->chanid,
1909 packet_put_int(WEXITSTATUS(status));
1911 } else if (WIFSIGNALED(status)) {
1912 channel_request_start(s->chanid,
1914 packet_put_int(WTERMSIG(status));
1916 packet_put_char(WCOREDUMP(status));
1917 #else /* WCOREDUMP */
1919 #endif /* WCOREDUMP */
1920 packet_put_cstring("");
1921 packet_put_cstring("");
1924 /* Some weird exit cause. Just exit. */
1925 packet_disconnect("wait returned status %04x.", status);
1928 /* disconnect channel */
1929 debug("session_exit_message: release channel %d", s->chanid);
1930 channel_cancel_cleanup(s->chanid);
1932 * emulate a write failure with 'chan_write_failed', nobody will be
1933 * interested in data we write.
1934 * Note that we must not call 'chan_read_failed', since there could
1935 * be some more data waiting in the pipe.
1937 if (c->ostate != CHAN_OUTPUT_CLOSED)
1938 chan_write_failed(c);
1943 session_free(Session *s)
1945 debug("session_free: session %d pid %d", s->self, s->pid);
1951 xfree(s->auth_data);
1953 xfree(s->auth_proto);
1958 session_close(Session *s)
1960 session_pty_cleanup(s);
1962 session_proctitle(s);
1966 session_close_by_pid(pid_t pid, int status)
1968 Session *s = session_by_pid(pid);
1970 debug("session_close_by_pid: no session for pid %d", s->pid);
1973 if (s->chanid != -1)
1974 session_exit_message(s, status);
1979 * this is called when a channel dies before
1980 * the session 'child' itself dies
1983 session_close_by_channel(int id, void *arg)
1985 Session *s = session_by_channel(id);
1987 debug("session_close_by_channel: no session for channel %d", id);
1990 /* disconnect channel */
1991 channel_cancel_cleanup(s->chanid);
1994 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1996 /* close session immediately */
1999 /* notify child, delay session cleanup */
2000 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
2001 error("session_close_by_channel: kill %d: %s",
2002 s->pid, strerror(errno));
2007 session_tty_list(void)
2009 static char buf[1024];
2012 for(i = 0; i < MAX_SESSIONS; i++) {
2013 Session *s = &sessions[i];
2014 if (s->used && s->ttyfd != -1) {
2016 strlcat(buf, ",", sizeof buf);
2017 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2021 strlcpy(buf, "notty", sizeof buf);
2026 session_proctitle(Session *s)
2029 error("no user for session %d", s->self);
2031 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2035 session_setup_x11fwd(Session *s)
2040 if (no_x11_forwarding_flag) {
2041 packet_send_debug("X11 forwarding disabled in user configuration file.");
2044 if (!options.x11_forwarding) {
2045 debug("X11 forwarding disabled in server configuration file.");
2048 if (!options.xauth_location ||
2049 (stat(options.xauth_location, &st) == -1)) {
2050 packet_send_debug("No xauth program; cannot forward with spoofing.");
2053 if (s->display != NULL || xauthfile != NULL) {
2054 debug("X11 display already set.");
2057 xauthfile = xmalloc(MAXPATHLEN);
2058 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
2059 temporarily_use_uid(s->pw);
2060 if (mkdtemp(xauthfile) == NULL) {
2061 error("private X11 dir: mkdtemp %s failed: %s",
2062 xauthfile, strerror(errno));
2068 strlcat(xauthfile, "/cookies", MAXPATHLEN);
2069 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
2073 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
2074 if (s->display == NULL) {
2075 xauthfile_cleanup_proc(s->pw);
2078 fatal_add_cleanup(xauthfile_cleanup_proc, s->pw);
2083 do_authenticated2(Authctxt *authctxt)