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, 2001 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.111 2001/12/06 18:09:23 stevesk Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
60 #ifdef WITH_IRIX_PROJECT
62 #endif /* WITH_IRIX_PROJECT */
64 #include <sys/resource.h>
66 #ifdef WITH_IRIX_AUDIT
68 #endif /* WITH_IRIX_AUDIT */
70 #if defined(HAVE_USERSEC_H)
76 #include <sys/cygwin.h>
77 #define is_winnt (GetVersion() < 0x80000000)
81 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
82 # define S_UFSIZE_HARD S_UFSIZE "_hard"
83 # define S_UCPU_HARD S_UCPU "_hard"
84 # define S_UDATA_HARD S_UDATA "_hard"
85 # define S_USTACK_HARD S_USTACK "_hard"
86 # define S_URSS_HARD S_URSS "_hard"
87 # define S_UCORE_HARD S_UCORE "_hard"
88 # define S_UNOFILE_HARD S_UNOFILE "_hard"
98 typedef struct Session Session;
107 int ptyfd, ttyfd, ptymaster;
108 int row, col, xpixel, ypixel;
114 char *auth_display[2];
117 int single_connection;
125 Session *session_new(void);
126 void session_set_fds(Session *, int, int, int);
127 static void session_pty_cleanup(void *);
128 void session_proctitle(Session *);
129 int session_setup_x11fwd(Session *);
130 void do_exec_pty(Session *, const char *);
131 void do_exec_no_pty(Session *, const char *);
132 void do_exec(Session *, const char *);
133 void do_login(Session *, const char *);
134 #ifdef LOGIN_NEEDS_UTMPX
135 static void do_pre_login(Session *s);
137 void do_child(Session *, const char *);
139 int check_quietlogin(Session *, const char *);
141 static void do_authenticated1(Authctxt *);
142 static void do_authenticated2(Authctxt *);
144 static void session_close(Session *);
145 static int session_pty_req(Session *);
148 extern ServerOptions options;
149 extern char *__progname;
150 extern int log_stderr;
151 extern int debug_flag;
152 extern u_int utmp_len;
153 extern int startup_pipe;
154 extern void destroy_sensitive_data(void);
156 /* original command from peer. */
157 const char *original_command = NULL;
160 #define MAX_SESSIONS 10
161 Session sessions[MAX_SESSIONS];
163 #ifdef WITH_AIXAUTHENTICATE
165 #endif /* WITH_AIXAUTHENTICATE */
167 #ifdef HAVE_LOGIN_CAP
168 static login_cap_t *lc;
172 do_authenticated(Authctxt *authctxt)
175 * Cancel the alarm we set to limit the time taken for
179 if (startup_pipe != -1) {
183 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
184 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
185 error("unable to get login class");
189 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
190 packet_disconnect("Approval failure for %s",
191 authctxt->pw->pw_name);
195 #ifdef WITH_AIXAUTHENTICATE
196 /* We don't have a pty yet, so just label the line as "ssh" */
197 if (loginsuccess(authctxt->user,
198 get_canonical_hostname(options.reverse_mapping_check),
199 "ssh", &aixloginmsg) < 0)
201 #endif /* WITH_AIXAUTHENTICATE */
203 /* setup the channel layer */
204 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
205 channel_permit_all_opens();
208 do_authenticated2(authctxt);
210 do_authenticated1(authctxt);
212 /* remove agent socket */
213 if (auth_get_socket_name())
214 auth_sock_cleanup_proc(authctxt->pw);
216 if (options.kerberos_ticket_cleanup)
217 krb4_cleanup_proc(authctxt);
220 if (options.kerberos_ticket_cleanup)
221 krb5_cleanup_proc(authctxt);
226 * Prepares for an interactive session. This is called after the user has
227 * been successfully authenticated. During this message exchange, pseudo
228 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
229 * are requested, etc.
232 do_authenticated1(Authctxt *authctxt)
236 int success, type, plen, screen_flag;
237 int compression_level = 0, enable_compression_after_reply = 0;
238 u_int proto_len, data_len, dlen;
241 s->authctxt = authctxt;
242 s->pw = authctxt->pw;
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:
270 success = session_pty_req(s);
273 case SSH_CMSG_X11_REQUEST_FORWARDING:
274 s->auth_proto = packet_get_string(&proto_len);
275 s->auth_data = packet_get_string(&data_len);
277 screen_flag = packet_get_protocol_flags() &
278 SSH_PROTOFLAG_SCREEN_NUMBER;
279 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
281 if (packet_remaining() == 4) {
283 debug2("Buggy client: "
284 "X11 screen flag missing");
285 s->screen = packet_get_int();
290 success = session_setup_x11fwd(s);
292 xfree(s->auth_proto);
294 s->auth_proto = NULL;
299 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
300 if (no_agent_forwarding_flag || compat13) {
301 debug("Authentication agent forwarding not permitted for this authentication.");
304 debug("Received authentication agent forwarding request.");
305 success = auth_input_request_forwarding(s->pw);
308 case SSH_CMSG_PORT_FORWARD_REQUEST:
309 if (no_port_forwarding_flag) {
310 debug("Port forwarding not permitted for this authentication.");
313 if (!options.allow_tcp_forwarding) {
314 debug("Port forwarding not permitted.");
317 debug("Received TCP/IP port forwarding request.");
318 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
322 case SSH_CMSG_MAX_PACKET_SIZE:
323 if (packet_set_maxsize(packet_get_int()) > 0)
327 #if defined(AFS) || defined(KRB5)
328 case SSH_CMSG_HAVE_KERBEROS_TGT:
329 if (!options.kerberos_tgt_passing) {
330 verbose("Kerberos TGT passing disabled.");
332 char *kdata = packet_get_string(&dlen);
333 packet_integrity_check(plen, 4 + dlen, type);
335 /* XXX - 0x41, see creds_to_radix version */
336 if (kdata[0] != 0x41) {
342 if (auth_krb5_tgt(s->authctxt, &tgt))
345 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
349 if (auth_krb4_tgt(s->authctxt, kdata))
352 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
358 #endif /* AFS || KRB5 */
361 case SSH_CMSG_HAVE_AFS_TOKEN:
362 if (!options.afs_token_passing || !k_hasafs()) {
363 verbose("AFS token passing disabled.");
365 /* Accept AFS token. */
366 char *token = packet_get_string(&dlen);
367 packet_integrity_check(plen, 4 + dlen, type);
369 if (auth_afs_token(s->authctxt, token))
372 verbose("AFS token refused for %.100s",
379 case SSH_CMSG_EXEC_SHELL:
380 case SSH_CMSG_EXEC_CMD:
381 if (type == SSH_CMSG_EXEC_CMD) {
382 command = packet_get_string(&dlen);
383 debug("Exec command '%.500s'", command);
395 * Any unknown messages in this phase are ignored,
396 * and a failure message is returned.
398 log("Unknown packet type received after authentication: %d", type);
400 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
404 /* Enable compression now that we have replied if appropriate. */
405 if (enable_compression_after_reply) {
406 enable_compression_after_reply = 0;
407 packet_start_compression(compression_level);
413 * This is called to fork and execute a command when we have no tty. This
414 * will call do_child from the child, and server_loop from the parent after
415 * setting up file descriptors and such.
418 do_exec_no_pty(Session *s, const char *command)
423 int pin[2], pout[2], perr[2];
424 /* Allocate pipes for communicating with the program. */
425 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
426 packet_disconnect("Could not create pipes: %.100s",
428 #else /* USE_PIPES */
429 int inout[2], err[2];
430 /* Uses socket pairs to communicate with the program. */
431 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
432 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
433 packet_disconnect("Could not create socket pairs: %.100s",
435 #endif /* USE_PIPES */
437 fatal("do_exec_no_pty: no session");
439 session_proctitle(s);
442 do_pam_session(s->pw->pw_name, NULL);
444 if (is_pam_password_change_required())
445 packet_disconnect("Password change required but no "
449 /* Fork the child. */
450 if ((pid = fork()) == 0) {
451 /* Child. Reinitialize the log since the pid has changed. */
452 log_init(__progname, options.log_level, options.log_facility, log_stderr);
455 * Create a new session and process group since the 4.4BSD
456 * setlogin() affects the entire process group.
459 error("setsid failed: %.100s", strerror(errno));
463 * Redirect stdin. We close the parent side of the socket
464 * pair, and make the child side the standard input.
467 if (dup2(pin[0], 0) < 0)
468 perror("dup2 stdin");
471 /* Redirect stdout. */
473 if (dup2(pout[1], 1) < 0)
474 perror("dup2 stdout");
477 /* Redirect stderr. */
479 if (dup2(perr[1], 2) < 0)
480 perror("dup2 stderr");
482 #else /* USE_PIPES */
484 * Redirect stdin, stdout, and stderr. Stdin and stdout will
485 * use the same socket, as some programs (particularly rdist)
486 * seem to depend on it.
490 if (dup2(inout[0], 0) < 0) /* stdin */
491 perror("dup2 stdin");
492 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
493 perror("dup2 stdout");
494 if (dup2(err[0], 2) < 0) /* stderr */
495 perror("dup2 stderr");
496 #endif /* USE_PIPES */
498 /* Do processing for the child (exec command etc). */
499 do_child(s, command);
504 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
507 packet_disconnect("fork failed: %.100s", strerror(errno));
509 /* Set interactive/non-interactive mode. */
510 packet_set_interactive(s->display != NULL);
512 /* We are the parent. Close the child sides of the pipes. */
518 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
520 /* Enter the interactive session. */
521 server_loop(pid, pin[1], pout[0], perr[0]);
522 /* server_loop has closed pin[1], pout[0], and perr[0]. */
524 #else /* USE_PIPES */
525 /* We are the parent. Close the child sides of the socket pairs. */
530 * Enter the interactive session. Note: server_loop must be able to
531 * handle the case that fdin and fdout are the same.
534 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
536 server_loop(pid, inout[1], inout[1], err[1]);
537 /* server_loop has closed inout[1] and err[1]. */
539 #endif /* USE_PIPES */
543 * This is called to fork and execute a command when we have a tty. This
544 * will call do_child from the child, and server_loop from the parent after
545 * setting up file descriptors, controlling tty, updating wtmp, utmp,
546 * lastlog, and other such operations.
549 do_exec_pty(Session *s, const char *command)
551 int fdout, ptyfd, ttyfd, ptymaster;
555 fatal("do_exec_pty: no session");
560 do_pam_session(s->pw->pw_name, s->tty);
564 /* Fork the child. */
565 if ((pid = fork()) == 0) {
567 /* Child. Reinitialize the log because the pid has changed. */
568 log_init(__progname, options.log_level, options.log_facility, log_stderr);
569 /* Close the master side of the pseudo tty. */
572 /* Make the pseudo tty our controlling tty. */
573 pty_make_controlling_tty(&ttyfd, s->tty);
575 /* Redirect stdin/stdout/stderr from the pseudo tty. */
576 if (dup2(ttyfd, 0) < 0)
577 error("dup2 stdin: %s", strerror(errno));
578 if (dup2(ttyfd, 1) < 0)
579 error("dup2 stdout: %s", strerror(errno));
580 if (dup2(ttyfd, 2) < 0)
581 error("dup2 stderr: %s", strerror(errno));
583 /* Close the extra descriptor for the pseudo tty. */
586 /* record login, etc. similar to login(1) */
588 if (!(options.use_login && command == NULL))
589 do_login(s, command);
590 # ifdef LOGIN_NEEDS_UTMPX
596 /* Do common processing for the child, such as execing the command. */
597 do_child(s, command);
602 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
605 packet_disconnect("fork failed: %.100s", strerror(errno));
608 /* Parent. Close the slave side of the pseudo tty. */
612 * Create another descriptor of the pty master side for use as the
613 * standard input. We could use the original descriptor, but this
614 * simplifies code in server_loop. The descriptor is bidirectional.
618 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
620 /* we keep a reference to the pty master */
621 ptymaster = dup(ptyfd);
623 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
624 s->ptymaster = ptymaster;
626 /* Enter interactive session. */
627 packet_set_interactive(1);
629 session_set_fds(s, ptyfd, fdout, -1);
631 server_loop(pid, ptyfd, fdout, -1);
632 /* server_loop _has_ closed ptyfd and fdout. */
636 #ifdef LOGIN_NEEDS_UTMPX
638 do_pre_login(Session *s)
641 struct sockaddr_storage from;
642 pid_t pid = getpid();
645 * Get IP address of client. If the connection is not a socket, let
646 * the address be 0.0.0.0.
648 memset(&from, 0, sizeof(from));
649 if (packet_connection_is_on_socket()) {
650 fromlen = sizeof(from);
651 if (getpeername(packet_get_connection_in(),
652 (struct sockaddr *) & from, &fromlen) < 0) {
653 debug("getpeername: %.100s", strerror(errno));
658 record_utmp_only(pid, s->tty, s->pw->pw_name,
659 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
660 (struct sockaddr *)&from);
665 * This is called to fork and execute a command. If another command is
666 * to be forced, execute that instead.
669 do_exec(Session *s, const char *command)
671 if (forced_command) {
672 original_command = command;
673 command = forced_command;
674 debug("Forced command '%.900s'", command);
678 do_exec_pty(s, command);
680 do_exec_no_pty(s, command);
682 original_command = NULL;
685 /* administrative, login(1)-like work */
687 do_login(Session *s, const char *command)
690 char hostname[MAXHOSTNAMELEN];
692 struct sockaddr_storage from;
693 time_t last_login_time;
694 struct passwd * pw = s->pw;
695 pid_t pid = getpid();
698 * Get IP address of client. If the connection is not a socket, let
699 * the address be 0.0.0.0.
701 memset(&from, 0, sizeof(from));
702 if (packet_connection_is_on_socket()) {
703 fromlen = sizeof(from);
704 if (getpeername(packet_get_connection_in(),
705 (struct sockaddr *) & from, &fromlen) < 0) {
706 debug("getpeername: %.100s", strerror(errno));
711 /* Get the time and hostname when the user last logged in. */
712 if (options.print_lastlog) {
714 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
715 hostname, sizeof(hostname));
718 /* Record that there was a login on that tty from the remote host. */
719 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
720 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
721 (struct sockaddr *)&from);
725 * If password change is needed, do it now.
726 * This needs to occur before the ~/.hushlogin check.
728 if (is_pam_password_change_required()) {
729 print_pam_messages();
734 if (check_quietlogin(s, command))
738 if (!is_pam_password_change_required())
739 print_pam_messages();
741 #ifdef WITH_AIXAUTHENTICATE
742 if (aixloginmsg && *aixloginmsg)
743 printf("%s\n", aixloginmsg);
744 #endif /* WITH_AIXAUTHENTICATE */
746 if (options.print_lastlog && last_login_time != 0) {
747 time_string = ctime(&last_login_time);
748 if (strchr(time_string, '\n'))
749 *strchr(time_string, '\n') = 0;
750 if (strcmp(hostname, "") == 0)
751 printf("Last login: %s\r\n", time_string);
753 printf("Last login: %s from %s\r\n", time_string, hostname);
760 * Display the message of the day.
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))
785 * Check for quiet login, either .hushlogin or command given.
788 check_quietlogin(Session *s, const char *command)
791 struct passwd *pw = s->pw;
794 /* Return 1 if .hushlogin exists or a command given. */
797 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
798 #ifdef HAVE_LOGIN_CAP
799 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
802 if (stat(buf, &st) >= 0)
809 * Sets the value of the given variable in the environment. If the variable
810 * already exists, its value is overriden.
813 child_set_env(char ***envp, u_int *envsizep, const char *name,
820 * Find the slot where the value should be stored. If the variable
821 * already exists, we reuse the slot; otherwise we append a new slot
822 * at the end of the array, expanding if necessary.
825 namelen = strlen(name);
826 for (i = 0; env[i]; i++)
827 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
830 /* Reuse the slot. */
833 /* New variable. Expand if necessary. */
834 if (i >= (*envsizep) - 1) {
836 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
838 /* Need to set the NULL pointer at end of array beyond the new slot. */
842 /* Allocate space and format the variable in the appropriate slot. */
843 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
844 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
848 * Reads environment variables from the given file and adds/overrides them
849 * into the environment. If the file does not exist, this does nothing.
850 * Otherwise, it must consist of empty lines, comments (line starts with '#')
851 * and assignments of the form name=value. No other forms are allowed.
854 read_environment_file(char ***env, u_int *envsize,
855 const char *filename)
861 f = fopen(filename, "r");
865 while (fgets(buf, sizeof(buf), f)) {
866 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
868 if (!*cp || *cp == '#' || *cp == '\n')
870 if (strchr(cp, '\n'))
871 *strchr(cp, '\n') = '\0';
872 value = strchr(cp, '=');
874 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
878 * Replace the equals sign by nul, and advance value to
883 child_set_env(env, envsize, cp, value);
890 * Sets any environment variables which have been specified by PAM
892 void do_pam_environment(char ***env, u_int *envsize)
894 char *equals, var_name[512], var_val[512];
898 if ((pam_env = fetch_pam_environment()) == NULL)
901 for(i = 0; pam_env[i] != NULL; i++) {
902 if ((equals = strstr(pam_env[i], "=")) == NULL)
905 if (strlen(pam_env[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, pam_env[i], equals - pam_env[i]);
910 strcpy(var_val, equals + 1);
912 debug3("PAM environment: %s=%s", var_name, var_val);
914 child_set_env(env, envsize, var_name, var_val);
921 void copy_environment(char ***env, u_int *envsize)
923 char *equals, var_name[512], var_val[512];
926 for(i = 0; environ[i] != NULL; i++) {
927 if ((equals = strstr(environ[i], "=")) == NULL)
930 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
931 memset(var_name, '\0', sizeof(var_name));
932 memset(var_val, '\0', sizeof(var_val));
934 strncpy(var_name, environ[i], equals - environ[i]);
935 strcpy(var_val, equals + 1);
937 debug3("Copy environment: %s=%s", var_name, var_val);
939 child_set_env(env, envsize, var_name, var_val);
945 #if defined(HAVE_GETUSERATTR)
947 * AIX-specific login initialisation
949 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
954 getrlimit(resource, &rlim);
957 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
959 rlim.rlim_cur = RLIM_INFINITY;
960 } else if (slim != 0) {
961 /* See the wackiness below */
962 if (rlim.rlim_cur == slim * mult)
965 rlim.rlim_cur = slim * mult;
970 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
972 rlim.rlim_max = RLIM_INFINITY;
973 } else if (hlim != 0) {
974 rlim.rlim_max = hlim * mult;
979 * XXX For cpu and fsize the soft limit is set to the hard limit
980 * if the hard limit is left at its default value and the soft limit
981 * is changed from its default value, either by requesting it
982 * (slim == 0) or by setting it to the current default. At least
983 * that's how rlogind does it. If you're confused you're not alone.
984 * Bug or feature? AIX 4.3.1.2
986 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
987 && hlim == 0 && slim != 0)
988 rlim.rlim_max = rlim.rlim_cur;
989 /* A specified hard limit limits the soft limit */
990 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
991 rlim.rlim_cur = rlim.rlim_max;
992 /* A soft limit can increase a hard limit */
993 else if (rlim.rlim_cur > rlim.rlim_max)
994 rlim.rlim_max = rlim.rlim_cur;
996 if (setrlimit(resource, &rlim) != 0)
997 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
1000 void set_limits_from_userattr(char *user)
1005 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
1006 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
1007 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
1008 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
1009 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
1010 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1011 #if defined(S_UNOFILE)
1012 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1015 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1016 /* Convert decimal to octal */
1017 (void) snprintf(buf, sizeof(buf), "%d", mask);
1018 if (sscanf(buf, "%o", &mask) == 1)
1022 #endif /* defined(HAVE_GETUSERATTR) */
1025 * Performs common processing for the child, such as setting up the
1026 * environment, closing extra file descriptors, setting the user and group
1027 * ids, and executing the command or shell.
1030 do_child(Session *s, const char *command)
1032 const char *shell, *hostname = NULL, *cp = NULL;
1033 struct passwd *pw = s->pw;
1039 extern char **environ;
1043 #ifdef WITH_IRIX_PROJECT
1045 #endif /* WITH_IRIX_PROJECT */
1046 #ifdef WITH_IRIX_JOBS
1049 #ifdef WITH_IRIX_ARRAY
1051 #endif /* WITH_IRIX_ARRAY */
1052 #endif /* WITH_IRIX_JOBS */
1055 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1057 /* remove hostkey from the child's memory */
1058 destroy_sensitive_data();
1060 /* login(1) is only called if we execute the login shell */
1061 if (options.use_login && command != NULL)
1062 options.use_login = 0;
1064 #if !defined(HAVE_OSF_SIA)
1065 if (!options.use_login) {
1066 # ifdef HAVE_LOGIN_CAP
1067 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1068 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1069 _PATH_NOLOGIN), "r");
1070 # else /* HAVE_LOGIN_CAP */
1072 f = fopen(_PATH_NOLOGIN, "r");
1073 # endif /* HAVE_LOGIN_CAP */
1075 /* /etc/nologin exists. Print its contents and exit. */
1076 while (fgets(buf, sizeof(buf), f))
1082 #endif /* HAVE_OSF_SIA */
1084 /* Set login name, uid, gid, and groups. */
1085 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1086 switch, so we let login(1) to this for us. */
1087 if (!options.use_login) {
1089 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1090 if (!check_quietlogin(s, command))
1092 #else /* HAVE_OSF_SIA */
1096 if (getuid() == 0 || geteuid() == 0) {
1098 # ifdef HAVE_GETUSERATTR
1099 set_limits_from_userattr(pw->pw_name);
1100 # endif /* HAVE_GETUSERATTR */
1101 # ifdef HAVE_LOGIN_CAP
1102 if (setusercontext(lc, pw, pw->pw_uid,
1103 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1104 perror("unable to set user context");
1107 # else /* HAVE_LOGIN_CAP */
1108 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1109 /* Sets login uid for accounting */
1110 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1111 error("setluid: %s", strerror(errno));
1112 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1114 if (setlogin(pw->pw_name) < 0)
1115 error("setlogin failed: %s", strerror(errno));
1116 if (setgid(pw->pw_gid) < 0) {
1120 /* Initialize the group list. */
1121 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1122 perror("initgroups");
1128 * PAM credentials may take the form of
1129 * supplementary groups. These will have been
1130 * wiped by the above initgroups() call.
1131 * Reestablish them here.
1134 # endif /* USE_PAM */
1135 # ifdef WITH_IRIX_JOBS
1136 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1138 fatal("Failed to create job container: %.100s",
1141 # endif /* WITH_IRIX_JOBS */
1142 # ifdef WITH_IRIX_ARRAY
1143 /* initialize array session */
1145 if (newarraysess() != 0)
1146 fatal("Failed to set up new array session: %.100s",
1149 # endif /* WITH_IRIX_ARRAY */
1150 # ifdef WITH_IRIX_PROJECT
1151 /* initialize irix project info */
1152 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1153 debug("Failed to get project id, using projid 0");
1156 if (setprid(projid))
1157 fatal("Failed to initialize project %d for %s: %.100s",
1158 (int)projid, pw->pw_name, strerror(errno));
1159 # endif /* WITH_IRIX_PROJECT */
1160 #ifdef WITH_IRIX_AUDIT
1161 if (sysconf(_SC_AUDIT)) {
1162 debug("Setting sat id to %d", (int) pw->pw_uid);
1163 if (satsetid(pw->pw_uid))
1164 debug("error setting satid: %.100s", strerror(errno));
1166 #endif /* WITH_IRIX_AUDIT */
1170 * AIX has a "usrinfo" area where logname and
1171 * other stuff is stored - a few applications
1172 * actually use this and die if it's not set
1176 cp = xmalloc(22 + strlen(s->tty) +
1177 2 * strlen(pw->pw_name));
1178 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1179 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1180 if (usrinfo(SETUINFO, cp, i) == -1)
1181 fatal("Couldn't set usrinfo: %s",
1183 debug3("AIX/UsrInfo: set len %d", i);
1187 /* Permanently switch to the desired uid. */
1188 permanently_set_uid(pw);
1189 # endif /* HAVE_LOGIN_CAP */
1191 #endif /* HAVE_OSF_SIA */
1196 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1197 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1200 * Get the shell from the password data. An empty shell field is
1201 * legal, and means /bin/sh.
1203 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1204 #ifdef HAVE_LOGIN_CAP
1205 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1208 /* Initialize the environment. */
1210 env = xmalloc(envsize * sizeof(char *));
1215 * The Windows environment contains some setting which are
1216 * important for a running system. They must not be dropped.
1218 copy_environment(&env, &envsize);
1221 if (!options.use_login) {
1222 /* Set basic environment. */
1223 child_set_env(&env, &envsize, "USER", pw->pw_name);
1224 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1225 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1226 #ifdef HAVE_LOGIN_CAP
1227 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1228 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1229 #else /* HAVE_LOGIN_CAP */
1230 # ifndef HAVE_CYGWIN
1232 * There's no standard path on Windows. The path contains
1233 * important components pointing to the system directories,
1234 * needed for loading shared libraries. So the path better
1235 * remains intact here.
1237 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1238 # endif /* HAVE_CYGWIN */
1239 #endif /* HAVE_LOGIN_CAP */
1241 snprintf(buf, sizeof buf, "%.200s/%.50s",
1242 _PATH_MAILDIR, pw->pw_name);
1243 child_set_env(&env, &envsize, "MAIL", buf);
1245 /* Normal systems set SHELL by default. */
1246 child_set_env(&env, &envsize, "SHELL", shell);
1249 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1251 /* Set custom environment options from RSA authentication. */
1252 if (!options.use_login) {
1253 while (custom_environment) {
1254 struct envstring *ce = custom_environment;
1257 for (i = 0; s[i] != '=' && s[i]; i++)
1261 child_set_env(&env, &envsize, s, s + i + 1);
1263 custom_environment = ce->next;
1269 snprintf(buf, sizeof buf, "%.50s %d %d",
1270 get_remote_ipaddr(), get_remote_port(), get_local_port());
1271 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1274 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1276 child_set_env(&env, &envsize, "TERM", s->term);
1278 child_set_env(&env, &envsize, "DISPLAY", s->display);
1279 if (original_command)
1280 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1284 if ((cp = getenv("AUTHSTATE")) != NULL)
1285 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1286 if ((cp = getenv("KRB5CCNAME")) != NULL)
1287 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1288 read_environment_file(&env, &envsize, "/etc/environment");
1291 if (s->authctxt->krb4_ticket_file)
1292 child_set_env(&env, &envsize, "KRBTKFILE",
1293 s->authctxt->krb4_ticket_file);
1296 if (s->authctxt->krb5_ticket_file)
1297 child_set_env(&env, &envsize, "KRB5CCNAME",
1298 s->authctxt->krb5_ticket_file);
1301 /* Pull in any environment variables that may have been set by PAM. */
1302 do_pam_environment(&env, &envsize);
1303 #endif /* USE_PAM */
1305 if (auth_get_socket_name() != NULL)
1306 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1307 auth_get_socket_name());
1309 /* read $HOME/.ssh/environment. */
1310 if (!options.use_login) {
1311 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1313 read_environment_file(&env, &envsize, buf);
1316 /* dump the environment */
1317 fprintf(stderr, "Environment:\n");
1318 for (i = 0; env[i]; i++)
1319 fprintf(stderr, " %.200s\n", env[i]);
1321 /* we have to stash the hostname before we close our socket. */
1322 if (options.use_login)
1323 hostname = get_remote_name_or_ip(utmp_len,
1324 options.reverse_mapping_check);
1326 * Close the connection descriptors; note that this is the child, and
1327 * the server will still have the socket open, and it is important
1328 * that we do not shutdown it. Note that the descriptors cannot be
1329 * closed before building the environment, as we call
1330 * get_remote_ipaddr there.
1332 if (packet_get_connection_in() == packet_get_connection_out())
1333 close(packet_get_connection_in());
1335 close(packet_get_connection_in());
1336 close(packet_get_connection_out());
1339 * Close all descriptors related to channels. They will still remain
1340 * open in the parent.
1342 /* XXX better use close-on-exec? -markus */
1343 channel_close_all();
1346 * Close any extra file descriptors. Note that there may still be
1347 * descriptors left by system functions. They will be closed later.
1352 * Close any extra open file descriptors so that we don\'t have them
1353 * hanging around in clients. Note that we want to do this after
1354 * initgroups, because at least on Solaris 2.3 it leaves file
1357 for (i = 3; i < 64; i++)
1361 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1362 * xauth are run in the proper environment.
1367 /* Try to get AFS tokens for the local cell. */
1371 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1372 krb_afslog(cell, 0);
1378 /* Change current directory to the user\'s home directory. */
1379 if (chdir(pw->pw_dir) < 0) {
1380 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1381 pw->pw_dir, strerror(errno));
1382 #ifdef HAVE_LOGIN_CAP
1383 if (login_getcapbool(lc, "requirehome", 0))
1389 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1392 if (!options.use_login) {
1393 /* ignore _PATH_SSH_USER_RC for subsystems */
1394 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1395 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1396 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1398 fprintf(stderr, "Running %s\n", cmd);
1399 f = popen(cmd, "w");
1402 fprintf(f, "%s %s\n", s->auth_proto,
1406 fprintf(stderr, "Could not run %s\n",
1408 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1410 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1411 _PATH_SSH_SYSTEM_RC);
1412 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1415 fprintf(f, "%s %s\n", s->auth_proto,
1419 fprintf(stderr, "Could not run %s\n",
1420 _PATH_SSH_SYSTEM_RC);
1421 } else if (do_xauth && options.xauth_location != NULL) {
1422 /* Add authority data to .Xauthority if appropriate. */
1425 "Running %.100s add "
1426 "%.100s %.100s %.100s\n",
1427 options.xauth_location, s->auth_display[0],
1428 s->auth_proto, s->auth_data);
1429 if (s->auth_display[1])
1431 "add %.100s %.100s %.100s\n",
1433 s->auth_proto, s->auth_data);
1435 snprintf(cmd, sizeof cmd, "%s -q -",
1436 options.xauth_location);
1437 f = popen(cmd, "w");
1439 fprintf(f, "add %s %s %s\n",
1440 s->auth_display[0], s->auth_proto,
1442 if (s->auth_display[1])
1443 fprintf(f, "add %s %s %s\n",
1444 s->auth_display[1], s->auth_proto,
1448 fprintf(stderr, "Could not run %s\n",
1452 /* Get the last component of the shell name. */
1453 cp = strrchr(shell, '/');
1460 /* restore SIGPIPE for child */
1461 signal(SIGPIPE, SIG_DFL);
1464 * If we have no command, execute the shell. In this case, the shell
1465 * name to be passed in argv[0] is preceded by '-' to indicate that
1466 * this is a login shell.
1469 if (!options.use_login) {
1472 /* Start the shell. Set initial character to '-'. */
1474 strlcpy(buf + 1, cp, sizeof(buf) - 1);
1476 /* Execute the shell. */
1479 execve(shell, argv, env);
1481 /* Executing the shell failed. */
1486 /* Launch login(1). */
1488 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1489 #ifdef LOGIN_NEEDS_TERM
1490 s->term? s->term : "unknown",
1492 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1494 /* Login couldn't be executed, die. */
1501 * Execute the command using the user's shell. This uses the -c
1502 * option to execute the command.
1504 argv[0] = (char *) cp;
1506 argv[2] = (char *) command;
1508 execve(shell, argv, env);
1517 static int did_init = 0;
1519 debug("session_new: init");
1520 for(i = 0; i < MAX_SESSIONS; i++) {
1521 sessions[i].used = 0;
1525 for(i = 0; i < MAX_SESSIONS; i++) {
1526 Session *s = &sessions[i];
1528 memset(s, 0, sizeof(*s));
1534 debug("session_new: session %d", i);
1545 for(i = 0; i < MAX_SESSIONS; i++) {
1546 Session *s = &sessions[i];
1547 debug("dump: used %d session %d %p channel %d pid %d",
1557 session_open(Authctxt *authctxt, int chanid)
1559 Session *s = session_new();
1560 debug("session_open: channel %d", chanid);
1562 error("no more sessions");
1565 s->authctxt = authctxt;
1566 s->pw = authctxt->pw;
1568 fatal("no user for session %d", s->self);
1569 debug("session_open: session %d: link with channel %d", s->self, chanid);
1575 session_by_channel(int id)
1578 for(i = 0; i < MAX_SESSIONS; i++) {
1579 Session *s = &sessions[i];
1580 if (s->used && s->chanid == id) {
1581 debug("session_by_channel: session %d channel %d", i, id);
1585 debug("session_by_channel: unknown channel %d", id);
1591 session_by_pid(pid_t pid)
1594 debug("session_by_pid: pid %d", pid);
1595 for(i = 0; i < MAX_SESSIONS; i++) {
1596 Session *s = &sessions[i];
1597 if (s->used && s->pid == pid)
1600 error("session_by_pid: unknown pid %d", pid);
1606 session_window_change_req(Session *s)
1608 s->col = packet_get_int();
1609 s->row = packet_get_int();
1610 s->xpixel = packet_get_int();
1611 s->ypixel = packet_get_int();
1613 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1618 session_pty_req(Session *s)
1624 debug("Allocating a pty not permitted for this authentication.");
1627 if (s->ttyfd != -1) {
1628 packet_disconnect("Protocol error: you already have a pty.");
1632 s->term = packet_get_string(&len);
1635 s->col = packet_get_int();
1636 s->row = packet_get_int();
1638 s->row = packet_get_int();
1639 s->col = packet_get_int();
1641 s->xpixel = packet_get_int();
1642 s->ypixel = packet_get_int();
1644 if (strcmp(s->term, "") == 0) {
1649 /* Allocate a pty and open it. */
1650 debug("Allocating pty.");
1651 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1657 error("session_pty_req: session %d alloc failed", s->self);
1660 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1662 /* for SSH1 the tty modes length is not given */
1664 n_bytes = packet_remaining();
1665 tty_parse_modes(s->ttyfd, &n_bytes);
1668 * Add a cleanup function to clear the utmp entry and record logout
1669 * time in case we call fatal() (e.g., the connection gets closed).
1671 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1672 pty_setowner(s->pw, s->tty);
1674 /* Set window size from the packet. */
1675 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1678 session_proctitle(s);
1683 session_subsystem_req(Session *s)
1688 char *cmd, *subsys = packet_get_string(&len);
1692 log("subsystem request for %s", subsys);
1694 for (i = 0; i < options.num_subsystems; i++) {
1695 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1696 cmd = options.subsystem_command[i];
1697 if (stat(cmd, &st) < 0) {
1698 error("subsystem: cannot stat %s: %s", cmd,
1702 debug("subsystem: exec() %s", cmd);
1703 s->is_subsystem = 1;
1710 log("subsystem request for %s failed, subsystem not found",
1718 session_x11_req(Session *s)
1722 s->single_connection = packet_get_char();
1723 s->auth_proto = packet_get_string(NULL);
1724 s->auth_data = packet_get_string(NULL);
1725 s->screen = packet_get_int();
1728 success = session_setup_x11fwd(s);
1730 xfree(s->auth_proto);
1731 xfree(s->auth_data);
1732 s->auth_proto = NULL;
1733 s->auth_data = NULL;
1739 session_shell_req(Session *s)
1747 session_exec_req(Session *s)
1750 char *command = packet_get_string(&len);
1752 do_exec(s, command);
1758 session_auth_agent_req(Session *s)
1760 static int called = 0;
1762 if (no_agent_forwarding_flag) {
1763 debug("session_auth_agent_req: no_agent_forwarding_flag");
1770 return auth_input_request_forwarding(s->pw);
1775 session_input_channel_req(int id, void *arg)
1784 rtype = packet_get_string(&len);
1785 reply = packet_get_char();
1787 s = session_by_channel(id);
1789 fatal("session_input_channel_req: channel %d: no session", id);
1790 c = channel_lookup(id);
1792 fatal("session_input_channel_req: channel %d: bad channel", id);
1794 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1795 s->self, id, rtype, reply);
1798 * a session is in LARVAL state until a shell, a command
1799 * or a subsystem is executed
1801 if (c->type == SSH_CHANNEL_LARVAL) {
1802 if (strcmp(rtype, "shell") == 0) {
1803 success = session_shell_req(s);
1804 } else if (strcmp(rtype, "exec") == 0) {
1805 success = session_exec_req(s);
1806 } else if (strcmp(rtype, "pty-req") == 0) {
1807 success = session_pty_req(s);
1808 } else if (strcmp(rtype, "x11-req") == 0) {
1809 success = session_x11_req(s);
1810 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1811 success = session_auth_agent_req(s);
1812 } else if (strcmp(rtype, "subsystem") == 0) {
1813 success = session_subsystem_req(s);
1816 if (strcmp(rtype, "window-change") == 0) {
1817 success = session_window_change_req(s);
1821 packet_start(success ?
1822 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1823 packet_put_int(c->remote_id);
1830 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1833 fatal("session_set_fds: called for proto != 2.0");
1835 * now that have a child and a pipe to the child,
1836 * we can activate our channel and register the fd's
1838 if (s->chanid == -1)
1839 fatal("no channel for session %d", s->self);
1840 channel_set_fds(s->chanid,
1842 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1847 * Function to perform pty cleanup. Also called if we get aborted abnormally
1848 * (e.g., due to a dropped connection).
1851 session_pty_cleanup(void *session)
1853 Session *s = session;
1856 error("session_pty_cleanup: no session");
1862 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1864 /* Record that the user has logged out. */
1866 record_logout(s->pid, s->tty);
1868 /* Release the pseudo-tty. */
1869 pty_release(s->tty);
1872 * Close the server side of the socket pairs. We must do this after
1873 * the pty cleanup, so that another process doesn't get this pty
1874 * while we're still cleaning up.
1876 if (close(s->ptymaster) < 0)
1877 error("close(s->ptymaster): %s", strerror(errno));
1879 /* unlink pty from session */
1884 session_exit_message(Session *s, int status)
1888 fatal("session_close: no session");
1889 c = channel_lookup(s->chanid);
1891 fatal("session_exit_message: session %d: no channel %d",
1892 s->self, s->chanid);
1893 debug("session_exit_message: session %d channel %d pid %d",
1894 s->self, s->chanid, s->pid);
1896 if (WIFEXITED(status)) {
1897 channel_request_start(s->chanid,
1899 packet_put_int(WEXITSTATUS(status));
1901 } else if (WIFSIGNALED(status)) {
1902 channel_request_start(s->chanid,
1904 packet_put_int(WTERMSIG(status));
1906 packet_put_char(WCOREDUMP(status));
1907 #else /* WCOREDUMP */
1909 #endif /* WCOREDUMP */
1910 packet_put_cstring("");
1911 packet_put_cstring("");
1914 /* Some weird exit cause. Just exit. */
1915 packet_disconnect("wait returned status %04x.", status);
1918 /* disconnect channel */
1919 debug("session_exit_message: release channel %d", s->chanid);
1920 channel_cancel_cleanup(s->chanid);
1922 * emulate a write failure with 'chan_write_failed', nobody will be
1923 * interested in data we write.
1924 * Note that we must not call 'chan_read_failed', since there could
1925 * be some more data waiting in the pipe.
1927 if (c->ostate != CHAN_OUTPUT_CLOSED)
1928 chan_write_failed(c);
1933 session_close(Session *s)
1935 debug("session_close: session %d pid %d", s->self, s->pid);
1936 if (s->ttyfd != -1) {
1937 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1938 session_pty_cleanup(s);
1944 if (s->auth_display[0])
1945 xfree(s->auth_display[0]);
1946 if (s->auth_display[1])
1947 xfree(s->auth_display[1]);
1949 xfree(s->auth_data);
1951 xfree(s->auth_proto);
1953 session_proctitle(s);
1957 session_close_by_pid(pid_t pid, int status)
1959 Session *s = session_by_pid(pid);
1961 debug("session_close_by_pid: no session for pid %d", pid);
1964 if (s->chanid != -1)
1965 session_exit_message(s, status);
1970 * this is called when a channel dies before
1971 * the session 'child' itself dies
1974 session_close_by_channel(int id, void *arg)
1976 Session *s = session_by_channel(id);
1978 debug("session_close_by_channel: no session for id %d", id);
1981 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1983 debug("session_close_by_channel: channel %d: has child", id);
1985 * delay detach of session, but release pty, since
1986 * the fd's to the child are already closed
1988 if (s->ttyfd != -1) {
1989 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1990 session_pty_cleanup(s);
1994 /* detach by removing callback */
1995 channel_cancel_cleanup(s->chanid);
2001 session_destroy_all(void)
2004 for(i = 0; i < MAX_SESSIONS; i++) {
2005 Session *s = &sessions[i];
2012 session_tty_list(void)
2014 static char buf[1024];
2017 for(i = 0; i < MAX_SESSIONS; i++) {
2018 Session *s = &sessions[i];
2019 if (s->used && s->ttyfd != -1) {
2021 strlcat(buf, ",", sizeof buf);
2022 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2026 strlcpy(buf, "notty", sizeof buf);
2031 session_proctitle(Session *s)
2034 error("no user for session %d", s->self);
2036 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2040 session_setup_x11fwd(Session *s)
2043 char display[512], auth_display[512];
2044 char hostname[MAXHOSTNAMELEN];
2046 if (no_x11_forwarding_flag) {
2047 packet_send_debug("X11 forwarding disabled in user configuration file.");
2050 if (!options.x11_forwarding) {
2051 debug("X11 forwarding disabled in server configuration file.");
2054 if (!options.xauth_location ||
2055 (stat(options.xauth_location, &st) == -1)) {
2056 packet_send_debug("No xauth program; cannot forward with spoofing.");
2059 if (options.use_login) {
2060 packet_send_debug("X11 forwarding disabled; "
2061 "not compatible with UseLogin=yes.");
2064 if (s->display != NULL) {
2065 debug("X11 display already set.");
2068 s->display_number = x11_create_display_inet(options.x11_display_offset,
2069 options.gateway_ports);
2070 if (s->display_number == -1) {
2071 debug("x11_create_display_inet failed.");
2075 /* Set up a suitable value for the DISPLAY variable. */
2076 if (gethostname(hostname, sizeof(hostname)) < 0)
2077 fatal("gethostname: %.100s", strerror(errno));
2079 * auth_display must be used as the displayname when the
2080 * authorization entry is added with xauth(1). This will be
2081 * different than the DISPLAY string for localhost displays.
2083 s->auth_display[1] = NULL;
2084 if (!options.gateway_ports) {
2087 snprintf(display, sizeof display, "localhost:%d.%d",
2088 s->display_number, s->screen);
2089 snprintf(auth_display, sizeof auth_display, "%.400s/unix:%d.%d",
2090 hostname, s->display_number, s->screen);
2091 s->display = xstrdup(display);
2092 s->auth_display[0] = xstrdup(auth_display);
2094 * Xlib may use gethostbyname() or uname() hostname to
2095 * look up authorization data for FamilyLocal; see:
2096 * xc/lib/xtrans/Xtrans.c:TRANS(GetHostname)
2097 * We just add authorization entries with both
2098 * hostname and nodename if they are different.
2100 if (uname(&uts) == -1)
2101 fatal("uname: %.100s", strerror(errno));
2102 if (strcmp(hostname, uts.nodename) != 0) {
2103 snprintf(auth_display, sizeof auth_display,
2104 "%.400s/unix:%d.%d", uts.nodename,
2105 s->display_number, s->screen);
2106 s->auth_display[1] = xstrdup(auth_display);
2109 #ifdef IPADDR_IN_DISPLAY
2111 struct in_addr my_addr;
2113 he = gethostbyname(hostname);
2115 error("Can't get IP address for X11 DISPLAY.");
2116 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2119 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2120 snprintf(display, sizeof display, "%.50s:%d.%d", inet_ntoa(my_addr),
2121 s->display_number, s->screen);
2123 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
2124 s->display_number, s->screen);
2126 s->display = xstrdup(display);
2127 s->auth_display[0] = xstrdup(display);
2134 do_authenticated2(Authctxt *authctxt)
2136 server_loop2(authctxt);