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);
488 /* Fork the child. */
489 if ((pid = fork()) == 0) {
490 /* Child. Reinitialize the log since the pid has changed. */
491 log_init(__progname, options.log_level, options.log_facility, log_stderr);
493 signal(SIGPIPE, SIG_DFL);
496 * Create a new session and process group since the 4.4BSD
497 * setlogin() affects the entire process group.
500 error("setsid failed: %.100s", strerror(errno));
504 * Redirect stdin. We close the parent side of the socket
505 * pair, and make the child side the standard input.
508 if (dup2(pin[0], 0) < 0)
509 perror("dup2 stdin");
512 /* Redirect stdout. */
514 if (dup2(pout[1], 1) < 0)
515 perror("dup2 stdout");
518 /* Redirect stderr. */
520 if (dup2(perr[1], 2) < 0)
521 perror("dup2 stderr");
523 #else /* USE_PIPES */
525 * Redirect stdin, stdout, and stderr. Stdin and stdout will
526 * use the same socket, as some programs (particularly rdist)
527 * seem to depend on it.
531 if (dup2(inout[0], 0) < 0) /* stdin */
532 perror("dup2 stdin");
533 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
534 perror("dup2 stdout");
535 if (dup2(err[0], 2) < 0) /* stderr */
536 perror("dup2 stderr");
537 #endif /* USE_PIPES */
539 /* Do processing for the child (exec command etc). */
540 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
545 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
548 packet_disconnect("fork failed: %.100s", strerror(errno));
550 /* Set interactive/non-interactive mode. */
551 packet_set_interactive(s->display != NULL);
553 /* We are the parent. Close the child sides of the pipes. */
559 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
561 /* Enter the interactive session. */
562 server_loop(pid, pin[1], pout[0], perr[0]);
563 /* server_loop has closed pin[1], pout[1], and perr[1]. */
565 #else /* USE_PIPES */
566 /* We are the parent. Close the child sides of the socket pairs. */
571 * Enter the interactive session. Note: server_loop must be able to
572 * handle the case that fdin and fdout are the same.
575 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
577 server_loop(pid, inout[1], inout[1], err[1]);
578 /* server_loop has closed inout[1] and err[1]. */
580 #endif /* USE_PIPES */
584 * This is called to fork and execute a command when we have a tty. This
585 * will call do_child from the child, and server_loop from the parent after
586 * setting up file descriptors, controlling tty, updating wtmp, utmp,
587 * lastlog, and other such operations.
590 do_exec_pty(Session *s, const char *command, struct passwd * pw)
592 int fdout, ptyfd, ttyfd, ptymaster;
596 fatal("do_exec_pty: no session");
601 do_pam_session(pw->pw_name, s->tty);
605 /* Fork the child. */
606 if ((pid = fork()) == 0) {
607 /* Child. Reinitialize the log because the pid has changed. */
608 log_init(__progname, options.log_level, options.log_facility, log_stderr);
610 signal(SIGPIPE, SIG_DFL);
612 /* Close the master side of the pseudo tty. */
615 /* Make the pseudo tty our controlling tty. */
616 pty_make_controlling_tty(&ttyfd, s->tty);
618 /* Redirect stdin from the pseudo tty. */
619 if (dup2(ttyfd, fileno(stdin)) < 0)
620 error("dup2 stdin failed: %.100s", strerror(errno));
622 /* Redirect stdout to the pseudo tty. */
623 if (dup2(ttyfd, fileno(stdout)) < 0)
624 error("dup2 stdin failed: %.100s", strerror(errno));
626 /* Redirect stderr to the pseudo tty. */
627 if (dup2(ttyfd, fileno(stderr)) < 0)
628 error("dup2 stdin failed: %.100s", strerror(errno));
630 /* Close the extra descriptor for the pseudo tty. */
633 /* record login, etc. similar to login(1) */
634 if (!(options.use_login && command == NULL))
635 do_login(s, command);
637 /* Do common processing for the child, such as execing the command. */
638 do_child(command, pw, s->term, s->display, s->auth_proto,
639 s->auth_data, s->tty);
644 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
647 packet_disconnect("fork failed: %.100s", strerror(errno));
650 /* Parent. Close the slave side of the pseudo tty. */
654 * Create another descriptor of the pty master side for use as the
655 * standard input. We could use the original descriptor, but this
656 * simplifies code in server_loop. The descriptor is bidirectional.
660 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
662 /* we keep a reference to the pty master */
663 ptymaster = dup(ptyfd);
665 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
666 s->ptymaster = ptymaster;
668 /* Enter interactive session. */
669 packet_set_interactive(1);
671 session_set_fds(s, ptyfd, fdout, -1);
673 server_loop(pid, ptyfd, fdout, -1);
674 /* server_loop _has_ closed ptyfd and fdout. */
675 session_pty_cleanup(s);
680 get_remote_name_or_ip(void)
682 static const char *remote = "";
684 remote = get_canonical_hostname(options.reverse_mapping_check);
685 if (utmp_len == 0 || strlen(remote) > utmp_len)
686 remote = get_remote_ipaddr();
690 /* administrative, login(1)-like work */
692 do_login(Session *s, const char *command)
697 char hostname[MAXHOSTNAMELEN];
699 struct sockaddr_storage from;
701 time_t last_login_time;
702 struct passwd * pw = s->pw;
703 pid_t pid = getpid();
706 * Get IP address of client. If the connection is not a socket, let
707 * the address be 0.0.0.0.
709 memset(&from, 0, sizeof(from));
710 if (packet_connection_is_on_socket()) {
711 fromlen = sizeof(from);
712 if (getpeername(packet_get_connection_in(),
713 (struct sockaddr *) & from, &fromlen) < 0) {
714 debug("getpeername: %.100s", strerror(errno));
719 /* Get the time and hostname when the user last logged in. */
721 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
722 hostname, sizeof(hostname));
724 /* Record that there was a login on that tty from the remote host. */
725 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
726 get_remote_name_or_ip(), (struct sockaddr *)&from);
730 * If password change is needed, do it now.
731 * This needs to occur before the ~/.hushlogin check.
733 if (is_pam_password_change_required()) {
734 print_pam_messages();
739 /* Done if .hushlogin exists or a command given. */
742 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
743 #ifdef HAVE_LOGIN_CAP
744 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
746 if (stat(buf, &st) >= 0)
751 if (!is_pam_password_change_required())
752 print_pam_messages();
754 #ifdef WITH_AIXAUTHENTICATE
755 if (aixloginmsg && *aixloginmsg)
756 printf("%s\n", aixloginmsg);
757 #endif /* WITH_AIXAUTHENTICATE */
759 if (last_login_time != 0) {
760 time_string = ctime(&last_login_time);
761 if (strchr(time_string, '\n'))
762 *strchr(time_string, '\n') = 0;
763 if (strcmp(hostname, "") == 0)
764 printf("Last login: %s\r\n", time_string);
766 printf("Last login: %s from %s\r\n", time_string, hostname);
768 if (options.print_motd) {
769 #ifdef HAVE_LOGIN_CAP
770 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
773 f = fopen("/etc/motd", "r");
776 while (fgets(buf, sizeof(buf), f))
784 * Sets the value of the given variable in the environment. If the variable
785 * already exists, its value is overriden.
788 child_set_env(char ***envp, u_int *envsizep, const char *name,
795 * Find the slot where the value should be stored. If the variable
796 * already exists, we reuse the slot; otherwise we append a new slot
797 * at the end of the array, expanding if necessary.
800 namelen = strlen(name);
801 for (i = 0; env[i]; i++)
802 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
805 /* Reuse the slot. */
808 /* New variable. Expand if necessary. */
809 if (i >= (*envsizep) - 1) {
811 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
813 /* Need to set the NULL pointer at end of array beyond the new slot. */
817 /* Allocate space and format the variable in the appropriate slot. */
818 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
819 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
823 * Reads environment variables from the given file and adds/overrides them
824 * into the environment. If the file does not exist, this does nothing.
825 * Otherwise, it must consist of empty lines, comments (line starts with '#')
826 * and assignments of the form name=value. No other forms are allowed.
829 read_environment_file(char ***env, u_int *envsize,
830 const char *filename)
836 f = fopen(filename, "r");
840 while (fgets(buf, sizeof(buf), f)) {
841 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
843 if (!*cp || *cp == '#' || *cp == '\n')
845 if (strchr(cp, '\n'))
846 *strchr(cp, '\n') = '\0';
847 value = strchr(cp, '=');
849 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
853 * Replace the equals sign by nul, and advance value to
858 child_set_env(env, envsize, cp, value);
865 * Sets any environment variables which have been specified by PAM
867 void do_pam_environment(char ***env, int *envsize)
869 char *equals, var_name[512], var_val[512];
873 if ((pam_env = fetch_pam_environment()) == NULL)
876 for(i = 0; pam_env[i] != NULL; i++) {
877 if ((equals = strstr(pam_env[i], "=")) == NULL)
880 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
881 memset(var_name, '\0', sizeof(var_name));
882 memset(var_val, '\0', sizeof(var_val));
884 strncpy(var_name, pam_env[i], equals - pam_env[i]);
885 strcpy(var_val, equals + 1);
887 debug3("PAM environment: %s=%s", var_name, var_val);
889 child_set_env(env, envsize, var_name, var_val);
896 void copy_environment(char ***env, int *envsize)
898 char *equals, var_name[512], var_val[512];
901 for(i = 0; environ[i] != NULL; i++) {
902 if ((equals = strstr(environ[i], "=")) == NULL)
905 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
906 memset(var_name, '\0', sizeof(var_name));
907 memset(var_val, '\0', sizeof(var_val));
909 strncpy(var_name, environ[i], equals - environ[i]);
910 strcpy(var_val, equals + 1);
912 debug3("Copy environment: %s=%s", var_name, var_val);
914 child_set_env(env, envsize, var_name, var_val);
920 #if defined(HAVE_GETUSERATTR)
922 * AIX-specific login initialisation
924 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
929 getrlimit(resource, &rlim);
932 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
934 rlim.rlim_cur = RLIM_INFINITY;
935 } else if (slim != 0) {
936 /* See the wackiness below */
937 if (rlim.rlim_cur == slim * mult)
940 rlim.rlim_cur = slim * mult;
945 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
947 rlim.rlim_max = RLIM_INFINITY;
948 } else if (hlim != 0) {
949 rlim.rlim_max = hlim * mult;
954 * XXX For cpu and fsize the soft limit is set to the hard limit
955 * if the hard limit is left at its default value and the soft limit
956 * is changed from its default value, either by requesting it
957 * (slim == 0) or by setting it to the current default. At least
958 * that's how rlogind does it. If you're confused you're not alone.
959 * Bug or feature? AIX 4.3.1.2
961 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
962 && hlim == 0 && slim != 0)
963 rlim.rlim_max = rlim.rlim_cur;
964 /* A specified hard limit limits the soft limit */
965 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
966 rlim.rlim_cur = rlim.rlim_max;
967 /* A soft limit can increase a hard limit */
968 else if (rlim.rlim_cur > rlim.rlim_max)
969 rlim.rlim_max = rlim.rlim_cur;
971 if (setrlimit(resource, &rlim) != 0)
972 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
975 void set_limits_from_userattr(char *user)
980 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
981 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
982 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
983 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
984 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
985 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
986 #if defined(S_UNOFILE)
987 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
990 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
991 /* Convert decimal to octal */
992 (void) snprintf(buf, sizeof(buf), "%d", mask);
993 if (sscanf(buf, "%o", &mask) == 1)
997 #endif /* defined(HAVE_GETUSERATTR) */
1000 * Performs common processing for the child, such as setting up the
1001 * environment, closing extra file descriptors, setting the user and group
1002 * ids, and executing the command or shell.
1005 do_child(const char *command, struct passwd * pw, const char *term,
1006 const char *display, const char *auth_proto,
1007 const char *auth_data, const char *ttyname)
1009 const char *shell, *hostname = NULL, *cp = NULL;
1015 extern char **environ;
1018 #ifdef WITH_IRIX_PROJECT
1020 #endif /* WITH_IRIX_PROJECT */
1021 #ifdef WITH_IRIX_JOBS
1024 #ifdef WITH_IRIX_ARRAY
1026 #endif /* WITH_IRIX_ARRAY */
1027 #endif /* WITH_IRIX_JOBS */
1030 /* login(1) is only called if we execute the login shell */
1031 if (options.use_login && command != NULL)
1032 options.use_login = 0;
1034 #ifndef USE_PAM /* pam_nologin handles this */
1035 if (!options.use_login) {
1036 # ifdef HAVE_LOGIN_CAP
1037 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1038 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1039 _PATH_NOLOGIN), "r");
1040 # else /* HAVE_LOGIN_CAP */
1042 f = fopen(_PATH_NOLOGIN, "r");
1043 # endif /* HAVE_LOGIN_CAP */
1045 /* /etc/nologin exists. Print its contents and exit. */
1046 while (fgets(buf, sizeof(buf), f))
1052 #endif /* USE_PAM */
1054 /* Set login name, uid, gid, and groups. */
1055 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1056 switch, so we let login(1) to this for us. */
1057 if (!options.use_login) {
1059 session_setup_sia(pw->pw_name, ttyname);
1060 #else /* HAVE_OSF_SIA */
1064 if (getuid() == 0 || geteuid() == 0) {
1066 # ifdef HAVE_GETUSERATTR
1067 set_limits_from_userattr(pw->pw_name);
1068 # endif /* HAVE_GETUSERATTR */
1069 # ifdef HAVE_LOGIN_CAP
1070 if (setusercontext(lc, pw, pw->pw_uid,
1071 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1072 perror("unable to set user context");
1076 if (auth_approval(NULL, lc, pw->pw_name, "ssh") <= 0) {
1077 error("approval failure for %s", pw->pw_name);
1078 fprintf(stderr, "Approval failure");
1082 # else /* HAVE_LOGIN_CAP */
1083 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1084 /* Sets login uid for accounting */
1085 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1086 error("setluid: %s", strerror(errno));
1087 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1089 if (setlogin(pw->pw_name) < 0)
1090 error("setlogin failed: %s", strerror(errno));
1091 if (setgid(pw->pw_gid) < 0) {
1095 /* Initialize the group list. */
1096 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1097 perror("initgroups");
1101 # ifdef WITH_IRIX_JOBS
1102 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1104 fatal("Failed to create job container: %.100s",
1107 # endif /* WITH_IRIX_JOBS */
1108 # ifdef WITH_IRIX_ARRAY
1109 /* initialize array session */
1111 if (newarraysess() != 0)
1112 fatal("Failed to set up new array session: %.100s",
1115 # endif /* WITH_IRIX_ARRAY */
1116 # ifdef WITH_IRIX_PROJECT
1117 /* initialize irix project info */
1118 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1119 debug("Failed to get project id, using projid 0");
1122 if (setprid(projid))
1123 fatal("Failed to initialize project %d for %s: %.100s",
1124 (int)projid, pw->pw_name, strerror(errno));
1125 # endif /* WITH_IRIX_PROJECT */
1126 #ifdef WITH_IRIX_AUDIT
1127 if (sysconf(_SC_AUDIT)) {
1128 debug("Setting sat id to %d", (int) pw->pw_uid);
1129 if (satsetid(pw->pw_uid))
1130 debug("error setting satid: %.100s", strerror(errno));
1132 #endif /* WITH_IRIX_AUDIT */
1134 /* Permanently switch to the desired uid. */
1135 permanently_set_uid(pw->pw_uid);
1136 # endif /* HAVE_LOGIN_CAP */
1138 #endif /* HAVE_OSF_SIA */
1143 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1144 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1147 * Get the shell from the password data. An empty shell field is
1148 * legal, and means /bin/sh.
1150 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1151 #ifdef HAVE_LOGIN_CAP
1152 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1156 /* Try to get AFS tokens for the local cell. */
1160 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1161 krb_afslog(cell, 0);
1167 /* Initialize the environment. */
1169 env = xmalloc(envsize * sizeof(char *));
1174 * The Windows environment contains some setting which are
1175 * important for a running system. They must not be dropped.
1177 copy_environment(&env, &envsize);
1180 if (!options.use_login) {
1181 /* Set basic environment. */
1182 child_set_env(&env, &envsize, "USER", pw->pw_name);
1183 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1184 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1185 #ifdef HAVE_LOGIN_CAP
1186 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1187 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1188 #else /* HAVE_LOGIN_CAP */
1189 # ifndef HAVE_CYGWIN
1191 * There's no standard path on Windows. The path contains
1192 * important components pointing to the system directories,
1193 * needed for loading shared libraries. So the path better
1194 * remains intact here.
1196 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1197 # endif /* HAVE_CYGWIN */
1198 #endif /* HAVE_LOGIN_CAP */
1200 snprintf(buf, sizeof buf, "%.200s/%.50s",
1201 _PATH_MAILDIR, pw->pw_name);
1202 child_set_env(&env, &envsize, "MAIL", buf);
1204 /* Normal systems set SHELL by default. */
1205 child_set_env(&env, &envsize, "SHELL", shell);
1208 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1210 /* Set custom environment options from RSA authentication. */
1211 while (custom_environment) {
1212 struct envstring *ce = custom_environment;
1215 for (i = 0; s[i] != '=' && s[i]; i++);
1218 child_set_env(&env, &envsize, s, s + i + 1);
1220 custom_environment = ce->next;
1225 snprintf(buf, sizeof buf, "%.50s %d %d",
1226 get_remote_ipaddr(), get_remote_port(), get_local_port());
1227 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1230 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1232 child_set_env(&env, &envsize, "TERM", term);
1234 child_set_env(&env, &envsize, "DISPLAY", display);
1235 if (original_command)
1236 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1240 if ((cp = getenv("AUTHSTATE")) != NULL)
1241 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1242 if ((cp = getenv("KRB5CCNAME")) != NULL)
1243 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1244 read_environment_file(&env, &envsize, "/etc/environment");
1249 extern char *ticket;
1252 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1257 /* Pull in any environment variables that may have been set by PAM. */
1258 do_pam_environment(&env, &envsize);
1259 #endif /* USE_PAM */
1262 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1263 if (auth_get_socket_name() != NULL)
1264 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1265 auth_get_socket_name());
1267 /* read $HOME/.ssh/environment. */
1268 if (!options.use_login) {
1269 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1271 read_environment_file(&env, &envsize, buf);
1274 /* dump the environment */
1275 fprintf(stderr, "Environment:\n");
1276 for (i = 0; env[i]; i++)
1277 fprintf(stderr, " %.200s\n", env[i]);
1279 /* we have to stash the hostname before we close our socket. */
1280 if (options.use_login)
1281 hostname = get_remote_name_or_ip();
1283 * Close the connection descriptors; note that this is the child, and
1284 * the server will still have the socket open, and it is important
1285 * that we do not shutdown it. Note that the descriptors cannot be
1286 * closed before building the environment, as we call
1287 * get_remote_ipaddr there.
1289 if (packet_get_connection_in() == packet_get_connection_out())
1290 close(packet_get_connection_in());
1292 close(packet_get_connection_in());
1293 close(packet_get_connection_out());
1296 * Close all descriptors related to channels. They will still remain
1297 * open in the parent.
1299 /* XXX better use close-on-exec? -markus */
1300 channel_close_all();
1303 * Close any extra file descriptors. Note that there may still be
1304 * descriptors left by system functions. They will be closed later.
1309 * Close any extra open file descriptors so that we don\'t have them
1310 * hanging around in clients. Note that we want to do this after
1311 * initgroups, because at least on Solaris 2.3 it leaves file
1314 for (i = 3; i < 64; i++)
1317 /* Change current directory to the user\'s home directory. */
1318 if (chdir(pw->pw_dir) < 0) {
1319 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1320 pw->pw_dir, strerror(errno));
1321 #ifdef HAVE_LOGIN_CAP
1322 if (login_getcapbool(lc, "requirehome", 0))
1328 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1329 * xauth are run in the proper environment.
1334 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1337 if (!options.use_login) {
1338 if (stat(_PATH_SSH_USER_RC, &st) >= 0) {
1340 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, _PATH_SSH_USER_RC);
1342 f = popen(_PATH_BSHELL " " _PATH_SSH_USER_RC, "w");
1344 if (auth_proto != NULL && auth_data != NULL)
1345 fprintf(f, "%s %s\n", auth_proto, auth_data);
1348 fprintf(stderr, "Could not run %s\n", _PATH_SSH_USER_RC);
1349 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1351 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, _PATH_SSH_SYSTEM_RC);
1353 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1355 if (auth_proto != NULL && auth_data != NULL)
1356 fprintf(f, "%s %s\n", auth_proto, auth_data);
1359 fprintf(stderr, "Could not run %s\n", _PATH_SSH_SYSTEM_RC);
1360 } else if (options.xauth_location != NULL) {
1361 /* Add authority data to .Xauthority if appropriate. */
1362 if (auth_proto != NULL && auth_data != NULL) {
1363 char *screen = strchr(display, ':');
1366 "Running %.100s add %.100s %.100s %.100s\n",
1367 options.xauth_location, display,
1368 auth_proto, auth_data);
1369 #ifndef NO_X11_UNIX_SOCKETS
1372 "Adding %.*s/unix%s %s %s\n",
1373 (int)(screen-display), display,
1374 screen, auth_proto, auth_data);
1375 #endif /* NO_X11_UNIX_SOCKETS */
1377 snprintf(cmd, sizeof cmd, "%s -q -",
1378 options.xauth_location);
1379 f = popen(cmd, "w");
1381 fprintf(f, "add %s %s %s\n", display,
1382 auth_proto, auth_data);
1383 #ifndef NO_X11_UNIX_SOCKETS
1385 fprintf(f, "add %.*s/unix%s %s %s\n",
1386 (int)(screen-display), display,
1387 screen, auth_proto, auth_data);
1388 #endif /* NO_X11_UNIX_SOCKETS */
1391 fprintf(stderr, "Could not run %s\n",
1396 /* Get the last component of the shell name. */
1397 cp = strrchr(shell, '/');
1404 * If we have no command, execute the shell. In this case, the shell
1405 * name to be passed in argv[0] is preceded by '-' to indicate that
1406 * this is a login shell.
1409 if (!options.use_login) {
1413 * Check for mail if we have a tty and it was enabled
1414 * in server options.
1416 if (ttyname && options.check_mail) {
1418 struct stat mailstat;
1419 mailbox = getenv("MAIL");
1420 if (mailbox != NULL) {
1421 if (stat(mailbox, &mailstat) != 0 ||
1422 mailstat.st_size == 0)
1423 printf("No mail.\n");
1424 else if (mailstat.st_mtime < mailstat.st_atime)
1425 printf("You have mail.\n");
1427 printf("You have new mail.\n");
1430 /* Start the shell. Set initial character to '-'. */
1432 strncpy(buf + 1, cp, sizeof(buf) - 1);
1433 buf[sizeof(buf) - 1] = 0;
1435 /* Execute the shell. */
1438 execve(shell, argv, env);
1440 /* Executing the shell failed. */
1445 /* Launch login(1). */
1447 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1448 "-p", "-f", "--", pw->pw_name, NULL);
1450 /* Login couldn't be executed, die. */
1457 * Execute the command using the user's shell. This uses the -c
1458 * option to execute the command.
1460 argv[0] = (char *) cp;
1462 argv[2] = (char *) command;
1464 execve(shell, argv, env);
1473 static int did_init = 0;
1475 debug("session_new: init");
1476 for(i = 0; i < MAX_SESSIONS; i++) {
1477 sessions[i].used = 0;
1478 sessions[i].self = i;
1482 for(i = 0; i < MAX_SESSIONS; i++) {
1483 Session *s = &sessions[i];
1494 s->auth_data = NULL;
1495 s->auth_proto = NULL;
1498 debug("session_new: session %d", i);
1509 for(i = 0; i < MAX_SESSIONS; i++) {
1510 Session *s = &sessions[i];
1511 debug("dump: used %d session %d %p channel %d pid %d",
1521 session_open(int chanid)
1523 Session *s = session_new();
1524 debug("session_open: channel %d", chanid);
1526 error("no more sessions");
1529 s->pw = auth_get_user();
1531 fatal("no user for session %d", s->self);
1532 debug("session_open: session %d: link with channel %d", s->self, chanid);
1538 session_by_channel(int id)
1541 for(i = 0; i < MAX_SESSIONS; i++) {
1542 Session *s = &sessions[i];
1543 if (s->used && s->chanid == id) {
1544 debug("session_by_channel: session %d channel %d", i, id);
1548 debug("session_by_channel: unknown channel %d", id);
1554 session_by_pid(pid_t pid)
1557 debug("session_by_pid: pid %d", pid);
1558 for(i = 0; i < MAX_SESSIONS; i++) {
1559 Session *s = &sessions[i];
1560 if (s->used && s->pid == pid)
1563 error("session_by_pid: unknown pid %d", pid);
1569 session_window_change_req(Session *s)
1571 s->col = packet_get_int();
1572 s->row = packet_get_int();
1573 s->xpixel = packet_get_int();
1574 s->ypixel = packet_get_int();
1576 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1581 session_pty_req(Session *s)
1584 char *term_modes; /* encoded terminal modes */
1590 s->term = packet_get_string(&len);
1591 s->col = packet_get_int();
1592 s->row = packet_get_int();
1593 s->xpixel = packet_get_int();
1594 s->ypixel = packet_get_int();
1595 term_modes = packet_get_string(&len);
1598 if (strcmp(s->term, "") == 0) {
1602 /* Allocate a pty and open it. */
1603 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1608 error("session_pty_req: session %d alloc failed", s->self);
1612 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1614 * Add a cleanup function to clear the utmp entry and record logout
1615 * time in case we call fatal() (e.g., the connection gets closed).
1617 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1618 pty_setowner(s->pw, s->tty);
1619 /* Get window size from the packet. */
1620 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1622 session_proctitle(s);
1624 /* XXX parse and set terminal modes */
1630 session_subsystem_req(Session *s)
1634 char *subsys = packet_get_string(&len);
1638 log("subsystem request for %s", subsys);
1640 for (i = 0; i < options.num_subsystems; i++) {
1641 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1642 debug("subsystem: exec() %s", options.subsystem_command[i]);
1643 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1649 log("subsystem request for %s failed, subsystem not found", subsys);
1656 session_x11_req(Session *s)
1659 if (no_x11_forwarding_flag) {
1660 debug("X11 forwarding disabled in user configuration file.");
1663 if (!options.x11_forwarding) {
1664 debug("X11 forwarding disabled in server configuration file.");
1667 if (xauthfile != NULL) {
1668 debug("X11 fwd already started.");
1672 debug("Received request for X11 forwarding with auth spoofing.");
1673 if (s->display != NULL)
1674 packet_disconnect("Protocol error: X11 display already set.");
1676 s->single_connection = packet_get_char();
1677 s->auth_proto = packet_get_string(NULL);
1678 s->auth_data = packet_get_string(NULL);
1679 s->screen = packet_get_int();
1682 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1683 if (s->display == NULL) {
1684 xfree(s->auth_proto);
1685 xfree(s->auth_data);
1688 xauthfile = xmalloc(MAXPATHLEN);
1689 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1690 temporarily_use_uid(s->pw->pw_uid);
1691 if (mkdtemp(xauthfile) == NULL) {
1693 error("private X11 dir: mkdtemp %s failed: %s",
1694 xauthfile, strerror(errno));
1697 xfree(s->auth_proto);
1698 xfree(s->auth_data);
1699 /* XXXX remove listening channels */
1702 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1703 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1707 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1712 session_shell_req(Session *s)
1714 /* if forced_command == NULL, the shell is execed */
1715 char *shell = forced_command;
1719 do_exec_no_pty(s, shell, s->pw);
1721 do_exec_pty(s, shell, s->pw);
1726 session_exec_req(Session *s)
1729 char *command = packet_get_string(&len);
1731 if (forced_command) {
1732 original_command = command;
1733 command = forced_command;
1734 debug("Forced command '%.500s'", forced_command);
1738 do_exec_no_pty(s, command, s->pw);
1740 do_exec_pty(s, command, s->pw);
1741 if (forced_command == NULL)
1747 session_auth_agent_req(Session *s)
1749 static int called = 0;
1751 if (no_agent_forwarding_flag) {
1752 debug("session_auth_agent_req: no_agent_forwarding_flag");
1759 return auth_input_request_forwarding(s->pw);
1764 session_input_channel_req(int id, void *arg)
1773 rtype = packet_get_string(&len);
1774 reply = packet_get_char();
1776 s = session_by_channel(id);
1778 fatal("session_input_channel_req: channel %d: no session", id);
1779 c = channel_lookup(id);
1781 fatal("session_input_channel_req: channel %d: bad channel", id);
1783 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1784 s->self, id, rtype, reply);
1787 * a session is in LARVAL state until a shell
1788 * or programm is executed
1790 if (c->type == SSH_CHANNEL_LARVAL) {
1791 if (strcmp(rtype, "shell") == 0) {
1792 success = session_shell_req(s);
1793 } else if (strcmp(rtype, "exec") == 0) {
1794 success = session_exec_req(s);
1795 } else if (strcmp(rtype, "pty-req") == 0) {
1796 success = session_pty_req(s);
1797 } else if (strcmp(rtype, "x11-req") == 0) {
1798 success = session_x11_req(s);
1799 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1800 success = session_auth_agent_req(s);
1801 } else if (strcmp(rtype, "subsystem") == 0) {
1802 success = session_subsystem_req(s);
1805 if (strcmp(rtype, "window-change") == 0) {
1806 success = session_window_change_req(s);
1810 packet_start(success ?
1811 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1812 packet_put_int(c->remote_id);
1819 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1822 fatal("session_set_fds: called for proto != 2.0");
1824 * now that have a child and a pipe to the child,
1825 * we can activate our channel and register the fd's
1827 if (s->chanid == -1)
1828 fatal("no channel for session %d", s->self);
1829 channel_set_fds(s->chanid,
1831 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1836 session_pty_cleanup(Session *s)
1838 if (s == NULL || s->ttyfd == -1)
1841 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1843 /* Cancel the cleanup function. */
1844 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1846 /* Record that the user has logged out. */
1847 record_logout(s->pid, s->tty);
1849 /* Release the pseudo-tty. */
1850 pty_release(s->tty);
1853 * Close the server side of the socket pairs. We must do this after
1854 * the pty cleanup, so that another process doesn't get this pty
1855 * while we're still cleaning up.
1857 if (close(s->ptymaster) < 0)
1858 error("close(s->ptymaster): %s", strerror(errno));
1862 session_exit_message(Session *s, int status)
1866 fatal("session_close: no session");
1867 c = channel_lookup(s->chanid);
1869 fatal("session_close: session %d: no channel %d",
1870 s->self, s->chanid);
1871 debug("session_exit_message: session %d channel %d pid %d",
1872 s->self, s->chanid, s->pid);
1874 if (WIFEXITED(status)) {
1875 channel_request_start(s->chanid,
1877 packet_put_int(WEXITSTATUS(status));
1879 } else if (WIFSIGNALED(status)) {
1880 channel_request_start(s->chanid,
1882 packet_put_int(WTERMSIG(status));
1884 packet_put_char(WCOREDUMP(status));
1885 #else /* WCOREDUMP */
1887 #endif /* WCOREDUMP */
1888 packet_put_cstring("");
1889 packet_put_cstring("");
1892 /* Some weird exit cause. Just exit. */
1893 packet_disconnect("wait returned status %04x.", status);
1896 /* disconnect channel */
1897 debug("session_exit_message: release channel %d", s->chanid);
1898 channel_cancel_cleanup(s->chanid);
1900 * emulate a write failure with 'chan_write_failed', nobody will be
1901 * interested in data we write.
1902 * Note that we must not call 'chan_read_failed', since there could
1903 * be some more data waiting in the pipe.
1905 if (c->ostate != CHAN_OUTPUT_CLOSED)
1906 chan_write_failed(c);
1911 session_free(Session *s)
1913 debug("session_free: session %d pid %d", s->self, s->pid);
1919 xfree(s->auth_data);
1921 xfree(s->auth_proto);
1926 session_close(Session *s)
1928 session_pty_cleanup(s);
1930 session_proctitle(s);
1934 session_close_by_pid(pid_t pid, int status)
1936 Session *s = session_by_pid(pid);
1938 debug("session_close_by_pid: no session for pid %d", s->pid);
1941 if (s->chanid != -1)
1942 session_exit_message(s, status);
1947 * this is called when a channel dies before
1948 * the session 'child' itself dies
1951 session_close_by_channel(int id, void *arg)
1953 Session *s = session_by_channel(id);
1955 debug("session_close_by_channel: no session for channel %d", id);
1958 /* disconnect channel */
1959 channel_cancel_cleanup(s->chanid);
1962 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1964 /* close session immediately */
1967 /* notify child, delay session cleanup */
1968 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1969 error("session_close_by_channel: kill %d: %s",
1970 s->pid, strerror(errno));
1975 session_tty_list(void)
1977 static char buf[1024];
1980 for(i = 0; i < MAX_SESSIONS; i++) {
1981 Session *s = &sessions[i];
1982 if (s->used && s->ttyfd != -1) {
1984 strlcat(buf, ",", sizeof buf);
1985 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1989 strlcpy(buf, "notty", sizeof buf);
1994 session_proctitle(Session *s)
1997 error("no user for session %d", s->self);
1999 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2003 do_authenticated2(Authctxt *authctxt)
2006 * Cancel the alarm we set to limit the time taken for
2010 if (startup_pipe != -1) {
2011 close(startup_pipe);
2014 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
2015 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
2016 error("unable to get login class");
2022 xauthfile_cleanup_proc(NULL);