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.107 2001/10/10 22:18:47 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
60 #ifdef WITH_IRIX_PROJECT
62 #endif /* WITH_IRIX_PROJECT */
64 #include <sys/resource.h>
66 #ifdef WITH_IRIX_AUDIT
68 #endif /* WITH_IRIX_AUDIT */
70 #if defined(HAVE_USERSEC_H)
76 #include <sys/cygwin.h>
77 #define is_winnt (GetVersion() < 0x80000000)
81 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
82 # define S_UFSIZE_HARD S_UFSIZE "_hard"
83 # define S_UCPU_HARD S_UCPU "_hard"
84 # define S_UDATA_HARD S_UDATA "_hard"
85 # define S_USTACK_HARD S_USTACK "_hard"
86 # define S_URSS_HARD S_URSS "_hard"
87 # define S_UCORE_HARD S_UCORE "_hard"
88 # define S_UNOFILE_HARD S_UNOFILE "_hard"
98 typedef struct Session Session;
107 int ptyfd, ttyfd, ptymaster;
108 int row, col, xpixel, ypixel;
115 int single_connection;
123 Session *session_new(void);
124 void session_set_fds(Session *, int, int, int);
125 static void session_pty_cleanup(void *);
126 void session_proctitle(Session *);
127 int session_setup_x11fwd(Session *);
128 void do_exec_pty(Session *, const char *);
129 void do_exec_no_pty(Session *, const char *);
130 void do_exec(Session *, const char *);
131 void do_login(Session *, const char *);
132 #ifdef LOGIN_NEEDS_UTMPX
133 static void do_pre_login(Session *s);
135 void do_child(Session *, const char *);
137 int check_quietlogin(Session *, const char *);
139 static void do_authenticated1(Authctxt *);
140 static void do_authenticated2(Authctxt *);
142 static void session_close(Session *);
143 static int session_pty_req(Session *);
146 extern ServerOptions options;
147 extern char *__progname;
148 extern int log_stderr;
149 extern int debug_flag;
150 extern u_int utmp_len;
151 extern int startup_pipe;
152 extern void destroy_sensitive_data(void);
154 /* original command from peer. */
155 const char *original_command = NULL;
158 #define MAX_SESSIONS 10
159 Session sessions[MAX_SESSIONS];
161 #ifdef WITH_AIXAUTHENTICATE
162 /* AIX's lastlogin message, set in auth1.c */
164 #endif /* WITH_AIXAUTHENTICATE */
166 #ifdef HAVE_LOGIN_CAP
167 static login_cap_t *lc;
171 do_authenticated(Authctxt *authctxt)
174 * Cancel the alarm we set to limit the time taken for
178 if (startup_pipe != -1) {
182 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
183 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
184 error("unable to get login class");
188 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
189 packet_disconnect("Approval failure for %s",
190 authctxt->pw->pw_name);
194 /* setup the channel layer */
195 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
196 channel_permit_all_opens();
199 do_authenticated2(authctxt);
201 do_authenticated1(authctxt);
203 /* remove agent socket */
204 if (auth_get_socket_name())
205 auth_sock_cleanup_proc(authctxt->pw);
207 if (options.kerberos_ticket_cleanup)
208 krb4_cleanup_proc(authctxt);
211 if (options.kerberos_ticket_cleanup)
212 krb5_cleanup_proc(authctxt);
217 * Prepares for an interactive session. This is called after the user has
218 * been successfully authenticated. During this message exchange, pseudo
219 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
220 * are requested, etc.
223 do_authenticated1(Authctxt *authctxt)
227 int success, type, plen, screen_flag;
228 int compression_level = 0, enable_compression_after_reply = 0;
229 u_int proto_len, data_len, dlen;
232 s->authctxt = authctxt;
233 s->pw = authctxt->pw;
236 * We stay in this loop until the client requests to execute a shell
242 /* Get a packet from the client. */
243 type = packet_read(&plen);
245 /* Process the packet. */
247 case SSH_CMSG_REQUEST_COMPRESSION:
248 packet_integrity_check(plen, 4, type);
249 compression_level = packet_get_int();
250 if (compression_level < 1 || compression_level > 9) {
251 packet_send_debug("Received illegal compression level %d.",
255 /* Enable compression after we have responded with SUCCESS. */
256 enable_compression_after_reply = 1;
260 case SSH_CMSG_REQUEST_PTY:
261 success = session_pty_req(s);
264 case SSH_CMSG_X11_REQUEST_FORWARDING:
265 s->auth_proto = packet_get_string(&proto_len);
266 s->auth_data = packet_get_string(&data_len);
268 screen_flag = packet_get_protocol_flags() &
269 SSH_PROTOFLAG_SCREEN_NUMBER;
270 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
272 if (packet_remaining() == 4) {
274 debug2("Buggy client: "
275 "X11 screen flag missing");
276 s->screen = packet_get_int();
281 success = session_setup_x11fwd(s);
283 xfree(s->auth_proto);
285 s->auth_proto = NULL;
290 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
291 if (no_agent_forwarding_flag || compat13) {
292 debug("Authentication agent forwarding not permitted for this authentication.");
295 debug("Received authentication agent forwarding request.");
296 success = auth_input_request_forwarding(s->pw);
299 case SSH_CMSG_PORT_FORWARD_REQUEST:
300 if (no_port_forwarding_flag) {
301 debug("Port forwarding not permitted for this authentication.");
304 if (!options.allow_tcp_forwarding) {
305 debug("Port forwarding not permitted.");
308 debug("Received TCP/IP port forwarding request.");
309 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
313 case SSH_CMSG_MAX_PACKET_SIZE:
314 if (packet_set_maxsize(packet_get_int()) > 0)
318 #if defined(AFS) || defined(KRB5)
319 case SSH_CMSG_HAVE_KERBEROS_TGT:
320 if (!options.kerberos_tgt_passing) {
321 verbose("Kerberos TGT passing disabled.");
323 char *kdata = packet_get_string(&dlen);
324 packet_integrity_check(plen, 4 + dlen, type);
326 /* XXX - 0x41, see creds_to_radix version */
327 if (kdata[0] != 0x41) {
333 if (auth_krb5_tgt(s->authctxt, &tgt))
336 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
340 if (auth_krb4_tgt(s->authctxt, kdata))
343 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
349 #endif /* AFS || KRB5 */
352 case SSH_CMSG_HAVE_AFS_TOKEN:
353 if (!options.afs_token_passing || !k_hasafs()) {
354 verbose("AFS token passing disabled.");
356 /* Accept AFS token. */
357 char *token = packet_get_string(&dlen);
358 packet_integrity_check(plen, 4 + dlen, type);
360 if (auth_afs_token(s->authctxt, token))
363 verbose("AFS token refused for %.100s",
370 case SSH_CMSG_EXEC_SHELL:
371 case SSH_CMSG_EXEC_CMD:
372 if (type == SSH_CMSG_EXEC_CMD) {
373 command = packet_get_string(&dlen);
374 debug("Exec command '%.500s'", command);
386 * Any unknown messages in this phase are ignored,
387 * and a failure message is returned.
389 log("Unknown packet type received after authentication: %d", type);
391 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
395 /* Enable compression now that we have replied if appropriate. */
396 if (enable_compression_after_reply) {
397 enable_compression_after_reply = 0;
398 packet_start_compression(compression_level);
404 * This is called to fork and execute a command when we have no tty. This
405 * will call do_child from the child, and server_loop from the parent after
406 * setting up file descriptors and such.
409 do_exec_no_pty(Session *s, const char *command)
414 int pin[2], pout[2], perr[2];
415 /* Allocate pipes for communicating with the program. */
416 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
417 packet_disconnect("Could not create pipes: %.100s",
419 #else /* USE_PIPES */
420 int inout[2], err[2];
421 /* Uses socket pairs to communicate with the program. */
422 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
423 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
424 packet_disconnect("Could not create socket pairs: %.100s",
426 #endif /* USE_PIPES */
428 fatal("do_exec_no_pty: no session");
430 session_proctitle(s);
433 do_pam_session(s->pw->pw_name, NULL);
437 /* Fork the child. */
438 if ((pid = fork()) == 0) {
439 /* Child. Reinitialize the log since the pid has changed. */
440 log_init(__progname, options.log_level, options.log_facility, log_stderr);
443 * Create a new session and process group since the 4.4BSD
444 * setlogin() affects the entire process group.
447 error("setsid failed: %.100s", strerror(errno));
451 * Redirect stdin. We close the parent side of the socket
452 * pair, and make the child side the standard input.
455 if (dup2(pin[0], 0) < 0)
456 perror("dup2 stdin");
459 /* Redirect stdout. */
461 if (dup2(pout[1], 1) < 0)
462 perror("dup2 stdout");
465 /* Redirect stderr. */
467 if (dup2(perr[1], 2) < 0)
468 perror("dup2 stderr");
470 #else /* USE_PIPES */
472 * Redirect stdin, stdout, and stderr. Stdin and stdout will
473 * use the same socket, as some programs (particularly rdist)
474 * seem to depend on it.
478 if (dup2(inout[0], 0) < 0) /* stdin */
479 perror("dup2 stdin");
480 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
481 perror("dup2 stdout");
482 if (dup2(err[0], 2) < 0) /* stderr */
483 perror("dup2 stderr");
484 #endif /* USE_PIPES */
486 /* Do processing for the child (exec command etc). */
487 do_child(s, command);
492 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
495 packet_disconnect("fork failed: %.100s", strerror(errno));
497 /* Set interactive/non-interactive mode. */
498 packet_set_interactive(s->display != NULL);
500 /* We are the parent. Close the child sides of the pipes. */
506 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
508 /* Enter the interactive session. */
509 server_loop(pid, pin[1], pout[0], perr[0]);
510 /* server_loop has closed pin[1], pout[0], and perr[0]. */
512 #else /* USE_PIPES */
513 /* We are the parent. Close the child sides of the socket pairs. */
518 * Enter the interactive session. Note: server_loop must be able to
519 * handle the case that fdin and fdout are the same.
522 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
524 server_loop(pid, inout[1], inout[1], err[1]);
525 /* server_loop has closed inout[1] and err[1]. */
527 #endif /* USE_PIPES */
531 * This is called to fork and execute a command when we have a tty. This
532 * will call do_child from the child, and server_loop from the parent after
533 * setting up file descriptors, controlling tty, updating wtmp, utmp,
534 * lastlog, and other such operations.
537 do_exec_pty(Session *s, const char *command)
539 int fdout, ptyfd, ttyfd, ptymaster;
543 fatal("do_exec_pty: no session");
548 do_pam_session(s->pw->pw_name, s->tty);
552 /* Fork the child. */
553 if ((pid = fork()) == 0) {
555 /* Child. Reinitialize the log because the pid has changed. */
556 log_init(__progname, options.log_level, options.log_facility, log_stderr);
557 /* Close the master side of the pseudo tty. */
560 /* Make the pseudo tty our controlling tty. */
561 pty_make_controlling_tty(&ttyfd, s->tty);
563 /* Redirect stdin/stdout/stderr from the pseudo tty. */
564 if (dup2(ttyfd, 0) < 0)
565 error("dup2 stdin: %s", strerror(errno));
566 if (dup2(ttyfd, 1) < 0)
567 error("dup2 stdout: %s", strerror(errno));
568 if (dup2(ttyfd, 2) < 0)
569 error("dup2 stderr: %s", strerror(errno));
571 /* Close the extra descriptor for the pseudo tty. */
574 /* record login, etc. similar to login(1) */
576 if (!(options.use_login && command == NULL))
577 do_login(s, command);
578 # ifdef LOGIN_NEEDS_UTMPX
584 /* Do common processing for the child, such as execing the command. */
585 do_child(s, command);
590 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
593 packet_disconnect("fork failed: %.100s", strerror(errno));
596 /* Parent. Close the slave side of the pseudo tty. */
600 * Create another descriptor of the pty master side for use as the
601 * standard input. We could use the original descriptor, but this
602 * simplifies code in server_loop. The descriptor is bidirectional.
606 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
608 /* we keep a reference to the pty master */
609 ptymaster = dup(ptyfd);
611 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
612 s->ptymaster = ptymaster;
614 /* Enter interactive session. */
615 packet_set_interactive(1);
617 session_set_fds(s, ptyfd, fdout, -1);
619 server_loop(pid, ptyfd, fdout, -1);
620 /* server_loop _has_ closed ptyfd and fdout. */
624 #ifdef LOGIN_NEEDS_UTMPX
626 do_pre_login(Session *s)
629 struct sockaddr_storage from;
630 pid_t pid = getpid();
633 * Get IP address of client. If the connection is not a socket, let
634 * the address be 0.0.0.0.
636 memset(&from, 0, sizeof(from));
637 if (packet_connection_is_on_socket()) {
638 fromlen = sizeof(from);
639 if (getpeername(packet_get_connection_in(),
640 (struct sockaddr *) & from, &fromlen) < 0) {
641 debug("getpeername: %.100s", strerror(errno));
646 record_utmp_only(pid, s->tty, s->pw->pw_name,
647 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
648 (struct sockaddr *)&from);
653 * This is called to fork and execute a command. If another command is
654 * to be forced, execute that instead.
657 do_exec(Session *s, const char *command)
659 if (forced_command) {
660 original_command = command;
661 command = forced_command;
662 debug("Forced command '%.900s'", command);
666 do_exec_pty(s, command);
668 do_exec_no_pty(s, command);
670 original_command = NULL;
673 /* administrative, login(1)-like work */
675 do_login(Session *s, const char *command)
678 char hostname[MAXHOSTNAMELEN];
680 struct sockaddr_storage from;
681 time_t last_login_time;
682 struct passwd * pw = s->pw;
683 pid_t pid = getpid();
686 * Get IP address of client. If the connection is not a socket, let
687 * the address be 0.0.0.0.
689 memset(&from, 0, sizeof(from));
690 if (packet_connection_is_on_socket()) {
691 fromlen = sizeof(from);
692 if (getpeername(packet_get_connection_in(),
693 (struct sockaddr *) & from, &fromlen) < 0) {
694 debug("getpeername: %.100s", strerror(errno));
699 /* Get the time and hostname when the user last logged in. */
700 if (options.print_lastlog) {
702 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
703 hostname, sizeof(hostname));
706 /* Record that there was a login on that tty from the remote host. */
707 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
708 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
709 (struct sockaddr *)&from);
713 * If password change is needed, do it now.
714 * This needs to occur before the ~/.hushlogin check.
716 if (is_pam_password_change_required()) {
717 print_pam_messages();
722 if (check_quietlogin(s, command))
726 if (!is_pam_password_change_required())
727 print_pam_messages();
729 #ifdef WITH_AIXAUTHENTICATE
730 if (aixloginmsg && *aixloginmsg)
731 printf("%s\n", aixloginmsg);
732 #endif /* WITH_AIXAUTHENTICATE */
734 if (options.print_lastlog && last_login_time != 0) {
735 time_string = ctime(&last_login_time);
736 if (strchr(time_string, '\n'))
737 *strchr(time_string, '\n') = 0;
738 if (strcmp(hostname, "") == 0)
739 printf("Last login: %s\r\n", time_string);
741 printf("Last login: %s from %s\r\n", time_string, hostname);
748 * Display the message of the day.
756 if (options.print_motd) {
757 #ifdef HAVE_LOGIN_CAP
758 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
761 f = fopen("/etc/motd", "r");
764 while (fgets(buf, sizeof(buf), f))
773 * Check for quiet login, either .hushlogin or command given.
776 check_quietlogin(Session *s, const char *command)
779 struct passwd *pw = s->pw;
782 /* Return 1 if .hushlogin exists or a command given. */
785 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
786 #ifdef HAVE_LOGIN_CAP
787 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
790 if (stat(buf, &st) >= 0)
797 * Sets the value of the given variable in the environment. If the variable
798 * already exists, its value is overriden.
801 child_set_env(char ***envp, u_int *envsizep, const char *name,
808 * Find the slot where the value should be stored. If the variable
809 * already exists, we reuse the slot; otherwise we append a new slot
810 * at the end of the array, expanding if necessary.
813 namelen = strlen(name);
814 for (i = 0; env[i]; i++)
815 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
818 /* Reuse the slot. */
821 /* New variable. Expand if necessary. */
822 if (i >= (*envsizep) - 1) {
824 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
826 /* Need to set the NULL pointer at end of array beyond the new slot. */
830 /* Allocate space and format the variable in the appropriate slot. */
831 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
832 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
836 * Reads environment variables from the given file and adds/overrides them
837 * into the environment. If the file does not exist, this does nothing.
838 * Otherwise, it must consist of empty lines, comments (line starts with '#')
839 * and assignments of the form name=value. No other forms are allowed.
842 read_environment_file(char ***env, u_int *envsize,
843 const char *filename)
849 f = fopen(filename, "r");
853 while (fgets(buf, sizeof(buf), f)) {
854 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
856 if (!*cp || *cp == '#' || *cp == '\n')
858 if (strchr(cp, '\n'))
859 *strchr(cp, '\n') = '\0';
860 value = strchr(cp, '=');
862 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
866 * Replace the equals sign by nul, and advance value to
871 child_set_env(env, envsize, cp, value);
878 * Sets any environment variables which have been specified by PAM
880 void do_pam_environment(char ***env, u_int *envsize)
882 char *equals, var_name[512], var_val[512];
886 if ((pam_env = fetch_pam_environment()) == NULL)
889 for(i = 0; pam_env[i] != NULL; i++) {
890 if ((equals = strstr(pam_env[i], "=")) == NULL)
893 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
894 memset(var_name, '\0', sizeof(var_name));
895 memset(var_val, '\0', sizeof(var_val));
897 strncpy(var_name, pam_env[i], equals - pam_env[i]);
898 strcpy(var_val, equals + 1);
900 debug3("PAM environment: %s=%s", var_name, var_val);
902 child_set_env(env, envsize, var_name, var_val);
909 void copy_environment(char ***env, u_int *envsize)
911 char *equals, var_name[512], var_val[512];
914 for(i = 0; environ[i] != NULL; i++) {
915 if ((equals = strstr(environ[i], "=")) == NULL)
918 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
919 memset(var_name, '\0', sizeof(var_name));
920 memset(var_val, '\0', sizeof(var_val));
922 strncpy(var_name, environ[i], equals - environ[i]);
923 strcpy(var_val, equals + 1);
925 debug3("Copy environment: %s=%s", var_name, var_val);
927 child_set_env(env, envsize, var_name, var_val);
933 #if defined(HAVE_GETUSERATTR)
935 * AIX-specific login initialisation
937 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
942 getrlimit(resource, &rlim);
945 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
947 rlim.rlim_cur = RLIM_INFINITY;
948 } else if (slim != 0) {
949 /* See the wackiness below */
950 if (rlim.rlim_cur == slim * mult)
953 rlim.rlim_cur = slim * mult;
958 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
960 rlim.rlim_max = RLIM_INFINITY;
961 } else if (hlim != 0) {
962 rlim.rlim_max = hlim * mult;
967 * XXX For cpu and fsize the soft limit is set to the hard limit
968 * if the hard limit is left at its default value and the soft limit
969 * is changed from its default value, either by requesting it
970 * (slim == 0) or by setting it to the current default. At least
971 * that's how rlogind does it. If you're confused you're not alone.
972 * Bug or feature? AIX 4.3.1.2
974 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
975 && hlim == 0 && slim != 0)
976 rlim.rlim_max = rlim.rlim_cur;
977 /* A specified hard limit limits the soft limit */
978 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
979 rlim.rlim_cur = rlim.rlim_max;
980 /* A soft limit can increase a hard limit */
981 else if (rlim.rlim_cur > rlim.rlim_max)
982 rlim.rlim_max = rlim.rlim_cur;
984 if (setrlimit(resource, &rlim) != 0)
985 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
988 void set_limits_from_userattr(char *user)
993 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
994 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
995 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
996 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
997 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
998 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
999 #if defined(S_UNOFILE)
1000 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1003 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1004 /* Convert decimal to octal */
1005 (void) snprintf(buf, sizeof(buf), "%d", mask);
1006 if (sscanf(buf, "%o", &mask) == 1)
1010 #endif /* defined(HAVE_GETUSERATTR) */
1013 * Performs common processing for the child, such as setting up the
1014 * environment, closing extra file descriptors, setting the user and group
1015 * ids, and executing the command or shell.
1018 do_child(Session *s, const char *command)
1020 const char *shell, *hostname = NULL, *cp = NULL;
1021 struct passwd *pw = s->pw;
1027 extern char **environ;
1031 #ifdef WITH_IRIX_PROJECT
1033 #endif /* WITH_IRIX_PROJECT */
1034 #ifdef WITH_IRIX_JOBS
1037 #ifdef WITH_IRIX_ARRAY
1039 #endif /* WITH_IRIX_ARRAY */
1040 #endif /* WITH_IRIX_JOBS */
1043 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1045 /* remove hostkey from the child's memory */
1046 destroy_sensitive_data();
1048 /* login(1) is only called if we execute the login shell */
1049 if (options.use_login && command != NULL)
1050 options.use_login = 0;
1052 #if !defined(HAVE_OSF_SIA)
1053 if (!options.use_login) {
1054 # ifdef HAVE_LOGIN_CAP
1055 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1056 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1057 _PATH_NOLOGIN), "r");
1058 # else /* HAVE_LOGIN_CAP */
1060 f = fopen(_PATH_NOLOGIN, "r");
1061 # endif /* HAVE_LOGIN_CAP */
1063 /* /etc/nologin exists. Print its contents and exit. */
1064 while (fgets(buf, sizeof(buf), f))
1070 #endif /* HAVE_OSF_SIA */
1072 /* Set login name, uid, gid, and groups. */
1073 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1074 switch, so we let login(1) to this for us. */
1075 if (!options.use_login) {
1077 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1078 if (!check_quietlogin(s, command))
1080 #else /* HAVE_OSF_SIA */
1084 if (getuid() == 0 || geteuid() == 0) {
1086 # ifdef HAVE_GETUSERATTR
1087 set_limits_from_userattr(pw->pw_name);
1088 # endif /* HAVE_GETUSERATTR */
1089 # ifdef HAVE_LOGIN_CAP
1090 if (setusercontext(lc, pw, pw->pw_uid,
1091 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1092 perror("unable to set user context");
1095 # else /* HAVE_LOGIN_CAP */
1096 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1097 /* Sets login uid for accounting */
1098 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1099 error("setluid: %s", strerror(errno));
1100 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1102 if (setlogin(pw->pw_name) < 0)
1103 error("setlogin failed: %s", strerror(errno));
1104 if (setgid(pw->pw_gid) < 0) {
1108 /* Initialize the group list. */
1109 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1110 perror("initgroups");
1116 * PAM credentials may take the form of
1117 * supplementary groups. These will have been
1118 * wiped by the above initgroups() call.
1119 * Reestablish them here.
1122 # endif /* USE_PAM */
1123 # ifdef WITH_IRIX_JOBS
1124 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1126 fatal("Failed to create job container: %.100s",
1129 # endif /* WITH_IRIX_JOBS */
1130 # ifdef WITH_IRIX_ARRAY
1131 /* initialize array session */
1133 if (newarraysess() != 0)
1134 fatal("Failed to set up new array session: %.100s",
1137 # endif /* WITH_IRIX_ARRAY */
1138 # ifdef WITH_IRIX_PROJECT
1139 /* initialize irix project info */
1140 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1141 debug("Failed to get project id, using projid 0");
1144 if (setprid(projid))
1145 fatal("Failed to initialize project %d for %s: %.100s",
1146 (int)projid, pw->pw_name, strerror(errno));
1147 # endif /* WITH_IRIX_PROJECT */
1148 #ifdef WITH_IRIX_AUDIT
1149 if (sysconf(_SC_AUDIT)) {
1150 debug("Setting sat id to %d", (int) pw->pw_uid);
1151 if (satsetid(pw->pw_uid))
1152 debug("error setting satid: %.100s", strerror(errno));
1154 #endif /* WITH_IRIX_AUDIT */
1158 * AIX has a "usrinfo" area where logname and
1159 * other stuff is stored - a few applications
1160 * actually use this and die if it's not set
1164 cp = xmalloc(22 + strlen(s->tty) +
1165 2 * strlen(pw->pw_name));
1166 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1167 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1168 if (usrinfo(SETUINFO, cp, i) == -1)
1169 fatal("Couldn't set usrinfo: %s",
1171 debug3("AIX/UsrInfo: set len %d", i);
1175 /* Permanently switch to the desired uid. */
1176 permanently_set_uid(pw);
1177 # endif /* HAVE_LOGIN_CAP */
1179 #endif /* HAVE_OSF_SIA */
1184 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1185 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1188 * Get the shell from the password data. An empty shell field is
1189 * legal, and means /bin/sh.
1191 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1192 #ifdef HAVE_LOGIN_CAP
1193 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1196 /* Initialize the environment. */
1198 env = xmalloc(envsize * sizeof(char *));
1203 * The Windows environment contains some setting which are
1204 * important for a running system. They must not be dropped.
1206 copy_environment(&env, &envsize);
1209 if (!options.use_login) {
1210 /* Set basic environment. */
1211 child_set_env(&env, &envsize, "USER", pw->pw_name);
1212 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1213 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1214 #ifdef HAVE_LOGIN_CAP
1215 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1216 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1217 #else /* HAVE_LOGIN_CAP */
1218 # ifndef HAVE_CYGWIN
1220 * There's no standard path on Windows. The path contains
1221 * important components pointing to the system directories,
1222 * needed for loading shared libraries. So the path better
1223 * remains intact here.
1225 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1226 # endif /* HAVE_CYGWIN */
1227 #endif /* HAVE_LOGIN_CAP */
1229 snprintf(buf, sizeof buf, "%.200s/%.50s",
1230 _PATH_MAILDIR, pw->pw_name);
1231 child_set_env(&env, &envsize, "MAIL", buf);
1233 /* Normal systems set SHELL by default. */
1234 child_set_env(&env, &envsize, "SHELL", shell);
1237 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1239 /* Set custom environment options from RSA authentication. */
1240 while (custom_environment) {
1241 struct envstring *ce = custom_environment;
1244 for (i = 0; s[i] != '=' && s[i]; i++);
1247 child_set_env(&env, &envsize, s, s + i + 1);
1249 custom_environment = ce->next;
1254 snprintf(buf, sizeof buf, "%.50s %d %d",
1255 get_remote_ipaddr(), get_remote_port(), get_local_port());
1256 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1259 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1261 child_set_env(&env, &envsize, "TERM", s->term);
1263 child_set_env(&env, &envsize, "DISPLAY", s->display);
1264 if (original_command)
1265 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1269 if ((cp = getenv("AUTHSTATE")) != NULL)
1270 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1271 if ((cp = getenv("KRB5CCNAME")) != NULL)
1272 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1273 read_environment_file(&env, &envsize, "/etc/environment");
1276 if (s->authctxt->krb4_ticket_file)
1277 child_set_env(&env, &envsize, "KRBTKFILE",
1278 s->authctxt->krb4_ticket_file);
1281 if (s->authctxt->krb5_ticket_file)
1282 child_set_env(&env, &envsize, "KRB5CCNAME",
1283 s->authctxt->krb5_ticket_file);
1286 /* Pull in any environment variables that may have been set by PAM. */
1287 do_pam_environment(&env, &envsize);
1288 #endif /* USE_PAM */
1290 if (auth_get_socket_name() != NULL)
1291 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1292 auth_get_socket_name());
1294 /* read $HOME/.ssh/environment. */
1295 if (!options.use_login) {
1296 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1298 read_environment_file(&env, &envsize, buf);
1301 /* dump the environment */
1302 fprintf(stderr, "Environment:\n");
1303 for (i = 0; env[i]; i++)
1304 fprintf(stderr, " %.200s\n", env[i]);
1306 /* we have to stash the hostname before we close our socket. */
1307 if (options.use_login)
1308 hostname = get_remote_name_or_ip(utmp_len,
1309 options.reverse_mapping_check);
1311 * Close the connection descriptors; note that this is the child, and
1312 * the server will still have the socket open, and it is important
1313 * that we do not shutdown it. Note that the descriptors cannot be
1314 * closed before building the environment, as we call
1315 * get_remote_ipaddr there.
1317 if (packet_get_connection_in() == packet_get_connection_out())
1318 close(packet_get_connection_in());
1320 close(packet_get_connection_in());
1321 close(packet_get_connection_out());
1324 * Close all descriptors related to channels. They will still remain
1325 * open in the parent.
1327 /* XXX better use close-on-exec? -markus */
1328 channel_close_all();
1331 * Close any extra file descriptors. Note that there may still be
1332 * descriptors left by system functions. They will be closed later.
1337 * Close any extra open file descriptors so that we don\'t have them
1338 * hanging around in clients. Note that we want to do this after
1339 * initgroups, because at least on Solaris 2.3 it leaves file
1342 for (i = 3; i < 64; i++)
1346 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1347 * xauth are run in the proper environment.
1352 /* Try to get AFS tokens for the local cell. */
1356 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1357 krb_afslog(cell, 0);
1363 /* Change current directory to the user\'s home directory. */
1364 if (chdir(pw->pw_dir) < 0) {
1365 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1366 pw->pw_dir, strerror(errno));
1367 #ifdef HAVE_LOGIN_CAP
1368 if (login_getcapbool(lc, "requirehome", 0))
1374 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1377 if (!options.use_login) {
1378 /* ignore _PATH_SSH_USER_RC for subsystems */
1379 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1380 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1381 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1383 fprintf(stderr, "Running %s\n", cmd);
1384 f = popen(cmd, "w");
1387 fprintf(f, "%s %s\n", s->auth_proto,
1391 fprintf(stderr, "Could not run %s\n",
1393 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1395 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1396 _PATH_SSH_SYSTEM_RC);
1397 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1400 fprintf(f, "%s %s\n", s->auth_proto,
1404 fprintf(stderr, "Could not run %s\n",
1405 _PATH_SSH_SYSTEM_RC);
1406 } else if (do_xauth && options.xauth_location != NULL) {
1407 /* Add authority data to .Xauthority if appropriate. */
1408 char *screen = strchr(s->display, ':');
1412 "Running %.100s add "
1413 "%.100s %.100s %.100s\n",
1414 options.xauth_location, s->display,
1415 s->auth_proto, s->auth_data);
1418 "Adding %.*s/unix%s %s %s\n",
1419 (int)(screen - s->display),
1421 s->auth_proto, s->auth_data);
1423 snprintf(cmd, sizeof cmd, "%s -q -",
1424 options.xauth_location);
1425 f = popen(cmd, "w");
1427 fprintf(f, "add %s %s %s\n", s->display,
1428 s->auth_proto, s->auth_data);
1430 fprintf(f, "add %.*s/unix%s %s %s\n",
1431 (int)(screen - s->display),
1437 fprintf(stderr, "Could not run %s\n",
1441 /* Get the last component of the shell name. */
1442 cp = strrchr(shell, '/');
1449 /* restore SIGPIPE for child */
1450 signal(SIGPIPE, SIG_DFL);
1453 * If we have no command, execute the shell. In this case, the shell
1454 * name to be passed in argv[0] is preceded by '-' to indicate that
1455 * this is a login shell.
1458 if (!options.use_login) {
1461 /* Start the shell. Set initial character to '-'. */
1463 strncpy(buf + 1, cp, sizeof(buf) - 1);
1464 buf[sizeof(buf) - 1] = 0;
1466 /* Execute the shell. */
1469 execve(shell, argv, env);
1471 /* Executing the shell failed. */
1476 /* Launch login(1). */
1478 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1479 #ifdef LOGIN_NEEDS_TERM
1480 s->term? s->term : "unknown",
1482 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1484 /* Login couldn't be executed, die. */
1491 * Execute the command using the user's shell. This uses the -c
1492 * option to execute the command.
1494 argv[0] = (char *) cp;
1496 argv[2] = (char *) command;
1498 execve(shell, argv, env);
1507 static int did_init = 0;
1509 debug("session_new: init");
1510 for(i = 0; i < MAX_SESSIONS; i++) {
1511 sessions[i].used = 0;
1515 for(i = 0; i < MAX_SESSIONS; i++) {
1516 Session *s = &sessions[i];
1518 memset(s, 0, sizeof(*s));
1524 debug("session_new: session %d", i);
1535 for(i = 0; i < MAX_SESSIONS; i++) {
1536 Session *s = &sessions[i];
1537 debug("dump: used %d session %d %p channel %d pid %d",
1547 session_open(Authctxt *authctxt, int chanid)
1549 Session *s = session_new();
1550 debug("session_open: channel %d", chanid);
1552 error("no more sessions");
1555 s->authctxt = authctxt;
1556 s->pw = authctxt->pw;
1558 fatal("no user for session %d", s->self);
1559 debug("session_open: session %d: link with channel %d", s->self, chanid);
1565 session_by_channel(int id)
1568 for(i = 0; i < MAX_SESSIONS; i++) {
1569 Session *s = &sessions[i];
1570 if (s->used && s->chanid == id) {
1571 debug("session_by_channel: session %d channel %d", i, id);
1575 debug("session_by_channel: unknown channel %d", id);
1581 session_by_pid(pid_t pid)
1584 debug("session_by_pid: pid %d", pid);
1585 for(i = 0; i < MAX_SESSIONS; i++) {
1586 Session *s = &sessions[i];
1587 if (s->used && s->pid == pid)
1590 error("session_by_pid: unknown pid %d", pid);
1596 session_window_change_req(Session *s)
1598 s->col = packet_get_int();
1599 s->row = packet_get_int();
1600 s->xpixel = packet_get_int();
1601 s->ypixel = packet_get_int();
1603 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1608 session_pty_req(Session *s)
1614 debug("Allocating a pty not permitted for this authentication.");
1617 if (s->ttyfd != -1) {
1618 packet_disconnect("Protocol error: you already have a pty.");
1622 s->term = packet_get_string(&len);
1625 s->col = packet_get_int();
1626 s->row = packet_get_int();
1628 s->row = packet_get_int();
1629 s->col = packet_get_int();
1631 s->xpixel = packet_get_int();
1632 s->ypixel = packet_get_int();
1634 if (strcmp(s->term, "") == 0) {
1639 /* Allocate a pty and open it. */
1640 debug("Allocating pty.");
1641 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1647 error("session_pty_req: session %d alloc failed", s->self);
1650 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1652 /* for SSH1 the tty modes length is not given */
1654 n_bytes = packet_remaining();
1655 tty_parse_modes(s->ttyfd, &n_bytes);
1658 * Add a cleanup function to clear the utmp entry and record logout
1659 * time in case we call fatal() (e.g., the connection gets closed).
1661 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1662 pty_setowner(s->pw, s->tty);
1664 /* Set window size from the packet. */
1665 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1668 session_proctitle(s);
1673 session_subsystem_req(Session *s)
1678 char *cmd, *subsys = packet_get_string(&len);
1682 log("subsystem request for %s", subsys);
1684 for (i = 0; i < options.num_subsystems; i++) {
1685 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1686 cmd = options.subsystem_command[i];
1687 if (stat(cmd, &st) < 0) {
1688 error("subsystem: cannot stat %s: %s", cmd,
1692 debug("subsystem: exec() %s", cmd);
1693 s->is_subsystem = 1;
1700 log("subsystem request for %s failed, subsystem not found",
1708 session_x11_req(Session *s)
1712 s->single_connection = packet_get_char();
1713 s->auth_proto = packet_get_string(NULL);
1714 s->auth_data = packet_get_string(NULL);
1715 s->screen = packet_get_int();
1718 success = session_setup_x11fwd(s);
1720 xfree(s->auth_proto);
1721 xfree(s->auth_data);
1722 s->auth_proto = NULL;
1723 s->auth_data = NULL;
1729 session_shell_req(Session *s)
1737 session_exec_req(Session *s)
1740 char *command = packet_get_string(&len);
1742 do_exec(s, command);
1748 session_auth_agent_req(Session *s)
1750 static int called = 0;
1752 if (no_agent_forwarding_flag) {
1753 debug("session_auth_agent_req: no_agent_forwarding_flag");
1760 return auth_input_request_forwarding(s->pw);
1765 session_input_channel_req(int id, void *arg)
1774 rtype = packet_get_string(&len);
1775 reply = packet_get_char();
1777 s = session_by_channel(id);
1779 fatal("session_input_channel_req: channel %d: no session", id);
1780 c = channel_lookup(id);
1782 fatal("session_input_channel_req: channel %d: bad channel", id);
1784 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1785 s->self, id, rtype, reply);
1788 * a session is in LARVAL state until a shell, a command
1789 * or a subsystem is executed
1791 if (c->type == SSH_CHANNEL_LARVAL) {
1792 if (strcmp(rtype, "shell") == 0) {
1793 success = session_shell_req(s);
1794 } else if (strcmp(rtype, "exec") == 0) {
1795 success = session_exec_req(s);
1796 } else if (strcmp(rtype, "pty-req") == 0) {
1797 success = session_pty_req(s);
1798 } else if (strcmp(rtype, "x11-req") == 0) {
1799 success = session_x11_req(s);
1800 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1801 success = session_auth_agent_req(s);
1802 } else if (strcmp(rtype, "subsystem") == 0) {
1803 success = session_subsystem_req(s);
1806 if (strcmp(rtype, "window-change") == 0) {
1807 success = session_window_change_req(s);
1811 packet_start(success ?
1812 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1813 packet_put_int(c->remote_id);
1820 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1823 fatal("session_set_fds: called for proto != 2.0");
1825 * now that have a child and a pipe to the child,
1826 * we can activate our channel and register the fd's
1828 if (s->chanid == -1)
1829 fatal("no channel for session %d", s->self);
1830 channel_set_fds(s->chanid,
1832 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1837 * Function to perform pty cleanup. Also called if we get aborted abnormally
1838 * (e.g., due to a dropped connection).
1841 session_pty_cleanup(void *session)
1843 Session *s = session;
1846 error("session_pty_cleanup: no session");
1852 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1854 /* Record that the user has logged out. */
1856 record_logout(s->pid, s->tty);
1858 /* Release the pseudo-tty. */
1859 pty_release(s->tty);
1862 * Close the server side of the socket pairs. We must do this after
1863 * the pty cleanup, so that another process doesn't get this pty
1864 * while we're still cleaning up.
1866 if (close(s->ptymaster) < 0)
1867 error("close(s->ptymaster): %s", strerror(errno));
1871 session_exit_message(Session *s, int status)
1875 fatal("session_close: no session");
1876 c = channel_lookup(s->chanid);
1878 fatal("session_exit_message: session %d: no channel %d",
1879 s->self, s->chanid);
1880 debug("session_exit_message: session %d channel %d pid %d",
1881 s->self, s->chanid, s->pid);
1883 if (WIFEXITED(status)) {
1884 channel_request_start(s->chanid,
1886 packet_put_int(WEXITSTATUS(status));
1888 } else if (WIFSIGNALED(status)) {
1889 channel_request_start(s->chanid,
1891 packet_put_int(WTERMSIG(status));
1893 packet_put_char(WCOREDUMP(status));
1894 #else /* WCOREDUMP */
1896 #endif /* WCOREDUMP */
1897 packet_put_cstring("");
1898 packet_put_cstring("");
1901 /* Some weird exit cause. Just exit. */
1902 packet_disconnect("wait returned status %04x.", status);
1905 /* disconnect channel */
1906 debug("session_exit_message: release channel %d", s->chanid);
1907 channel_cancel_cleanup(s->chanid);
1909 * emulate a write failure with 'chan_write_failed', nobody will be
1910 * interested in data we write.
1911 * Note that we must not call 'chan_read_failed', since there could
1912 * be some more data waiting in the pipe.
1914 if (c->ostate != CHAN_OUTPUT_CLOSED)
1915 chan_write_failed(c);
1920 session_close(Session *s)
1922 debug("session_close: session %d pid %d", s->self, s->pid);
1923 if (s->ttyfd != -1) {
1924 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1925 session_pty_cleanup(s);
1932 xfree(s->auth_data);
1934 xfree(s->auth_proto);
1936 session_proctitle(s);
1940 session_close_by_pid(pid_t pid, int status)
1942 Session *s = session_by_pid(pid);
1944 debug("session_close_by_pid: no session for pid %d", pid);
1947 if (s->chanid != -1)
1948 session_exit_message(s, status);
1953 * this is called when a channel dies before
1954 * the session 'child' itself dies
1957 session_close_by_channel(int id, void *arg)
1959 Session *s = session_by_channel(id);
1961 debug("session_close_by_channel: no session for id %d", id);
1964 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1967 debug("session_close_by_channel: channel %d: has child", id);
1970 /* detach by removing callback */
1971 channel_cancel_cleanup(s->chanid);
1977 session_destroy_all(void)
1980 for(i = 0; i < MAX_SESSIONS; i++) {
1981 Session *s = &sessions[i];
1988 session_tty_list(void)
1990 static char buf[1024];
1993 for(i = 0; i < MAX_SESSIONS; i++) {
1994 Session *s = &sessions[i];
1995 if (s->used && s->ttyfd != -1) {
1997 strlcat(buf, ",", sizeof buf);
1998 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2002 strlcpy(buf, "notty", sizeof buf);
2007 session_proctitle(Session *s)
2010 error("no user for session %d", s->self);
2012 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2016 session_setup_x11fwd(Session *s)
2020 if (no_x11_forwarding_flag) {
2021 packet_send_debug("X11 forwarding disabled in user configuration file.");
2024 if (!options.x11_forwarding) {
2025 debug("X11 forwarding disabled in server configuration file.");
2028 if (!options.xauth_location ||
2029 (stat(options.xauth_location, &st) == -1)) {
2030 packet_send_debug("No xauth program; cannot forward with spoofing.");
2033 if (options.use_login) {
2034 packet_send_debug("X11 forwarding disabled; "
2035 "not compatible with UseLogin=yes.");
2038 if (s->display != NULL) {
2039 debug("X11 display already set.");
2042 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
2043 if (s->display == NULL) {
2044 debug("x11_create_display_inet failed.");
2051 do_authenticated2(Authctxt *authctxt)
2053 server_loop2(authctxt);