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.64 2001/03/20 19:35:29 markus Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
61 #ifdef WITH_IRIX_PROJECT
63 #endif /* WITH_IRIX_PROJECT */
65 #include <sys/resource.h>
67 #ifdef WITH_IRIX_AUDIT
69 #endif /* WITH_IRIX_AUDIT */
71 #if defined(HAVE_USERSEC_H)
77 #include <sys/cygwin.h>
78 #define is_winnt (GetVersion() < 0x80000000)
82 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
83 # define S_UFSIZE_HARD S_UFSIZE "_hard"
84 # define S_UCPU_HARD S_UCPU "_hard"
85 # define S_UDATA_HARD S_UDATA "_hard"
86 # define S_USTACK_HARD S_USTACK "_hard"
87 # define S_URSS_HARD S_URSS "_hard"
88 # define S_UCORE_HARD S_UCORE "_hard"
89 # define S_UNOFILE_HARD S_UNOFILE "_hard"
99 typedef struct Session Session;
107 int ptyfd, ttyfd, ptymaster;
108 int row, col, xpixel, ypixel;
115 int single_connection;
123 Session *session_new(void);
124 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
125 void session_pty_cleanup(Session *s);
126 void session_proctitle(Session *s);
127 void do_exec_pty(Session *s, const char *command);
128 void do_exec_no_pty(Session *s, const char *command);
129 void do_login(Session *s, const char *command);
130 void do_child(Session *s, const char *command);
133 extern ServerOptions options;
134 extern char *__progname;
135 extern int log_stderr;
136 extern int debug_flag;
137 extern u_int utmp_len;
139 extern int startup_pipe;
141 /* Local Xauthority file. */
142 static char *xauthfile;
144 /* original command from peer. */
145 char *original_command = NULL;
148 #define MAX_SESSIONS 10
149 Session sessions[MAX_SESSIONS];
151 #ifdef WITH_AIXAUTHENTICATE
152 /* AIX's lastlogin message, set in auth1.c */
154 #endif /* WITH_AIXAUTHENTICATE */
156 #ifdef HAVE_LOGIN_CAP
157 static login_cap_t *lc;
161 * Remove local Xauthority file.
164 xauthfile_cleanup_proc(void *ignore)
166 debug("xauthfile_cleanup_proc called");
168 if (xauthfile != NULL) {
171 p = strrchr(xauthfile, '/');
182 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
183 * dropped connection).
186 pty_cleanup_proc(void *session)
190 fatal("pty_cleanup_proc: no session");
191 debug("pty_cleanup_proc: %s", s->tty);
194 /* Record that the user has logged out. */
195 record_logout(s->pid, s->tty);
198 /* Release the pseudo-tty. */
203 * Prepares for an interactive session. This is called after the user has
204 * been successfully authenticated. During this message exchange, pseudo
205 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
206 * are requested, etc.
209 do_authenticated(struct passwd * pw)
213 int compression_level = 0, enable_compression_after_reply = 0;
218 u_int proto_len, data_len, dlen;
222 * Cancel the alarm we set to limit the time taken for
226 if (startup_pipe != -1) {
231 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
232 channel_permit_all_opens();
237 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
238 if ((lc = login_getclass(pw->pw_class)) == NULL) {
239 error("unable to get login class");
245 * We stay in this loop until the client requests to execute a shell
251 /* Get a packet from the client. */
252 type = packet_read(&plen);
254 /* Process the packet. */
256 case SSH_CMSG_REQUEST_COMPRESSION:
257 packet_integrity_check(plen, 4, type);
258 compression_level = packet_get_int();
259 if (compression_level < 1 || compression_level > 9) {
260 packet_send_debug("Received illegal compression level %d.",
264 /* Enable compression after we have responded with SUCCESS. */
265 enable_compression_after_reply = 1;
269 case SSH_CMSG_REQUEST_PTY:
271 debug("Allocating a pty not permitted for this authentication.");
275 packet_disconnect("Protocol error: you already have a pty.");
277 debug("Allocating pty.");
279 /* Allocate a pty and open it. */
280 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
282 error("Failed to allocate pty.");
285 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
286 pty_setowner(pw, s->tty);
288 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
289 s->term = packet_get_string(&dlen);
290 packet_integrity_check(dlen, strlen(s->term), type);
291 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
292 /* Remaining bytes */
293 n_bytes = plen - (4 + dlen + 4 * 4);
295 if (strcmp(s->term, "") == 0) {
299 /* Get window size from the packet. */
300 s->row = packet_get_int();
301 s->col = packet_get_int();
302 s->xpixel = packet_get_int();
303 s->ypixel = packet_get_int();
304 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
306 /* Get tty modes from the packet. */
307 tty_parse_modes(s->ttyfd, &n_bytes);
308 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
310 session_proctitle(s);
312 /* Indicate that we now have a pty. */
317 case SSH_CMSG_X11_REQUEST_FORWARDING:
318 if (!options.x11_forwarding) {
319 packet_send_debug("X11 forwarding disabled in server configuration file.");
322 if (!options.xauth_location) {
323 packet_send_debug("No xauth program; cannot forward with spoofing.");
326 if (no_x11_forwarding_flag) {
327 packet_send_debug("X11 forwarding not permitted for this authentication.");
330 debug("Received request for X11 forwarding with auth spoofing.");
331 if (s->display != NULL)
332 packet_disconnect("Protocol error: X11 display already set.");
334 s->auth_proto = packet_get_string(&proto_len);
335 s->auth_data = packet_get_string(&data_len);
337 screen_flag = packet_get_protocol_flags() &
338 SSH_PROTOFLAG_SCREEN_NUMBER;
339 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
341 if (packet_remaining() == 4) {
343 debug2("Buggy client: "
344 "X11 screen flag missing");
345 packet_integrity_check(plen,
346 4 + proto_len + 4 + data_len + 4, type);
347 s->screen = packet_get_int();
349 packet_integrity_check(plen,
350 4 + proto_len + 4 + data_len, type);
353 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
355 if (s->display == NULL)
358 /* Setup to always have a local .Xauthority. */
359 xauthfile = xmalloc(MAXPATHLEN);
360 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
361 temporarily_use_uid(pw->pw_uid);
362 if (mkdtemp(xauthfile) == NULL) {
364 error("private X11 dir: mkdtemp %s failed: %s",
365 xauthfile, strerror(errno));
368 /* XXXX remove listening channels */
371 strlcat(xauthfile, "/cookies", MAXPATHLEN);
372 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
376 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
380 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
381 if (no_agent_forwarding_flag || compat13) {
382 debug("Authentication agent forwarding not permitted for this authentication.");
385 debug("Received authentication agent forwarding request.");
386 success = auth_input_request_forwarding(pw);
389 case SSH_CMSG_PORT_FORWARD_REQUEST:
390 if (no_port_forwarding_flag) {
391 debug("Port forwarding not permitted for this authentication.");
394 if (!options.allow_tcp_forwarding) {
395 debug("Port forwarding not permitted.");
398 debug("Received TCP/IP port forwarding request.");
399 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
403 case SSH_CMSG_MAX_PACKET_SIZE:
404 if (packet_set_maxsize(packet_get_int()) > 0)
408 case SSH_CMSG_EXEC_SHELL:
409 case SSH_CMSG_EXEC_CMD:
410 if (type == SSH_CMSG_EXEC_CMD) {
411 command = packet_get_string(&dlen);
412 debug("Exec command '%.500s'", command);
413 packet_integrity_check(plen, 4 + dlen, type);
416 packet_integrity_check(plen, 0, type);
418 if (forced_command != NULL) {
419 original_command = command;
420 command = forced_command;
421 debug("Forced command '%.500s'", forced_command);
424 do_exec_pty(s, command);
426 do_exec_no_pty(s, command);
430 /* Cleanup user's local Xauthority file. */
432 xauthfile_cleanup_proc(NULL);
437 * Any unknown messages in this phase are ignored,
438 * and a failure message is returned.
440 log("Unknown packet type received after authentication: %d", type);
442 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
446 /* Enable compression now that we have replied if appropriate. */
447 if (enable_compression_after_reply) {
448 enable_compression_after_reply = 0;
449 packet_start_compression(compression_level);
455 * This is called to fork and execute a command when we have no tty. This
456 * will call do_child from the child, and server_loop from the parent after
457 * setting up file descriptors and such.
460 do_exec_no_pty(Session *s, const char *command)
465 int pin[2], pout[2], perr[2];
466 /* Allocate pipes for communicating with the program. */
467 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
468 packet_disconnect("Could not create pipes: %.100s",
470 #else /* USE_PIPES */
471 int inout[2], err[2];
472 /* Uses socket pairs to communicate with the program. */
473 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
474 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
475 packet_disconnect("Could not create socket pairs: %.100s",
477 #endif /* USE_PIPES */
479 fatal("do_exec_no_pty: no session");
481 session_proctitle(s);
487 /* Fork the child. */
488 if ((pid = fork()) == 0) {
489 /* Child. Reinitialize the log since the pid has changed. */
490 log_init(__progname, options.log_level, options.log_facility, log_stderr);
492 signal(SIGPIPE, SIG_DFL);
495 * Create a new session and process group since the 4.4BSD
496 * setlogin() affects the entire process group.
499 error("setsid failed: %.100s", strerror(errno));
503 * Redirect stdin. We close the parent side of the socket
504 * pair, and make the child side the standard input.
507 if (dup2(pin[0], 0) < 0)
508 perror("dup2 stdin");
511 /* Redirect stdout. */
513 if (dup2(pout[1], 1) < 0)
514 perror("dup2 stdout");
517 /* Redirect stderr. */
519 if (dup2(perr[1], 2) < 0)
520 perror("dup2 stderr");
522 #else /* USE_PIPES */
524 * Redirect stdin, stdout, and stderr. Stdin and stdout will
525 * use the same socket, as some programs (particularly rdist)
526 * seem to depend on it.
530 if (dup2(inout[0], 0) < 0) /* stdin */
531 perror("dup2 stdin");
532 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
533 perror("dup2 stdout");
534 if (dup2(err[0], 2) < 0) /* stderr */
535 perror("dup2 stderr");
536 #endif /* USE_PIPES */
538 /* Do processing for the child (exec command etc). */
539 do_child(s, command);
544 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
547 packet_disconnect("fork failed: %.100s", strerror(errno));
549 /* Set interactive/non-interactive mode. */
550 packet_set_interactive(s->display != NULL);
552 /* We are the parent. Close the child sides of the pipes. */
558 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
560 /* Enter the interactive session. */
561 server_loop(pid, pin[1], pout[0], perr[0]);
562 /* server_loop has closed pin[1], pout[0], and perr[0]. */
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->is_subsystem ? -1 : err[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)
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 signal(SIGPIPE, SIG_DFL);
611 /* Close the master side of the pseudo tty. */
614 /* Make the pseudo tty our controlling tty. */
615 pty_make_controlling_tty(&ttyfd, s->tty);
617 /* Redirect stdin from the pseudo tty. */
618 if (dup2(ttyfd, fileno(stdin)) < 0)
619 error("dup2 stdin failed: %.100s", strerror(errno));
621 /* Redirect stdout to the pseudo tty. */
622 if (dup2(ttyfd, fileno(stdout)) < 0)
623 error("dup2 stdin failed: %.100s", strerror(errno));
625 /* Redirect stderr to the pseudo tty. */
626 if (dup2(ttyfd, fileno(stderr)) < 0)
627 error("dup2 stdin failed: %.100s", strerror(errno));
629 /* Close the extra descriptor for the pseudo tty. */
632 /* record login, etc. similar to login(1) */
633 if (!(options.use_login && command == NULL))
634 do_login(s, command);
636 /* Do common processing for the child, such as execing the command. */
637 do_child(s, command);
642 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
645 packet_disconnect("fork failed: %.100s", strerror(errno));
648 /* Parent. Close the slave side of the pseudo tty. */
652 * Create another descriptor of the pty master side for use as the
653 * standard input. We could use the original descriptor, but this
654 * simplifies code in server_loop. The descriptor is bidirectional.
658 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
660 /* we keep a reference to the pty master */
661 ptymaster = dup(ptyfd);
663 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
664 s->ptymaster = ptymaster;
666 /* Enter interactive session. */
667 packet_set_interactive(1);
669 session_set_fds(s, ptyfd, fdout, -1);
671 server_loop(pid, ptyfd, fdout, -1);
672 /* server_loop _has_ closed ptyfd and fdout. */
673 session_pty_cleanup(s);
678 get_remote_name_or_ip(void)
680 static const char *remote = "";
682 remote = get_canonical_hostname(options.reverse_mapping_check);
683 if (utmp_len == 0 || strlen(remote) > utmp_len)
684 remote = get_remote_ipaddr();
688 /* administrative, login(1)-like work */
690 do_login(Session *s, const char *command)
695 char hostname[MAXHOSTNAMELEN];
697 struct sockaddr_storage from;
699 time_t last_login_time;
700 struct passwd * pw = s->pw;
701 pid_t pid = getpid();
704 * Get IP address of client. If the connection is not a socket, let
705 * the address be 0.0.0.0.
707 memset(&from, 0, sizeof(from));
708 if (packet_connection_is_on_socket()) {
709 fromlen = sizeof(from);
710 if (getpeername(packet_get_connection_in(),
711 (struct sockaddr *) & from, &fromlen) < 0) {
712 debug("getpeername: %.100s", strerror(errno));
717 /* Get the time and hostname when the user last logged in. */
719 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
720 hostname, sizeof(hostname));
722 /* Record that there was a login on that tty from the remote host. */
723 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
724 get_remote_name_or_ip(), (struct sockaddr *)&from);
728 * If password change is needed, do it now.
729 * This needs to occur before the ~/.hushlogin check.
731 if (is_pam_password_change_required()) {
732 print_pam_messages();
737 /* Done if .hushlogin exists or a command given. */
740 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
741 #ifdef HAVE_LOGIN_CAP
742 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
744 if (stat(buf, &st) >= 0)
749 if (!is_pam_password_change_required())
750 print_pam_messages();
752 #ifdef WITH_AIXAUTHENTICATE
753 if (aixloginmsg && *aixloginmsg)
754 printf("%s\n", aixloginmsg);
755 #endif /* WITH_AIXAUTHENTICATE */
757 if (last_login_time != 0) {
758 time_string = ctime(&last_login_time);
759 if (strchr(time_string, '\n'))
760 *strchr(time_string, '\n') = 0;
761 if (strcmp(hostname, "") == 0)
762 printf("Last login: %s\r\n", time_string);
764 printf("Last login: %s from %s\r\n", time_string, hostname);
766 if (options.print_motd) {
767 #ifdef HAVE_LOGIN_CAP
768 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
771 f = fopen("/etc/motd", "r");
774 while (fgets(buf, sizeof(buf), f))
782 * Sets the value of the given variable in the environment. If the variable
783 * already exists, its value is overriden.
786 child_set_env(char ***envp, u_int *envsizep, const char *name,
793 * Find the slot where the value should be stored. If the variable
794 * already exists, we reuse the slot; otherwise we append a new slot
795 * at the end of the array, expanding if necessary.
798 namelen = strlen(name);
799 for (i = 0; env[i]; i++)
800 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
803 /* Reuse the slot. */
806 /* New variable. Expand if necessary. */
807 if (i >= (*envsizep) - 1) {
809 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
811 /* Need to set the NULL pointer at end of array beyond the new slot. */
815 /* Allocate space and format the variable in the appropriate slot. */
816 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
817 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
821 * Reads environment variables from the given file and adds/overrides them
822 * into the environment. If the file does not exist, this does nothing.
823 * Otherwise, it must consist of empty lines, comments (line starts with '#')
824 * and assignments of the form name=value. No other forms are allowed.
827 read_environment_file(char ***env, u_int *envsize,
828 const char *filename)
834 f = fopen(filename, "r");
838 while (fgets(buf, sizeof(buf), f)) {
839 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
841 if (!*cp || *cp == '#' || *cp == '\n')
843 if (strchr(cp, '\n'))
844 *strchr(cp, '\n') = '\0';
845 value = strchr(cp, '=');
847 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
851 * Replace the equals sign by nul, and advance value to
856 child_set_env(env, envsize, cp, value);
863 * Sets any environment variables which have been specified by PAM
865 void do_pam_environment(char ***env, int *envsize)
867 char *equals, var_name[512], var_val[512];
871 if ((pam_env = fetch_pam_environment()) == NULL)
874 for(i = 0; pam_env[i] != NULL; i++) {
875 if ((equals = strstr(pam_env[i], "=")) == NULL)
878 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
879 memset(var_name, '\0', sizeof(var_name));
880 memset(var_val, '\0', sizeof(var_val));
882 strncpy(var_name, pam_env[i], equals - pam_env[i]);
883 strcpy(var_val, equals + 1);
885 debug3("PAM environment: %s=%s", var_name, var_val);
887 child_set_env(env, envsize, var_name, var_val);
894 void copy_environment(char ***env, int *envsize)
896 char *equals, var_name[512], var_val[512];
899 for(i = 0; environ[i] != NULL; i++) {
900 if ((equals = strstr(environ[i], "=")) == NULL)
903 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
904 memset(var_name, '\0', sizeof(var_name));
905 memset(var_val, '\0', sizeof(var_val));
907 strncpy(var_name, environ[i], equals - environ[i]);
908 strcpy(var_val, equals + 1);
910 debug3("Copy environment: %s=%s", var_name, var_val);
912 child_set_env(env, envsize, var_name, var_val);
918 #if defined(HAVE_GETUSERATTR)
920 * AIX-specific login initialisation
922 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
927 getrlimit(resource, &rlim);
930 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
932 rlim.rlim_cur = RLIM_INFINITY;
933 } else if (slim != 0) {
934 /* See the wackiness below */
935 if (rlim.rlim_cur == slim * mult)
938 rlim.rlim_cur = slim * mult;
943 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
945 rlim.rlim_max = RLIM_INFINITY;
946 } else if (hlim != 0) {
947 rlim.rlim_max = hlim * mult;
952 * XXX For cpu and fsize the soft limit is set to the hard limit
953 * if the hard limit is left at its default value and the soft limit
954 * is changed from its default value, either by requesting it
955 * (slim == 0) or by setting it to the current default. At least
956 * that's how rlogind does it. If you're confused you're not alone.
957 * Bug or feature? AIX 4.3.1.2
959 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
960 && hlim == 0 && slim != 0)
961 rlim.rlim_max = rlim.rlim_cur;
962 /* A specified hard limit limits the soft limit */
963 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
964 rlim.rlim_cur = rlim.rlim_max;
965 /* A soft limit can increase a hard limit */
966 else if (rlim.rlim_cur > rlim.rlim_max)
967 rlim.rlim_max = rlim.rlim_cur;
969 if (setrlimit(resource, &rlim) != 0)
970 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
973 void set_limits_from_userattr(char *user)
978 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
979 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
980 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
981 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
982 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
983 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
984 #if defined(S_UNOFILE)
985 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
988 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
989 /* Convert decimal to octal */
990 (void) snprintf(buf, sizeof(buf), "%d", mask);
991 if (sscanf(buf, "%o", &mask) == 1)
995 #endif /* defined(HAVE_GETUSERATTR) */
998 * Performs common processing for the child, such as setting up the
999 * environment, closing extra file descriptors, setting the user and group
1000 * ids, and executing the command or shell.
1003 do_child(Session *s, const char *command)
1005 const char *shell, *hostname = NULL, *cp = NULL;
1006 struct passwd * pw = s->pw;
1012 extern char **environ;
1015 int do_xauth = s->auth_proto != NULL && s->auth_data != NULL;
1016 #ifdef WITH_IRIX_PROJECT
1018 #endif /* WITH_IRIX_PROJECT */
1019 #ifdef WITH_IRIX_JOBS
1022 #ifdef WITH_IRIX_ARRAY
1024 #endif /* WITH_IRIX_ARRAY */
1025 #endif /* WITH_IRIX_JOBS */
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 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1057 #else /* HAVE_OSF_SIA */
1061 if (getuid() == 0 || geteuid() == 0) {
1063 # ifdef HAVE_GETUSERATTR
1064 set_limits_from_userattr(pw->pw_name);
1065 # endif /* HAVE_GETUSERATTR */
1066 # ifdef HAVE_LOGIN_CAP
1067 if (setusercontext(lc, pw, pw->pw_uid,
1068 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1069 perror("unable to set user context");
1073 if (auth_approval(NULL, lc, pw->pw_name, "ssh") <= 0) {
1074 error("approval failure for %s", pw->pw_name);
1075 fprintf(stderr, "Approval failure");
1079 # else /* HAVE_LOGIN_CAP */
1080 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1081 /* Sets login uid for accounting */
1082 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1083 error("setluid: %s", strerror(errno));
1084 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
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 */
1133 * AIX has a "usrinfo" area where logname and
1134 * other stuff is stored - a few applications
1135 * actually use this and die if it's not set
1139 cp = xmalloc(22 + strlen(s->tty) +
1140 2 * strlen(pw->pw_name));
1141 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1142 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1143 if (usrinfo(SETUINFO, cp, i) == -1)
1144 fatal("Couldn't set usrinfo: %s",
1146 debug3("AIX/UsrInfo: set len %d", i);
1150 /* Permanently switch to the desired uid. */
1151 permanently_set_uid(pw->pw_uid);
1152 # endif /* HAVE_LOGIN_CAP */
1154 #endif /* HAVE_OSF_SIA */
1159 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1160 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1163 * Get the shell from the password data. An empty shell field is
1164 * legal, and means /bin/sh.
1166 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1167 #ifdef HAVE_LOGIN_CAP
1168 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1172 /* Try to get AFS tokens for the local cell. */
1176 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1177 krb_afslog(cell, 0);
1183 /* Initialize the environment. */
1185 env = xmalloc(envsize * sizeof(char *));
1190 * The Windows environment contains some setting which are
1191 * important for a running system. They must not be dropped.
1193 copy_environment(&env, &envsize);
1196 if (!options.use_login) {
1197 /* Set basic environment. */
1198 child_set_env(&env, &envsize, "USER", pw->pw_name);
1199 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1200 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1201 #ifdef HAVE_LOGIN_CAP
1202 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1203 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1204 #else /* HAVE_LOGIN_CAP */
1205 # ifndef HAVE_CYGWIN
1207 * There's no standard path on Windows. The path contains
1208 * important components pointing to the system directories,
1209 * needed for loading shared libraries. So the path better
1210 * remains intact here.
1212 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1213 # endif /* HAVE_CYGWIN */
1214 #endif /* HAVE_LOGIN_CAP */
1216 snprintf(buf, sizeof buf, "%.200s/%.50s",
1217 _PATH_MAILDIR, pw->pw_name);
1218 child_set_env(&env, &envsize, "MAIL", buf);
1220 /* Normal systems set SHELL by default. */
1221 child_set_env(&env, &envsize, "SHELL", shell);
1224 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1226 /* Set custom environment options from RSA authentication. */
1227 while (custom_environment) {
1228 struct envstring *ce = custom_environment;
1231 for (i = 0; s[i] != '=' && s[i]; i++);
1234 child_set_env(&env, &envsize, s, s + i + 1);
1236 custom_environment = ce->next;
1241 snprintf(buf, sizeof buf, "%.50s %d %d",
1242 get_remote_ipaddr(), get_remote_port(), get_local_port());
1243 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1246 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1248 child_set_env(&env, &envsize, "TERM", s->term);
1250 child_set_env(&env, &envsize, "DISPLAY", s->display);
1251 if (original_command)
1252 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1256 if ((cp = getenv("AUTHSTATE")) != NULL)
1257 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1258 if ((cp = getenv("KRB5CCNAME")) != NULL)
1259 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1260 read_environment_file(&env, &envsize, "/etc/environment");
1265 extern char *ticket;
1268 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1273 /* Pull in any environment variables that may have been set by PAM. */
1274 do_pam_environment(&env, &envsize);
1275 #endif /* USE_PAM */
1278 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1279 if (auth_get_socket_name() != NULL)
1280 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1281 auth_get_socket_name());
1283 /* read $HOME/.ssh/environment. */
1284 if (!options.use_login) {
1285 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1287 read_environment_file(&env, &envsize, buf);
1290 /* dump the environment */
1291 fprintf(stderr, "Environment:\n");
1292 for (i = 0; env[i]; i++)
1293 fprintf(stderr, " %.200s\n", env[i]);
1295 /* we have to stash the hostname before we close our socket. */
1296 if (options.use_login)
1297 hostname = get_remote_name_or_ip();
1299 * Close the connection descriptors; note that this is the child, and
1300 * the server will still have the socket open, and it is important
1301 * that we do not shutdown it. Note that the descriptors cannot be
1302 * closed before building the environment, as we call
1303 * get_remote_ipaddr there.
1305 if (packet_get_connection_in() == packet_get_connection_out())
1306 close(packet_get_connection_in());
1308 close(packet_get_connection_in());
1309 close(packet_get_connection_out());
1312 * Close all descriptors related to channels. They will still remain
1313 * open in the parent.
1315 /* XXX better use close-on-exec? -markus */
1316 channel_close_all();
1319 * Close any extra file descriptors. Note that there may still be
1320 * descriptors left by system functions. They will be closed later.
1325 * Close any extra open file descriptors so that we don\'t have them
1326 * hanging around in clients. Note that we want to do this after
1327 * initgroups, because at least on Solaris 2.3 it leaves file
1330 for (i = 3; i < 64; i++)
1333 /* Change current directory to the user\'s home directory. */
1334 if (chdir(pw->pw_dir) < 0) {
1335 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1336 pw->pw_dir, strerror(errno));
1337 #ifdef HAVE_LOGIN_CAP
1338 if (login_getcapbool(lc, "requirehome", 0))
1344 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1345 * xauth are run in the proper environment.
1350 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1353 if (!options.use_login) {
1354 if (stat(_PATH_SSH_USER_RC, &st) >= 0) {
1356 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1358 f = popen(_PATH_BSHELL " " _PATH_SSH_USER_RC, "w");
1361 fprintf(f, "%s %s\n", s->auth_proto,
1365 fprintf(stderr, "Could not run %s\n",
1367 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1369 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1370 _PATH_SSH_SYSTEM_RC);
1372 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1375 fprintf(f, "%s %s\n", s->auth_proto,
1379 fprintf(stderr, "Could not run %s\n",
1380 _PATH_SSH_SYSTEM_RC);
1381 } else if (do_xauth && options.xauth_location != NULL) {
1382 /* Add authority data to .Xauthority if appropriate. */
1383 char *screen = strchr(s->display, ':');
1387 "Running %.100s add "
1388 "%.100s %.100s %.100s\n",
1389 options.xauth_location, s->display,
1390 s->auth_proto, s->auth_data);
1393 "Adding %.*s/unix%s %s %s\n",
1394 (int)(screen - s->display),
1396 s->auth_proto, s->auth_data);
1398 snprintf(cmd, sizeof cmd, "%s -q -",
1399 options.xauth_location);
1400 f = popen(cmd, "w");
1402 fprintf(f, "add %s %s %s\n", s->display,
1403 s->auth_proto, s->auth_data);
1405 fprintf(f, "add %.*s/unix%s %s %s\n",
1406 (int)(screen - s->display),
1412 fprintf(stderr, "Could not run %s\n",
1416 /* Get the last component of the shell name. */
1417 cp = strrchr(shell, '/');
1424 * If we have no command, execute the shell. In this case, the shell
1425 * name to be passed in argv[0] is preceded by '-' to indicate that
1426 * this is a login shell.
1429 if (!options.use_login) {
1433 * Check for mail if we have a tty and it was enabled
1434 * in server options.
1436 if (s->ttyfd != -1 && options.check_mail) {
1438 struct stat mailstat;
1440 mailbox = getenv("MAIL");
1441 if (mailbox != NULL) {
1442 if (stat(mailbox, &mailstat) != 0 ||
1443 mailstat.st_size == 0)
1444 printf("No mail.\n");
1445 else if (mailstat.st_mtime < mailstat.st_atime)
1446 printf("You have mail.\n");
1448 printf("You have new mail.\n");
1451 /* Start the shell. Set initial character to '-'. */
1453 strncpy(buf + 1, cp, sizeof(buf) - 1);
1454 buf[sizeof(buf) - 1] = 0;
1456 /* Execute the shell. */
1459 execve(shell, argv, env);
1461 /* Executing the shell failed. */
1466 /* Launch login(1). */
1468 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1469 "-p", "-f", "--", pw->pw_name, NULL);
1471 /* Login couldn't be executed, die. */
1478 * Execute the command using the user's shell. This uses the -c
1479 * option to execute the command.
1481 argv[0] = (char *) cp;
1483 argv[2] = (char *) command;
1485 execve(shell, argv, env);
1494 static int did_init = 0;
1496 debug("session_new: init");
1497 for(i = 0; i < MAX_SESSIONS; i++) {
1498 sessions[i].used = 0;
1499 sessions[i].self = i;
1503 for(i = 0; i < MAX_SESSIONS; i++) {
1504 Session *s = &sessions[i];
1507 s->is_subsystem = 0;
1515 s->auth_data = NULL;
1516 s->auth_proto = NULL;
1519 debug("session_new: session %d", i);
1530 for(i = 0; i < MAX_SESSIONS; i++) {
1531 Session *s = &sessions[i];
1532 debug("dump: used %d session %d %p channel %d pid %d",
1542 session_open(int chanid)
1544 Session *s = session_new();
1545 debug("session_open: channel %d", chanid);
1547 error("no more sessions");
1550 s->pw = auth_get_user();
1552 fatal("no user for session %d", s->self);
1553 debug("session_open: session %d: link with channel %d", s->self, chanid);
1559 session_by_channel(int id)
1562 for(i = 0; i < MAX_SESSIONS; i++) {
1563 Session *s = &sessions[i];
1564 if (s->used && s->chanid == id) {
1565 debug("session_by_channel: session %d channel %d", i, id);
1569 debug("session_by_channel: unknown channel %d", id);
1575 session_by_pid(pid_t pid)
1578 debug("session_by_pid: pid %d", pid);
1579 for(i = 0; i < MAX_SESSIONS; i++) {
1580 Session *s = &sessions[i];
1581 if (s->used && s->pid == pid)
1584 error("session_by_pid: unknown pid %d", pid);
1590 session_window_change_req(Session *s)
1592 s->col = packet_get_int();
1593 s->row = packet_get_int();
1594 s->xpixel = packet_get_int();
1595 s->ypixel = packet_get_int();
1597 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1602 session_pty_req(Session *s)
1605 char *term_modes; /* encoded terminal modes */
1611 s->term = packet_get_string(&len);
1612 s->col = packet_get_int();
1613 s->row = packet_get_int();
1614 s->xpixel = packet_get_int();
1615 s->ypixel = packet_get_int();
1616 term_modes = packet_get_string(&len);
1619 if (strcmp(s->term, "") == 0) {
1623 /* Allocate a pty and open it. */
1624 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1629 error("session_pty_req: session %d alloc failed", s->self);
1633 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1635 * Add a cleanup function to clear the utmp entry and record logout
1636 * time in case we call fatal() (e.g., the connection gets closed).
1638 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1639 pty_setowner(s->pw, s->tty);
1640 /* Get window size from the packet. */
1641 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1643 session_proctitle(s);
1645 /* XXX parse and set terminal modes */
1651 session_subsystem_req(Session *s)
1655 char *subsys = packet_get_string(&len);
1659 log("subsystem request for %s", subsys);
1661 for (i = 0; i < options.num_subsystems; i++) {
1662 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1663 debug("subsystem: exec() %s", options.subsystem_command[i]);
1664 s->is_subsystem = 1;
1665 do_exec_no_pty(s, options.subsystem_command[i]);
1671 log("subsystem request for %s failed, subsystem not found", subsys);
1678 session_x11_req(Session *s)
1681 if (no_x11_forwarding_flag) {
1682 debug("X11 forwarding disabled in user configuration file.");
1685 if (!options.x11_forwarding) {
1686 debug("X11 forwarding disabled in server configuration file.");
1689 if (xauthfile != NULL) {
1690 debug("X11 fwd already started.");
1694 debug("Received request for X11 forwarding with auth spoofing.");
1695 if (s->display != NULL)
1696 packet_disconnect("Protocol error: X11 display already set.");
1698 s->single_connection = packet_get_char();
1699 s->auth_proto = packet_get_string(NULL);
1700 s->auth_data = packet_get_string(NULL);
1701 s->screen = packet_get_int();
1704 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1705 if (s->display == NULL) {
1706 xfree(s->auth_proto);
1707 xfree(s->auth_data);
1710 xauthfile = xmalloc(MAXPATHLEN);
1711 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1712 temporarily_use_uid(s->pw->pw_uid);
1713 if (mkdtemp(xauthfile) == NULL) {
1715 error("private X11 dir: mkdtemp %s failed: %s",
1716 xauthfile, strerror(errno));
1719 xfree(s->auth_proto);
1720 xfree(s->auth_data);
1721 /* XXXX remove listening channels */
1724 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1725 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1729 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1734 session_shell_req(Session *s)
1736 /* if forced_command == NULL, the shell is execed */
1737 char *shell = forced_command;
1740 do_exec_no_pty(s, shell);
1742 do_exec_pty(s, shell);
1747 session_exec_req(Session *s)
1750 char *command = packet_get_string(&len);
1752 if (forced_command) {
1753 original_command = command;
1754 command = forced_command;
1755 debug("Forced command '%.500s'", forced_command);
1758 do_exec_no_pty(s, command);
1760 do_exec_pty(s, command);
1761 if (forced_command == NULL)
1767 session_auth_agent_req(Session *s)
1769 static int called = 0;
1771 if (no_agent_forwarding_flag) {
1772 debug("session_auth_agent_req: no_agent_forwarding_flag");
1779 return auth_input_request_forwarding(s->pw);
1784 session_input_channel_req(int id, void *arg)
1793 rtype = packet_get_string(&len);
1794 reply = packet_get_char();
1796 s = session_by_channel(id);
1798 fatal("session_input_channel_req: channel %d: no session", id);
1799 c = channel_lookup(id);
1801 fatal("session_input_channel_req: channel %d: bad channel", id);
1803 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1804 s->self, id, rtype, reply);
1807 * a session is in LARVAL state until a shell, a command
1808 * or a subsystem is executed
1810 if (c->type == SSH_CHANNEL_LARVAL) {
1811 if (strcmp(rtype, "shell") == 0) {
1812 success = session_shell_req(s);
1813 } else if (strcmp(rtype, "exec") == 0) {
1814 success = session_exec_req(s);
1815 } else if (strcmp(rtype, "pty-req") == 0) {
1816 success = session_pty_req(s);
1817 } else if (strcmp(rtype, "x11-req") == 0) {
1818 success = session_x11_req(s);
1819 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1820 success = session_auth_agent_req(s);
1821 } else if (strcmp(rtype, "subsystem") == 0) {
1822 success = session_subsystem_req(s);
1825 if (strcmp(rtype, "window-change") == 0) {
1826 success = session_window_change_req(s);
1830 packet_start(success ?
1831 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1832 packet_put_int(c->remote_id);
1839 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1842 fatal("session_set_fds: called for proto != 2.0");
1844 * now that have a child and a pipe to the child,
1845 * we can activate our channel and register the fd's
1847 if (s->chanid == -1)
1848 fatal("no channel for session %d", s->self);
1849 channel_set_fds(s->chanid,
1851 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1856 session_pty_cleanup(Session *s)
1858 if (s == NULL || s->ttyfd == -1)
1861 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1863 /* Cancel the cleanup function. */
1864 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1866 /* Record that the user has logged out. */
1867 record_logout(s->pid, s->tty);
1869 /* Release the pseudo-tty. */
1870 pty_release(s->tty);
1873 * Close the server side of the socket pairs. We must do this after
1874 * the pty cleanup, so that another process doesn't get this pty
1875 * while we're still cleaning up.
1877 if (close(s->ptymaster) < 0)
1878 error("close(s->ptymaster): %s", strerror(errno));
1882 session_exit_message(Session *s, int status)
1886 fatal("session_close: no session");
1887 c = channel_lookup(s->chanid);
1889 fatal("session_close: session %d: no channel %d",
1890 s->self, s->chanid);
1891 debug("session_exit_message: session %d channel %d pid %d",
1892 s->self, s->chanid, s->pid);
1894 if (WIFEXITED(status)) {
1895 channel_request_start(s->chanid,
1897 packet_put_int(WEXITSTATUS(status));
1899 } else if (WIFSIGNALED(status)) {
1900 channel_request_start(s->chanid,
1902 packet_put_int(WTERMSIG(status));
1904 packet_put_char(WCOREDUMP(status));
1905 #else /* WCOREDUMP */
1907 #endif /* WCOREDUMP */
1908 packet_put_cstring("");
1909 packet_put_cstring("");
1912 /* Some weird exit cause. Just exit. */
1913 packet_disconnect("wait returned status %04x.", status);
1916 /* disconnect channel */
1917 debug("session_exit_message: release channel %d", s->chanid);
1918 channel_cancel_cleanup(s->chanid);
1920 * emulate a write failure with 'chan_write_failed', nobody will be
1921 * interested in data we write.
1922 * Note that we must not call 'chan_read_failed', since there could
1923 * be some more data waiting in the pipe.
1925 if (c->ostate != CHAN_OUTPUT_CLOSED)
1926 chan_write_failed(c);
1931 session_free(Session *s)
1933 debug("session_free: session %d pid %d", s->self, s->pid);
1939 xfree(s->auth_data);
1941 xfree(s->auth_proto);
1946 session_close(Session *s)
1948 session_pty_cleanup(s);
1950 session_proctitle(s);
1954 session_close_by_pid(pid_t pid, int status)
1956 Session *s = session_by_pid(pid);
1958 debug("session_close_by_pid: no session for pid %d", s->pid);
1961 if (s->chanid != -1)
1962 session_exit_message(s, status);
1967 * this is called when a channel dies before
1968 * the session 'child' itself dies
1971 session_close_by_channel(int id, void *arg)
1973 Session *s = session_by_channel(id);
1975 debug("session_close_by_channel: no session for channel %d", id);
1978 /* disconnect channel */
1979 channel_cancel_cleanup(s->chanid);
1982 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1984 /* close session immediately */
1987 /* notify child, delay session cleanup */
1988 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1989 error("session_close_by_channel: kill %d: %s",
1990 s->pid, strerror(errno));
1995 session_tty_list(void)
1997 static char buf[1024];
2000 for(i = 0; i < MAX_SESSIONS; i++) {
2001 Session *s = &sessions[i];
2002 if (s->used && s->ttyfd != -1) {
2004 strlcat(buf, ",", sizeof buf);
2005 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2009 strlcpy(buf, "notty", sizeof buf);
2014 session_proctitle(Session *s)
2017 error("no user for session %d", s->self);
2019 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2023 do_authenticated2(Authctxt *authctxt)
2026 * Cancel the alarm we set to limit the time taken for
2030 if (startup_pipe != -1) {
2031 close(startup_pipe);
2034 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
2035 channel_permit_all_opens();
2036 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
2037 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
2038 error("unable to get login class");
2044 xauthfile_cleanup_proc(NULL);