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.56 2001/02/16 14:03:43 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"
95 typedef struct Session Session;
104 int ptyfd, ttyfd, ptymaster;
105 int row, col, xpixel, ypixel;
112 int single_connection;
119 Session *session_new(void);
120 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
121 void session_pty_cleanup(Session *s);
122 void session_proctitle(Session *s);
123 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
124 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
125 void do_login(Session *s, const char *command);
128 do_child(const char *command, struct passwd * pw, const char *term,
129 const char *display, const char *auth_proto,
130 const char *auth_data, const char *ttyname);
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;
221 * Cancel the alarm we set to limit the time taken for
225 if (startup_pipe != -1) {
231 * Inform the channel mechanism that we are the server side and that
232 * the client may request to connect to any port at all. (The user
233 * could do it anyway, and we wouldn\'t know what is permitted except
234 * by the client telling us, so we can equally well trust the client
235 * not to request anything bogus.)
237 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
238 channel_permit_all_opens();
243 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
244 if ((lc = login_getclass(pw->pw_class)) == NULL) {
245 error("unable to get login class");
251 * We stay in this loop until the client requests to execute a shell
257 /* Get a packet from the client. */
258 type = packet_read(&plen);
260 /* Process the packet. */
262 case SSH_CMSG_REQUEST_COMPRESSION:
263 packet_integrity_check(plen, 4, type);
264 compression_level = packet_get_int();
265 if (compression_level < 1 || compression_level > 9) {
266 packet_send_debug("Received illegal compression level %d.",
270 /* Enable compression after we have responded with SUCCESS. */
271 enable_compression_after_reply = 1;
275 case SSH_CMSG_REQUEST_PTY:
277 debug("Allocating a pty not permitted for this authentication.");
281 packet_disconnect("Protocol error: you already have a pty.");
283 debug("Allocating pty.");
285 /* Allocate a pty and open it. */
286 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
288 error("Failed to allocate pty.");
291 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
292 pty_setowner(pw, s->tty);
294 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
295 s->term = packet_get_string(&dlen);
296 packet_integrity_check(dlen, strlen(s->term), type);
297 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
298 /* Remaining bytes */
299 n_bytes = plen - (4 + dlen + 4 * 4);
301 if (strcmp(s->term, "") == 0) {
305 /* Get window size from the packet. */
306 s->row = packet_get_int();
307 s->col = packet_get_int();
308 s->xpixel = packet_get_int();
309 s->ypixel = packet_get_int();
310 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
312 /* Get tty modes from the packet. */
313 tty_parse_modes(s->ttyfd, &n_bytes);
314 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
316 session_proctitle(s);
318 /* Indicate that we now have a pty. */
323 case SSH_CMSG_X11_REQUEST_FORWARDING:
324 if (!options.x11_forwarding) {
325 packet_send_debug("X11 forwarding disabled in server configuration file.");
328 if (!options.xauth_location) {
329 packet_send_debug("No xauth program; cannot forward with spoofing.");
332 if (no_x11_forwarding_flag) {
333 packet_send_debug("X11 forwarding not permitted for this authentication.");
336 debug("Received request for X11 forwarding with auth spoofing.");
337 if (s->display != NULL)
338 packet_disconnect("Protocol error: X11 display already set.");
340 s->auth_proto = packet_get_string(&proto_len);
341 s->auth_data = packet_get_string(&data_len);
343 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER) {
344 debug2("SSH_PROTOFLAG_SCREEN_NUMBER == true");
345 packet_integrity_check(plen,
346 4 + proto_len + 4 + data_len + 4, type);
347 s->screen = packet_get_int();
349 debug2("SSH_PROTOFLAG_SCREEN_NUMBER == false");
350 packet_integrity_check(plen,
351 4 + proto_len + 4 + data_len, type);
354 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
356 if (s->display == NULL)
359 /* Setup to always have a local .Xauthority. */
360 xauthfile = xmalloc(MAXPATHLEN);
361 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
362 temporarily_use_uid(pw->pw_uid);
363 if (mkdtemp(xauthfile) == NULL) {
365 error("private X11 dir: mkdtemp %s failed: %s",
366 xauthfile, strerror(errno));
369 /* XXXX remove listening channels */
372 strlcat(xauthfile, "/cookies", MAXPATHLEN);
373 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
377 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
381 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
382 if (no_agent_forwarding_flag || compat13) {
383 debug("Authentication agent forwarding not permitted for this authentication.");
386 debug("Received authentication agent forwarding request.");
387 success = auth_input_request_forwarding(pw);
390 case SSH_CMSG_PORT_FORWARD_REQUEST:
391 if (no_port_forwarding_flag) {
392 debug("Port forwarding not permitted for this authentication.");
395 if (!options.allow_tcp_forwarding) {
396 debug("Port forwarding not permitted.");
399 debug("Received TCP/IP port forwarding request.");
400 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
404 case SSH_CMSG_MAX_PACKET_SIZE:
405 if (packet_set_maxsize(packet_get_int()) > 0)
409 case SSH_CMSG_EXEC_SHELL:
410 case SSH_CMSG_EXEC_CMD:
411 if (type == SSH_CMSG_EXEC_CMD) {
412 command = packet_get_string(&dlen);
413 debug("Exec command '%.500s'", command);
414 packet_integrity_check(plen, 4 + dlen, type);
417 packet_integrity_check(plen, 0, type);
419 if (forced_command != NULL) {
420 original_command = command;
421 command = forced_command;
422 debug("Forced command '%.500s'", forced_command);
425 do_exec_pty(s, command, pw);
427 do_exec_no_pty(s, command, pw);
431 /* Cleanup user's local Xauthority file. */
433 xauthfile_cleanup_proc(NULL);
438 * Any unknown messages in this phase are ignored,
439 * and a failure message is returned.
441 log("Unknown packet type received after authentication: %d", type);
443 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
447 /* Enable compression now that we have replied if appropriate. */
448 if (enable_compression_after_reply) {
449 enable_compression_after_reply = 0;
450 packet_start_compression(compression_level);
456 * This is called to fork and execute a command when we have no tty. This
457 * will call do_child from the child, and server_loop from the parent after
458 * setting up file descriptors and such.
461 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
466 int pin[2], pout[2], perr[2];
467 /* Allocate pipes for communicating with the program. */
468 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
469 packet_disconnect("Could not create pipes: %.100s",
471 #else /* USE_PIPES */
472 int inout[2], err[2];
473 /* Uses socket pairs to communicate with the program. */
474 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
475 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
476 packet_disconnect("Could not create socket pairs: %.100s",
478 #endif /* USE_PIPES */
480 fatal("do_exec_no_pty: no session");
482 session_proctitle(s);
484 /* Fork the child. */
485 if ((pid = fork()) == 0) {
486 /* Child. Reinitialize the log since the pid has changed. */
487 log_init(__progname, options.log_level, options.log_facility, log_stderr);
489 signal(SIGPIPE, SIG_DFL);
492 * Create a new session and process group since the 4.4BSD
493 * setlogin() affects the entire process group.
496 error("setsid failed: %.100s", strerror(errno));
500 * Redirect stdin. We close the parent side of the socket
501 * pair, and make the child side the standard input.
504 if (dup2(pin[0], 0) < 0)
505 perror("dup2 stdin");
508 /* Redirect stdout. */
510 if (dup2(pout[1], 1) < 0)
511 perror("dup2 stdout");
514 /* Redirect stderr. */
516 if (dup2(perr[1], 2) < 0)
517 perror("dup2 stderr");
519 #else /* USE_PIPES */
521 * Redirect stdin, stdout, and stderr. Stdin and stdout will
522 * use the same socket, as some programs (particularly rdist)
523 * seem to depend on it.
527 if (dup2(inout[0], 0) < 0) /* stdin */
528 perror("dup2 stdin");
529 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
530 perror("dup2 stdout");
531 if (dup2(err[0], 2) < 0) /* stderr */
532 perror("dup2 stderr");
533 #endif /* USE_PIPES */
535 /* Do processing for the child (exec command etc). */
536 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
541 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
544 packet_disconnect("fork failed: %.100s", strerror(errno));
546 /* Set interactive/non-interactive mode. */
547 packet_set_interactive(s->display != NULL);
549 /* We are the parent. Close the child sides of the pipes. */
555 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
557 /* Enter the interactive session. */
558 server_loop(pid, pin[1], pout[0], perr[0]);
559 /* server_loop has closed pin[1], pout[1], and perr[1]. */
561 #else /* USE_PIPES */
562 /* We are the parent. Close the child sides of the socket pairs. */
567 * Enter the interactive session. Note: server_loop must be able to
568 * handle the case that fdin and fdout are the same.
571 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
573 server_loop(pid, inout[1], inout[1], err[1]);
574 /* server_loop has closed inout[1] and err[1]. */
576 #endif /* USE_PIPES */
580 * This is called to fork and execute a command when we have a tty. This
581 * will call do_child from the child, and server_loop from the parent after
582 * setting up file descriptors, controlling tty, updating wtmp, utmp,
583 * lastlog, and other such operations.
586 do_exec_pty(Session *s, const char *command, struct passwd * pw)
588 int fdout, ptyfd, ttyfd, ptymaster;
592 fatal("do_exec_pty: no session");
596 /* Fork the child. */
597 if ((pid = fork()) == 0) {
598 /* Child. Reinitialize the log because the pid has changed. */
599 log_init(__progname, options.log_level, options.log_facility, log_stderr);
601 signal(SIGPIPE, SIG_DFL);
603 /* Close the master side of the pseudo tty. */
606 /* Make the pseudo tty our controlling tty. */
607 pty_make_controlling_tty(&ttyfd, s->tty);
609 /* Redirect stdin from the pseudo tty. */
610 if (dup2(ttyfd, fileno(stdin)) < 0)
611 error("dup2 stdin failed: %.100s", strerror(errno));
613 /* Redirect stdout to the pseudo tty. */
614 if (dup2(ttyfd, fileno(stdout)) < 0)
615 error("dup2 stdin failed: %.100s", strerror(errno));
617 /* Redirect stderr to the pseudo tty. */
618 if (dup2(ttyfd, fileno(stderr)) < 0)
619 error("dup2 stdin failed: %.100s", strerror(errno));
621 /* Close the extra descriptor for the pseudo tty. */
624 /* record login, etc. similar to login(1) */
625 if (!(options.use_login && command == NULL))
626 do_login(s, command);
628 /* Do common processing for the child, such as execing the command. */
629 do_child(command, pw, s->term, s->display, s->auth_proto,
630 s->auth_data, s->tty);
635 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
638 packet_disconnect("fork failed: %.100s", strerror(errno));
641 /* Parent. Close the slave side of the pseudo tty. */
645 * Create another descriptor of the pty master side for use as the
646 * standard input. We could use the original descriptor, but this
647 * simplifies code in server_loop. The descriptor is bidirectional.
651 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
653 /* we keep a reference to the pty master */
654 ptymaster = dup(ptyfd);
656 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
657 s->ptymaster = ptymaster;
659 /* Enter interactive session. */
660 packet_set_interactive(1);
662 session_set_fds(s, ptyfd, fdout, -1);
664 server_loop(pid, ptyfd, fdout, -1);
665 /* server_loop _has_ closed ptyfd and fdout. */
666 session_pty_cleanup(s);
671 get_remote_name_or_ip(void)
673 static const char *remote = "";
675 remote = get_canonical_hostname(options.reverse_mapping_check);
676 if (utmp_len == 0 || strlen(remote) > utmp_len)
677 remote = get_remote_ipaddr();
681 /* administrative, login(1)-like work */
683 do_login(Session *s, const char *command)
688 char hostname[MAXHOSTNAMELEN];
690 struct sockaddr_storage from;
692 time_t last_login_time;
693 struct passwd * pw = s->pw;
694 pid_t pid = getpid();
697 * Get IP address of client. If the connection is not a socket, let
698 * the address be 0.0.0.0.
700 memset(&from, 0, sizeof(from));
701 if (packet_connection_is_on_socket()) {
702 fromlen = sizeof(from);
703 if (getpeername(packet_get_connection_in(),
704 (struct sockaddr *) & from, &fromlen) < 0) {
705 debug("getpeername: %.100s", strerror(errno));
710 /* Get the time and hostname when the user last logged in. */
712 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
713 hostname, sizeof(hostname));
715 /* Record that there was a login on that tty from the remote host. */
716 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
717 get_remote_name_or_ip(), (struct sockaddr *)&from);
721 * If password change is needed, do it now.
722 * This needs to occur before the ~/.hushlogin check.
724 if (is_pam_password_change_required()) {
725 print_pam_messages();
730 /* Done if .hushlogin exists or a command given. */
733 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
734 #ifdef HAVE_LOGIN_CAP
735 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
737 if (stat(buf, &st) >= 0)
742 if (!is_pam_password_change_required())
743 print_pam_messages();
745 #ifdef WITH_AIXAUTHENTICATE
746 if (aixloginmsg && *aixloginmsg)
747 printf("%s\n", aixloginmsg);
748 #endif /* WITH_AIXAUTHENTICATE */
750 if (last_login_time != 0) {
751 time_string = ctime(&last_login_time);
752 if (strchr(time_string, '\n'))
753 *strchr(time_string, '\n') = 0;
754 if (strcmp(hostname, "") == 0)
755 printf("Last login: %s\r\n", time_string);
757 printf("Last login: %s from %s\r\n", time_string, hostname);
759 if (options.print_motd) {
760 #ifdef HAVE_LOGIN_CAP
761 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
764 f = fopen("/etc/motd", "r");
767 while (fgets(buf, sizeof(buf), f))
775 * Sets the value of the given variable in the environment. If the variable
776 * already exists, its value is overriden.
779 child_set_env(char ***envp, u_int *envsizep, const char *name,
786 * Find the slot where the value should be stored. If the variable
787 * already exists, we reuse the slot; otherwise we append a new slot
788 * at the end of the array, expanding if necessary.
791 namelen = strlen(name);
792 for (i = 0; env[i]; i++)
793 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
796 /* Reuse the slot. */
799 /* New variable. Expand if necessary. */
800 if (i >= (*envsizep) - 1) {
802 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
804 /* Need to set the NULL pointer at end of array beyond the new slot. */
808 /* Allocate space and format the variable in the appropriate slot. */
809 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
810 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
814 * Reads environment variables from the given file and adds/overrides them
815 * into the environment. If the file does not exist, this does nothing.
816 * Otherwise, it must consist of empty lines, comments (line starts with '#')
817 * and assignments of the form name=value. No other forms are allowed.
820 read_environment_file(char ***env, u_int *envsize,
821 const char *filename)
827 f = fopen(filename, "r");
831 while (fgets(buf, sizeof(buf), f)) {
832 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
834 if (!*cp || *cp == '#' || *cp == '\n')
836 if (strchr(cp, '\n'))
837 *strchr(cp, '\n') = '\0';
838 value = strchr(cp, '=');
840 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
844 * Replace the equals sign by nul, and advance value to
849 child_set_env(env, envsize, cp, value);
856 * Sets any environment variables which have been specified by PAM
858 void do_pam_environment(char ***env, int *envsize)
860 char *equals, var_name[512], var_val[512];
864 if ((pam_env = fetch_pam_environment()) == NULL)
867 for(i = 0; pam_env[i] != NULL; i++) {
868 if ((equals = strstr(pam_env[i], "=")) == NULL)
871 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
872 memset(var_name, '\0', sizeof(var_name));
873 memset(var_val, '\0', sizeof(var_val));
875 strncpy(var_name, pam_env[i], equals - pam_env[i]);
876 strcpy(var_val, equals + 1);
878 debug3("PAM environment: %s=%s", var_name, var_val);
880 child_set_env(env, envsize, var_name, var_val);
887 void copy_environment(char ***env, int *envsize)
889 char *equals, var_name[512], var_val[512];
892 for(i = 0; environ[i] != NULL; i++) {
893 if ((equals = strstr(environ[i], "=")) == NULL)
896 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
897 memset(var_name, '\0', sizeof(var_name));
898 memset(var_val, '\0', sizeof(var_val));
900 strncpy(var_name, environ[i], equals - environ[i]);
901 strcpy(var_val, equals + 1);
903 debug3("Copy environment: %s=%s", var_name, var_val);
905 child_set_env(env, envsize, var_name, var_val);
911 #if defined(HAVE_GETUSERATTR)
913 * AIX-specific login initialisation
915 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
920 getrlimit(resource, &rlim);
923 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
925 rlim.rlim_cur = RLIM_INFINITY;
926 } else if (slim != 0) {
927 /* See the wackiness below */
928 if (rlim.rlim_cur == slim * mult)
931 rlim.rlim_cur = slim * mult;
936 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
938 rlim.rlim_max = RLIM_INFINITY;
939 } else if (hlim != 0) {
940 rlim.rlim_max = hlim * mult;
945 * XXX For cpu and fsize the soft limit is set to the hard limit
946 * if the hard limit is left at its default value and the soft limit
947 * is changed from its default value, either by requesting it
948 * (slim == 0) or by setting it to the current default. At least
949 * that's how rlogind does it. If you're confused you're not alone.
950 * Bug or feature? AIX 4.3.1.2
952 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
953 && hlim == 0 && slim != 0)
954 rlim.rlim_max = rlim.rlim_cur;
955 /* A specified hard limit limits the soft limit */
956 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
957 rlim.rlim_cur = rlim.rlim_max;
958 /* A soft limit can increase a hard limit */
959 else if (rlim.rlim_cur > rlim.rlim_max)
960 rlim.rlim_max = rlim.rlim_cur;
962 if (setrlimit(resource, &rlim) != 0)
963 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
966 void set_limits_from_userattr(char *user)
971 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
972 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
973 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
974 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
975 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
976 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
977 #if defined(S_UNOFILE)
978 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
981 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
982 /* Convert decimal to octal */
983 (void) snprintf(buf, sizeof(buf), "%d", mask);
984 if (sscanf(buf, "%o", &mask) == 1)
988 #endif /* defined(HAVE_GETUSERATTR) */
991 * Performs common processing for the child, such as setting up the
992 * environment, closing extra file descriptors, setting the user and group
993 * ids, and executing the command or shell.
996 do_child(const char *command, struct passwd * pw, const char *term,
997 const char *display, const char *auth_proto,
998 const char *auth_data, const char *ttyname)
1000 const char *shell, *hostname = NULL, *cp = NULL;
1006 extern char **environ;
1009 #ifdef WITH_IRIX_PROJECT
1011 #endif /* WITH_IRIX_PROJECT */
1012 #ifdef WITH_IRIX_JOBS
1015 #ifdef WITH_IRIX_ARRAY
1017 #endif /* WITH_IRIX_ARRAY */
1018 #endif /* WITH_IRIX_JOBS */
1021 do_pam_session(pw->pw_name, ttyname);
1023 #endif /* USE_PAM */
1025 /* login(1) is only called if we execute the login shell */
1026 if (options.use_login && command != NULL)
1027 options.use_login = 0;
1029 #ifndef USE_PAM /* pam_nologin handles this */
1030 if (!options.use_login) {
1031 # ifdef HAVE_LOGIN_CAP
1032 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1033 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1034 _PATH_NOLOGIN), "r");
1035 # else /* HAVE_LOGIN_CAP */
1037 f = fopen(_PATH_NOLOGIN, "r");
1038 # endif /* HAVE_LOGIN_CAP */
1040 /* /etc/nologin exists. Print its contents and exit. */
1041 while (fgets(buf, sizeof(buf), f))
1047 #endif /* USE_PAM */
1049 /* Set login name, uid, gid, and groups. */
1050 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1051 switch, so we let login(1) to this for us. */
1052 if (!options.use_login) {
1054 session_setup_sia(pw->pw_name, ttyname);
1055 #else /* HAVE_OSF_SIA */
1059 if (getuid() == 0 || geteuid() == 0) {
1061 # ifdef HAVE_GETUSERATTR
1062 set_limits_from_userattr(pw->pw_name);
1063 # endif /* HAVE_GETUSERATTR */
1064 # ifdef HAVE_LOGIN_CAP
1065 if (setusercontext(lc, pw, pw->pw_uid,
1066 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1067 perror("unable to set user context");
1071 if (auth_approval(NULL, lc, pw->pw_name, "ssh") <= 0) {
1072 error("approval failure for %s", pw->pw_name);
1073 fprintf(stderr, "Approval failure");
1077 # else /* HAVE_LOGIN_CAP */
1078 if (setlogin(pw->pw_name) < 0)
1079 error("setlogin failed: %s", strerror(errno));
1080 if (setgid(pw->pw_gid) < 0) {
1084 /* Initialize the group list. */
1085 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1086 perror("initgroups");
1090 # ifdef WITH_IRIX_JOBS
1091 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1093 fatal("Failed to create job container: %.100s",
1096 # endif /* WITH_IRIX_JOBS */
1097 # ifdef WITH_IRIX_ARRAY
1098 /* initialize array session */
1100 if (newarraysess() != 0)
1101 fatal("Failed to set up new array session: %.100s",
1104 # endif /* WITH_IRIX_ARRAY */
1105 # ifdef WITH_IRIX_PROJECT
1106 /* initialize irix project info */
1107 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1108 debug("Failed to get project id, using projid 0");
1111 if (setprid(projid))
1112 fatal("Failed to initialize project %d for %s: %.100s",
1113 (int)projid, pw->pw_name, strerror(errno));
1114 # endif /* WITH_IRIX_PROJECT */
1115 #ifdef WITH_IRIX_AUDIT
1116 if (sysconf(_SC_AUDIT)) {
1117 debug("Setting sat id to %d", (int) pw->pw_uid);
1118 if (satsetid(pw->pw_uid))
1119 debug("error setting satid: %.100s", strerror(errno));
1121 #endif /* WITH_IRIX_AUDIT */
1123 /* Permanently switch to the desired uid. */
1124 permanently_set_uid(pw->pw_uid);
1125 # endif /* HAVE_LOGIN_CAP */
1127 #endif /* HAVE_OSF_SIA */
1129 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1130 /* Sets login uid for accounting */
1131 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1132 error("setluid: %s", strerror(errno));
1133 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1138 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1139 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1142 * Get the shell from the password data. An empty shell field is
1143 * legal, and means /bin/sh.
1145 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1146 #ifdef HAVE_LOGIN_CAP
1147 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1151 /* Try to get AFS tokens for the local cell. */
1155 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1156 krb_afslog(cell, 0);
1162 /* Initialize the environment. */
1164 env = xmalloc(envsize * sizeof(char *));
1169 * The Windows environment contains some setting which are
1170 * important for a running system. They must not be dropped.
1172 copy_environment(&env, &envsize);
1175 if (!options.use_login) {
1176 /* Set basic environment. */
1177 child_set_env(&env, &envsize, "USER", pw->pw_name);
1178 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1179 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1180 #ifdef HAVE_LOGIN_CAP
1181 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1182 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1183 #else /* HAVE_LOGIN_CAP */
1184 # ifndef HAVE_CYGWIN
1186 * There's no standard path on Windows. The path contains
1187 * important components pointing to the system directories,
1188 * needed for loading shared libraries. So the path better
1189 * remains intact here.
1191 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1192 # endif /* HAVE_CYGWIN */
1193 #endif /* HAVE_LOGIN_CAP */
1195 snprintf(buf, sizeof buf, "%.200s/%.50s",
1196 _PATH_MAILDIR, pw->pw_name);
1197 child_set_env(&env, &envsize, "MAIL", buf);
1199 /* Normal systems set SHELL by default. */
1200 child_set_env(&env, &envsize, "SHELL", shell);
1203 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1205 /* Set custom environment options from RSA authentication. */
1206 while (custom_environment) {
1207 struct envstring *ce = custom_environment;
1210 for (i = 0; s[i] != '=' && s[i]; i++);
1213 child_set_env(&env, &envsize, s, s + i + 1);
1215 custom_environment = ce->next;
1220 snprintf(buf, sizeof buf, "%.50s %d %d",
1221 get_remote_ipaddr(), get_remote_port(), get_local_port());
1222 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1225 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1227 child_set_env(&env, &envsize, "TERM", term);
1229 child_set_env(&env, &envsize, "DISPLAY", display);
1230 if (original_command)
1231 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1235 if ((cp = getenv("AUTHSTATE")) != NULL)
1236 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1237 if ((cp = getenv("KRB5CCNAME")) != NULL)
1238 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1239 read_environment_file(&env, &envsize, "/etc/environment");
1244 extern char *ticket;
1247 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1252 /* Pull in any environment variables that may have been set by PAM. */
1253 do_pam_environment(&env, &envsize);
1254 #endif /* USE_PAM */
1257 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1258 if (auth_get_socket_name() != NULL)
1259 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1260 auth_get_socket_name());
1262 /* read $HOME/.ssh/environment. */
1263 if (!options.use_login) {
1264 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1266 read_environment_file(&env, &envsize, buf);
1269 /* dump the environment */
1270 fprintf(stderr, "Environment:\n");
1271 for (i = 0; env[i]; i++)
1272 fprintf(stderr, " %.200s\n", env[i]);
1274 /* we have to stash the hostname before we close our socket. */
1275 if (options.use_login)
1276 hostname = get_remote_name_or_ip();
1278 * Close the connection descriptors; note that this is the child, and
1279 * the server will still have the socket open, and it is important
1280 * that we do not shutdown it. Note that the descriptors cannot be
1281 * closed before building the environment, as we call
1282 * get_remote_ipaddr there.
1284 if (packet_get_connection_in() == packet_get_connection_out())
1285 close(packet_get_connection_in());
1287 close(packet_get_connection_in());
1288 close(packet_get_connection_out());
1291 * Close all descriptors related to channels. They will still remain
1292 * open in the parent.
1294 /* XXX better use close-on-exec? -markus */
1295 channel_close_all();
1298 * Close any extra file descriptors. Note that there may still be
1299 * descriptors left by system functions. They will be closed later.
1304 * Close any extra open file descriptors so that we don\'t have them
1305 * hanging around in clients. Note that we want to do this after
1306 * initgroups, because at least on Solaris 2.3 it leaves file
1309 for (i = 3; i < 64; i++)
1312 /* Change current directory to the user\'s home directory. */
1313 if (chdir(pw->pw_dir) < 0) {
1314 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1315 pw->pw_dir, strerror(errno));
1316 #ifdef HAVE_LOGIN_CAP
1317 if (login_getcapbool(lc, "requirehome", 0))
1323 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1324 * xauth are run in the proper environment.
1329 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1332 if (!options.use_login) {
1333 if (stat(_PATH_SSH_USER_RC, &st) >= 0) {
1335 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, _PATH_SSH_USER_RC);
1337 f = popen(_PATH_BSHELL " " _PATH_SSH_USER_RC, "w");
1339 if (auth_proto != NULL && auth_data != NULL)
1340 fprintf(f, "%s %s\n", auth_proto, auth_data);
1343 fprintf(stderr, "Could not run %s\n", _PATH_SSH_USER_RC);
1344 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1346 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, _PATH_SSH_SYSTEM_RC);
1348 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1350 if (auth_proto != NULL && auth_data != NULL)
1351 fprintf(f, "%s %s\n", auth_proto, auth_data);
1354 fprintf(stderr, "Could not run %s\n", _PATH_SSH_SYSTEM_RC);
1355 } else if (options.xauth_location != NULL) {
1356 /* Add authority data to .Xauthority if appropriate. */
1357 if (auth_proto != NULL && auth_data != NULL) {
1358 char *screen = strchr(display, ':');
1361 "Running %.100s add %.100s %.100s %.100s\n",
1362 options.xauth_location, display,
1363 auth_proto, auth_data);
1364 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1367 "Adding %.*s/unix%s %s %s\n",
1368 (int)(screen-display), display,
1369 screen, auth_proto, auth_data);
1372 snprintf(cmd, sizeof cmd, "%s -q -",
1373 options.xauth_location);
1374 f = popen(cmd, "w");
1376 fprintf(f, "add %s %s %s\n", display,
1377 auth_proto, auth_data);
1378 #ifndef HAVE_CYGWIN /* Unix sockets are not supported */
1380 fprintf(f, "add %.*s/unix%s %s %s\n",
1381 (int)(screen-display), display,
1382 screen, auth_proto, auth_data);
1386 fprintf(stderr, "Could not run %s\n",
1391 /* Get the last component of the shell name. */
1392 cp = strrchr(shell, '/');
1399 * If we have no command, execute the shell. In this case, the shell
1400 * name to be passed in argv[0] is preceded by '-' to indicate that
1401 * this is a login shell.
1404 if (!options.use_login) {
1408 * Check for mail if we have a tty and it was enabled
1409 * in server options.
1411 if (ttyname && options.check_mail) {
1413 struct stat mailstat;
1414 mailbox = getenv("MAIL");
1415 if (mailbox != NULL) {
1416 if (stat(mailbox, &mailstat) != 0 ||
1417 mailstat.st_size == 0)
1418 printf("No mail.\n");
1419 else if (mailstat.st_mtime < mailstat.st_atime)
1420 printf("You have mail.\n");
1422 printf("You have new mail.\n");
1425 /* Start the shell. Set initial character to '-'. */
1427 strncpy(buf + 1, cp, sizeof(buf) - 1);
1428 buf[sizeof(buf) - 1] = 0;
1430 /* Execute the shell. */
1433 execve(shell, argv, env);
1435 /* Executing the shell failed. */
1440 /* Launch login(1). */
1442 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1443 "-p", "-f", "--", pw->pw_name, NULL);
1445 /* Login couldn't be executed, die. */
1452 * Execute the command using the user's shell. This uses the -c
1453 * option to execute the command.
1455 argv[0] = (char *) cp;
1457 argv[2] = (char *) command;
1459 execve(shell, argv, env);
1468 static int did_init = 0;
1470 debug("session_new: init");
1471 for(i = 0; i < MAX_SESSIONS; i++) {
1472 sessions[i].used = 0;
1473 sessions[i].self = i;
1477 for(i = 0; i < MAX_SESSIONS; i++) {
1478 Session *s = &sessions[i];
1489 s->auth_data = NULL;
1490 s->auth_proto = NULL;
1493 debug("session_new: session %d", i);
1504 for(i = 0; i < MAX_SESSIONS; i++) {
1505 Session *s = &sessions[i];
1506 debug("dump: used %d session %d %p channel %d pid %d",
1516 session_open(int chanid)
1518 Session *s = session_new();
1519 debug("session_open: channel %d", chanid);
1521 error("no more sessions");
1524 s->pw = auth_get_user();
1526 fatal("no user for session %d", s->self);
1527 debug("session_open: session %d: link with channel %d", s->self, chanid);
1533 session_by_channel(int id)
1536 for(i = 0; i < MAX_SESSIONS; i++) {
1537 Session *s = &sessions[i];
1538 if (s->used && s->chanid == id) {
1539 debug("session_by_channel: session %d channel %d", i, id);
1543 debug("session_by_channel: unknown channel %d", id);
1549 session_by_pid(pid_t pid)
1552 debug("session_by_pid: pid %d", pid);
1553 for(i = 0; i < MAX_SESSIONS; i++) {
1554 Session *s = &sessions[i];
1555 if (s->used && s->pid == pid)
1558 error("session_by_pid: unknown pid %d", pid);
1564 session_window_change_req(Session *s)
1566 s->col = packet_get_int();
1567 s->row = packet_get_int();
1568 s->xpixel = packet_get_int();
1569 s->ypixel = packet_get_int();
1571 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1576 session_pty_req(Session *s)
1579 char *term_modes; /* encoded terminal modes */
1585 s->term = packet_get_string(&len);
1586 s->col = packet_get_int();
1587 s->row = packet_get_int();
1588 s->xpixel = packet_get_int();
1589 s->ypixel = packet_get_int();
1590 term_modes = packet_get_string(&len);
1593 if (strcmp(s->term, "") == 0) {
1597 /* Allocate a pty and open it. */
1598 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1603 error("session_pty_req: session %d alloc failed", s->self);
1607 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1609 * Add a cleanup function to clear the utmp entry and record logout
1610 * time in case we call fatal() (e.g., the connection gets closed).
1612 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1613 pty_setowner(s->pw, s->tty);
1614 /* Get window size from the packet. */
1615 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1617 session_proctitle(s);
1619 /* XXX parse and set terminal modes */
1625 session_subsystem_req(Session *s)
1629 char *subsys = packet_get_string(&len);
1633 log("subsystem request for %s", subsys);
1635 for (i = 0; i < options.num_subsystems; i++) {
1636 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1637 debug("subsystem: exec() %s", options.subsystem_command[i]);
1638 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1644 log("subsystem request for %s failed, subsystem not found", subsys);
1651 session_x11_req(Session *s)
1654 if (no_x11_forwarding_flag) {
1655 debug("X11 forwarding disabled in user configuration file.");
1658 if (!options.x11_forwarding) {
1659 debug("X11 forwarding disabled in server configuration file.");
1662 if (xauthfile != NULL) {
1663 debug("X11 fwd already started.");
1667 debug("Received request for X11 forwarding with auth spoofing.");
1668 if (s->display != NULL)
1669 packet_disconnect("Protocol error: X11 display already set.");
1671 s->single_connection = packet_get_char();
1672 s->auth_proto = packet_get_string(NULL);
1673 s->auth_data = packet_get_string(NULL);
1674 s->screen = packet_get_int();
1677 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1678 if (s->display == NULL) {
1679 xfree(s->auth_proto);
1680 xfree(s->auth_data);
1683 xauthfile = xmalloc(MAXPATHLEN);
1684 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1685 temporarily_use_uid(s->pw->pw_uid);
1686 if (mkdtemp(xauthfile) == NULL) {
1688 error("private X11 dir: mkdtemp %s failed: %s",
1689 xauthfile, strerror(errno));
1692 xfree(s->auth_proto);
1693 xfree(s->auth_data);
1694 /* XXXX remove listening channels */
1697 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1698 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1702 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1707 session_shell_req(Session *s)
1709 /* if forced_command == NULL, the shell is execed */
1710 char *shell = forced_command;
1714 do_exec_no_pty(s, shell, s->pw);
1716 do_exec_pty(s, shell, s->pw);
1721 session_exec_req(Session *s)
1724 char *command = packet_get_string(&len);
1726 if (forced_command) {
1727 original_command = command;
1728 command = forced_command;
1729 debug("Forced command '%.500s'", forced_command);
1733 do_exec_no_pty(s, command, s->pw);
1735 do_exec_pty(s, command, s->pw);
1736 if (forced_command == NULL)
1742 session_auth_agent_req(Session *s)
1744 static int called = 0;
1746 if (no_agent_forwarding_flag) {
1747 debug("session_auth_agent_req: no_agent_forwarding_flag");
1754 return auth_input_request_forwarding(s->pw);
1759 session_input_channel_req(int id, void *arg)
1768 rtype = packet_get_string(&len);
1769 reply = packet_get_char();
1771 s = session_by_channel(id);
1773 fatal("session_input_channel_req: channel %d: no session", id);
1774 c = channel_lookup(id);
1776 fatal("session_input_channel_req: channel %d: bad channel", id);
1778 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1779 s->self, id, rtype, reply);
1782 * a session is in LARVAL state until a shell
1783 * or programm is executed
1785 if (c->type == SSH_CHANNEL_LARVAL) {
1786 if (strcmp(rtype, "shell") == 0) {
1787 success = session_shell_req(s);
1788 } else if (strcmp(rtype, "exec") == 0) {
1789 success = session_exec_req(s);
1790 } else if (strcmp(rtype, "pty-req") == 0) {
1791 success = session_pty_req(s);
1792 } else if (strcmp(rtype, "x11-req") == 0) {
1793 success = session_x11_req(s);
1794 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1795 success = session_auth_agent_req(s);
1796 } else if (strcmp(rtype, "subsystem") == 0) {
1797 success = session_subsystem_req(s);
1800 if (strcmp(rtype, "window-change") == 0) {
1801 success = session_window_change_req(s);
1805 packet_start(success ?
1806 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1807 packet_put_int(c->remote_id);
1814 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1817 fatal("session_set_fds: called for proto != 2.0");
1819 * now that have a child and a pipe to the child,
1820 * we can activate our channel and register the fd's
1822 if (s->chanid == -1)
1823 fatal("no channel for session %d", s->self);
1824 channel_set_fds(s->chanid,
1826 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1831 session_pty_cleanup(Session *s)
1833 if (s == NULL || s->ttyfd == -1)
1836 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1838 /* Cancel the cleanup function. */
1839 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1841 /* Record that the user has logged out. */
1842 record_logout(s->pid, s->tty);
1844 /* Release the pseudo-tty. */
1845 pty_release(s->tty);
1848 * Close the server side of the socket pairs. We must do this after
1849 * the pty cleanup, so that another process doesn't get this pty
1850 * while we're still cleaning up.
1852 if (close(s->ptymaster) < 0)
1853 error("close(s->ptymaster): %s", strerror(errno));
1857 session_exit_message(Session *s, int status)
1861 fatal("session_close: no session");
1862 c = channel_lookup(s->chanid);
1864 fatal("session_close: session %d: no channel %d",
1865 s->self, s->chanid);
1866 debug("session_exit_message: session %d channel %d pid %d",
1867 s->self, s->chanid, s->pid);
1869 if (WIFEXITED(status)) {
1870 channel_request_start(s->chanid,
1872 packet_put_int(WEXITSTATUS(status));
1874 } else if (WIFSIGNALED(status)) {
1875 channel_request_start(s->chanid,
1877 packet_put_int(WTERMSIG(status));
1879 packet_put_char(WCOREDUMP(status));
1880 #else /* WCOREDUMP */
1882 #endif /* WCOREDUMP */
1883 packet_put_cstring("");
1884 packet_put_cstring("");
1887 /* Some weird exit cause. Just exit. */
1888 packet_disconnect("wait returned status %04x.", status);
1891 /* disconnect channel */
1892 debug("session_exit_message: release channel %d", s->chanid);
1893 channel_cancel_cleanup(s->chanid);
1895 * emulate a write failure with 'chan_write_failed', nobody will be
1896 * interested in data we write.
1897 * Note that we must not call 'chan_read_failed', since there could
1898 * be some more data waiting in the pipe.
1900 if (c->ostate != CHAN_OUTPUT_CLOSED)
1901 chan_write_failed(c);
1906 session_free(Session *s)
1908 debug("session_free: session %d pid %d", s->self, s->pid);
1914 xfree(s->auth_data);
1916 xfree(s->auth_proto);
1921 session_close(Session *s)
1923 session_pty_cleanup(s);
1925 session_proctitle(s);
1929 session_close_by_pid(pid_t pid, int status)
1931 Session *s = session_by_pid(pid);
1933 debug("session_close_by_pid: no session for pid %d", s->pid);
1936 if (s->chanid != -1)
1937 session_exit_message(s, status);
1942 * this is called when a channel dies before
1943 * the session 'child' itself dies
1946 session_close_by_channel(int id, void *arg)
1948 Session *s = session_by_channel(id);
1950 debug("session_close_by_channel: no session for channel %d", id);
1953 /* disconnect channel */
1954 channel_cancel_cleanup(s->chanid);
1957 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1959 /* close session immediately */
1962 /* notify child, delay session cleanup */
1963 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1964 error("session_close_by_channel: kill %d: %s",
1965 s->pid, strerror(errno));
1970 session_tty_list(void)
1972 static char buf[1024];
1975 for(i = 0; i < MAX_SESSIONS; i++) {
1976 Session *s = &sessions[i];
1977 if (s->used && s->ttyfd != -1) {
1979 strlcat(buf, ",", sizeof buf);
1980 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1984 strlcpy(buf, "notty", sizeof buf);
1989 session_proctitle(Session *s)
1992 error("no user for session %d", s->self);
1994 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1998 do_authenticated2(Authctxt *authctxt)
2001 * Cancel the alarm we set to limit the time taken for
2005 if (startup_pipe != -1) {
2006 close(startup_pipe);
2009 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
2010 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
2011 error("unable to get login class");
2017 xauthfile_cleanup_proc(NULL);