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.100 2001/08/16 19:18:34 jakob 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 void do_child(Session *, const char *);
134 int check_quietlogin(Session *, const char *);
136 static void do_authenticated1(Authctxt *);
137 static void do_authenticated2(Authctxt *);
139 static void session_close(Session *);
140 static int session_pty_req(Session *);
143 extern ServerOptions options;
144 extern char *__progname;
145 extern int log_stderr;
146 extern int debug_flag;
147 extern u_int utmp_len;
148 extern int startup_pipe;
149 extern void destroy_sensitive_data(void);
151 /* original command from peer. */
152 const char *original_command = NULL;
155 #define MAX_SESSIONS 10
156 Session sessions[MAX_SESSIONS];
158 #ifdef WITH_AIXAUTHENTICATE
159 /* AIX's lastlogin message, set in auth1.c */
161 #endif /* WITH_AIXAUTHENTICATE */
163 #ifdef HAVE_LOGIN_CAP
164 static login_cap_t *lc;
168 do_authenticated(Authctxt *authctxt)
171 * Cancel the alarm we set to limit the time taken for
175 if (startup_pipe != -1) {
179 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
180 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
181 error("unable to get login class");
185 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
186 packet_disconnect("Approval failure for %s",
187 authctxt->pw->pw_name);
191 /* setup the channel layer */
192 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
193 channel_permit_all_opens();
196 do_authenticated2(authctxt);
198 do_authenticated1(authctxt);
200 /* remove agent socket */
201 if (auth_get_socket_name())
202 auth_sock_cleanup_proc(authctxt->pw);
204 if (options.kerberos_ticket_cleanup)
205 krb4_cleanup_proc(authctxt);
208 if (options.kerberos_ticket_cleanup)
209 krb5_cleanup_proc(authctxt);
214 * Prepares for an interactive session. This is called after the user has
215 * been successfully authenticated. During this message exchange, pseudo
216 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
217 * are requested, etc.
220 do_authenticated1(Authctxt *authctxt)
224 int success, type, plen, screen_flag;
225 int compression_level = 0, enable_compression_after_reply = 0;
226 u_int proto_len, data_len, dlen;
229 s->authctxt = authctxt;
230 s->pw = authctxt->pw;
233 * We stay in this loop until the client requests to execute a shell
239 /* Get a packet from the client. */
240 type = packet_read(&plen);
242 /* Process the packet. */
244 case SSH_CMSG_REQUEST_COMPRESSION:
245 packet_integrity_check(plen, 4, type);
246 compression_level = packet_get_int();
247 if (compression_level < 1 || compression_level > 9) {
248 packet_send_debug("Received illegal compression level %d.",
252 /* Enable compression after we have responded with SUCCESS. */
253 enable_compression_after_reply = 1;
257 case SSH_CMSG_REQUEST_PTY:
258 success = session_pty_req(s);
261 case SSH_CMSG_X11_REQUEST_FORWARDING:
262 s->auth_proto = packet_get_string(&proto_len);
263 s->auth_data = packet_get_string(&data_len);
265 screen_flag = packet_get_protocol_flags() &
266 SSH_PROTOFLAG_SCREEN_NUMBER;
267 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
269 if (packet_remaining() == 4) {
271 debug2("Buggy client: "
272 "X11 screen flag missing");
273 s->screen = packet_get_int();
278 success = session_setup_x11fwd(s);
280 xfree(s->auth_proto);
282 s->auth_proto = NULL;
287 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
288 if (no_agent_forwarding_flag || compat13) {
289 debug("Authentication agent forwarding not permitted for this authentication.");
292 debug("Received authentication agent forwarding request.");
293 success = auth_input_request_forwarding(s->pw);
296 case SSH_CMSG_PORT_FORWARD_REQUEST:
297 if (no_port_forwarding_flag) {
298 debug("Port forwarding not permitted for this authentication.");
301 if (!options.allow_tcp_forwarding) {
302 debug("Port forwarding not permitted.");
305 debug("Received TCP/IP port forwarding request.");
306 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
310 case SSH_CMSG_MAX_PACKET_SIZE:
311 if (packet_set_maxsize(packet_get_int()) > 0)
315 #if defined(AFS) || defined(KRB5)
316 case SSH_CMSG_HAVE_KERBEROS_TGT:
317 if (!options.kerberos_tgt_passing) {
318 verbose("Kerberos TGT passing disabled.");
320 char *kdata = packet_get_string(&dlen);
321 packet_integrity_check(plen, 4 + dlen, type);
323 /* XXX - 0x41, see creds_to_radix version */
324 if (kdata[0] != 0x41) {
330 if (auth_krb5_tgt(s->authctxt, &tgt))
333 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
337 if (auth_krb4_tgt(s->authctxt, kdata))
340 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
346 #endif /* AFS || KRB5 */
349 case SSH_CMSG_HAVE_AFS_TOKEN:
350 if (!options.afs_token_passing || !k_hasafs()) {
351 verbose("AFS token passing disabled.");
353 /* Accept AFS token. */
354 char *token = packet_get_string(&dlen);
355 packet_integrity_check(plen, 4 + dlen, type);
357 if (auth_afs_token(s->authctxt, token))
360 verbose("AFS token refused for %.100s",
367 case SSH_CMSG_EXEC_SHELL:
368 case SSH_CMSG_EXEC_CMD:
369 if (type == SSH_CMSG_EXEC_CMD) {
370 command = packet_get_string(&dlen);
371 debug("Exec command '%.500s'", command);
383 * Any unknown messages in this phase are ignored,
384 * and a failure message is returned.
386 log("Unknown packet type received after authentication: %d", type);
388 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
392 /* Enable compression now that we have replied if appropriate. */
393 if (enable_compression_after_reply) {
394 enable_compression_after_reply = 0;
395 packet_start_compression(compression_level);
401 * This is called to fork and execute a command when we have no tty. This
402 * will call do_child from the child, and server_loop from the parent after
403 * setting up file descriptors and such.
406 do_exec_no_pty(Session *s, const char *command)
411 int pin[2], pout[2], perr[2];
412 /* Allocate pipes for communicating with the program. */
413 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
414 packet_disconnect("Could not create pipes: %.100s",
416 #else /* USE_PIPES */
417 int inout[2], err[2];
418 /* Uses socket pairs to communicate with the program. */
419 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
420 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
421 packet_disconnect("Could not create socket pairs: %.100s",
423 #endif /* USE_PIPES */
425 fatal("do_exec_no_pty: no session");
427 session_proctitle(s);
430 do_pam_session(s->pw->pw_name, NULL);
434 /* Fork the child. */
435 if ((pid = fork()) == 0) {
436 /* Child. Reinitialize the log since the pid has changed. */
437 log_init(__progname, options.log_level, options.log_facility, log_stderr);
440 * Create a new session and process group since the 4.4BSD
441 * setlogin() affects the entire process group.
444 error("setsid failed: %.100s", strerror(errno));
448 * Redirect stdin. We close the parent side of the socket
449 * pair, and make the child side the standard input.
452 if (dup2(pin[0], 0) < 0)
453 perror("dup2 stdin");
456 /* Redirect stdout. */
458 if (dup2(pout[1], 1) < 0)
459 perror("dup2 stdout");
462 /* Redirect stderr. */
464 if (dup2(perr[1], 2) < 0)
465 perror("dup2 stderr");
467 #else /* USE_PIPES */
469 * Redirect stdin, stdout, and stderr. Stdin and stdout will
470 * use the same socket, as some programs (particularly rdist)
471 * seem to depend on it.
475 if (dup2(inout[0], 0) < 0) /* stdin */
476 perror("dup2 stdin");
477 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
478 perror("dup2 stdout");
479 if (dup2(err[0], 2) < 0) /* stderr */
480 perror("dup2 stderr");
481 #endif /* USE_PIPES */
483 /* Do processing for the child (exec command etc). */
484 do_child(s, command);
489 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
492 packet_disconnect("fork failed: %.100s", strerror(errno));
494 /* Set interactive/non-interactive mode. */
495 packet_set_interactive(s->display != NULL);
497 /* We are the parent. Close the child sides of the pipes. */
503 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
505 /* Enter the interactive session. */
506 server_loop(pid, pin[1], pout[0], perr[0]);
507 /* server_loop has closed pin[1], pout[0], and perr[0]. */
509 #else /* USE_PIPES */
510 /* We are the parent. Close the child sides of the socket pairs. */
515 * Enter the interactive session. Note: server_loop must be able to
516 * handle the case that fdin and fdout are the same.
519 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
521 server_loop(pid, inout[1], inout[1], err[1]);
522 /* server_loop has closed inout[1] and err[1]. */
524 #endif /* USE_PIPES */
528 * This is called to fork and execute a command when we have a tty. This
529 * will call do_child from the child, and server_loop from the parent after
530 * setting up file descriptors, controlling tty, updating wtmp, utmp,
531 * lastlog, and other such operations.
534 do_exec_pty(Session *s, const char *command)
536 int fdout, ptyfd, ttyfd, ptymaster;
540 fatal("do_exec_pty: no session");
545 do_pam_session(s->pw->pw_name, s->tty);
549 /* Fork the child. */
550 if ((pid = fork()) == 0) {
552 /* Child. Reinitialize the log because the pid has changed. */
553 log_init(__progname, options.log_level, options.log_facility, log_stderr);
554 /* Close the master side of the pseudo tty. */
557 /* Make the pseudo tty our controlling tty. */
558 pty_make_controlling_tty(&ttyfd, s->tty);
560 /* Redirect stdin from the pseudo tty. */
561 if (dup2(ttyfd, fileno(stdin)) < 0)
562 error("dup2 stdin failed: %.100s", strerror(errno));
564 /* Redirect stdout to the pseudo tty. */
565 if (dup2(ttyfd, fileno(stdout)) < 0)
566 error("dup2 stdin failed: %.100s", strerror(errno));
568 /* Redirect stderr to the pseudo tty. */
569 if (dup2(ttyfd, fileno(stderr)) < 0)
570 error("dup2 stdin failed: %.100s", strerror(errno));
572 /* Close the extra descriptor for the pseudo tty. */
575 /* record login, etc. similar to login(1) */
577 if (!(options.use_login && command == NULL))
578 do_login(s, command);
579 # ifdef LOGIN_NEEDS_UTMPX
585 /* Do common processing for the child, such as execing the command. */
586 do_child(s, command);
591 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
594 packet_disconnect("fork failed: %.100s", strerror(errno));
597 /* Parent. Close the slave side of the pseudo tty. */
601 * Create another descriptor of the pty master side for use as the
602 * standard input. We could use the original descriptor, but this
603 * simplifies code in server_loop. The descriptor is bidirectional.
607 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
609 /* we keep a reference to the pty master */
610 ptymaster = dup(ptyfd);
612 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
613 s->ptymaster = ptymaster;
615 /* Enter interactive session. */
616 packet_set_interactive(1);
618 session_set_fds(s, ptyfd, fdout, -1);
620 server_loop(pid, ptyfd, fdout, -1);
621 /* server_loop _has_ closed ptyfd and fdout. */
625 #ifdef LOGIN_NEEDS_UTMPX
627 do_pre_login(Session *s)
630 struct sockaddr_storage from;
631 pid_t pid = getpid();
634 * Get IP address of client. If the connection is not a socket, let
635 * the address be 0.0.0.0.
637 memset(&from, 0, sizeof(from));
638 if (packet_connection_is_on_socket()) {
639 fromlen = sizeof(from);
640 if (getpeername(packet_get_connection_in(),
641 (struct sockaddr *) & from, &fromlen) < 0) {
642 debug("getpeername: %.100s", strerror(errno));
647 record_utmp_only(pid, s->tty, s->pw->pw_name,
648 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
649 (struct sockaddr *)&from);
654 * This is called to fork and execute a command. If another command is
655 * to be forced, execute that instead.
658 do_exec(Session *s, const char *command)
660 if (forced_command) {
661 original_command = command;
662 command = forced_command;
663 debug("Forced command '%.900s'", command);
667 do_exec_pty(s, command);
669 do_exec_no_pty(s, command);
671 original_command = NULL;
674 /* administrative, login(1)-like work */
676 do_login(Session *s, const char *command)
679 char hostname[MAXHOSTNAMELEN];
681 struct sockaddr_storage from;
682 time_t last_login_time;
683 struct passwd * pw = s->pw;
684 pid_t pid = getpid();
687 * Get IP address of client. If the connection is not a socket, let
688 * the address be 0.0.0.0.
690 memset(&from, 0, sizeof(from));
691 if (packet_connection_is_on_socket()) {
692 fromlen = sizeof(from);
693 if (getpeername(packet_get_connection_in(),
694 (struct sockaddr *) & from, &fromlen) < 0) {
695 debug("getpeername: %.100s", strerror(errno));
700 /* Get the time and hostname when the user last logged in. */
701 if (options.print_lastlog) {
703 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
704 hostname, sizeof(hostname));
707 /* Record that there was a login on that tty from the remote host. */
708 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
709 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
710 (struct sockaddr *)&from);
714 * If password change is needed, do it now.
715 * This needs to occur before the ~/.hushlogin check.
717 if (is_pam_password_change_required()) {
718 print_pam_messages();
723 if (check_quietlogin(s, command))
727 if (!is_pam_password_change_required())
728 print_pam_messages();
730 #ifdef WITH_AIXAUTHENTICATE
731 if (aixloginmsg && *aixloginmsg)
732 printf("%s\n", aixloginmsg);
733 #endif /* WITH_AIXAUTHENTICATE */
735 if (options.print_lastlog && last_login_time != 0) {
736 time_string = ctime(&last_login_time);
737 if (strchr(time_string, '\n'))
738 *strchr(time_string, '\n') = 0;
739 if (strcmp(hostname, "") == 0)
740 printf("Last login: %s\r\n", time_string);
742 printf("Last login: %s from %s\r\n", time_string, hostname);
749 * Display the message of the day.
757 if (options.print_motd) {
758 #ifdef HAVE_LOGIN_CAP
759 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
762 f = fopen("/etc/motd", "r");
765 while (fgets(buf, sizeof(buf), f))
774 * Check for quiet login, either .hushlogin or command given.
777 check_quietlogin(Session *s, const char *command)
780 struct passwd *pw = s->pw;
783 /* Return 1 if .hushlogin exists or a command given. */
786 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
787 #ifdef HAVE_LOGIN_CAP
788 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
791 if (stat(buf, &st) >= 0)
798 * Sets the value of the given variable in the environment. If the variable
799 * already exists, its value is overriden.
802 child_set_env(char ***envp, u_int *envsizep, const char *name,
809 * Find the slot where the value should be stored. If the variable
810 * already exists, we reuse the slot; otherwise we append a new slot
811 * at the end of the array, expanding if necessary.
814 namelen = strlen(name);
815 for (i = 0; env[i]; i++)
816 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
819 /* Reuse the slot. */
822 /* New variable. Expand if necessary. */
823 if (i >= (*envsizep) - 1) {
825 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
827 /* Need to set the NULL pointer at end of array beyond the new slot. */
831 /* Allocate space and format the variable in the appropriate slot. */
832 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
833 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
837 * Reads environment variables from the given file and adds/overrides them
838 * into the environment. If the file does not exist, this does nothing.
839 * Otherwise, it must consist of empty lines, comments (line starts with '#')
840 * and assignments of the form name=value. No other forms are allowed.
843 read_environment_file(char ***env, u_int *envsize,
844 const char *filename)
850 f = fopen(filename, "r");
854 while (fgets(buf, sizeof(buf), f)) {
855 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
857 if (!*cp || *cp == '#' || *cp == '\n')
859 if (strchr(cp, '\n'))
860 *strchr(cp, '\n') = '\0';
861 value = strchr(cp, '=');
863 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
867 * Replace the equals sign by nul, and advance value to
872 child_set_env(env, envsize, cp, value);
879 * Sets any environment variables which have been specified by PAM
881 void do_pam_environment(char ***env, u_int *envsize)
883 char *equals, var_name[512], var_val[512];
887 if ((pam_env = fetch_pam_environment()) == NULL)
890 for(i = 0; pam_env[i] != NULL; i++) {
891 if ((equals = strstr(pam_env[i], "=")) == NULL)
894 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
895 memset(var_name, '\0', sizeof(var_name));
896 memset(var_val, '\0', sizeof(var_val));
898 strncpy(var_name, pam_env[i], equals - pam_env[i]);
899 strcpy(var_val, equals + 1);
901 debug3("PAM environment: %s=%s", var_name, var_val);
903 child_set_env(env, envsize, var_name, var_val);
910 void copy_environment(char ***env, u_int *envsize)
912 char *equals, var_name[512], var_val[512];
915 for(i = 0; environ[i] != NULL; i++) {
916 if ((equals = strstr(environ[i], "=")) == NULL)
919 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
920 memset(var_name, '\0', sizeof(var_name));
921 memset(var_val, '\0', sizeof(var_val));
923 strncpy(var_name, environ[i], equals - environ[i]);
924 strcpy(var_val, equals + 1);
926 debug3("Copy environment: %s=%s", var_name, var_val);
928 child_set_env(env, envsize, var_name, var_val);
934 #if defined(HAVE_GETUSERATTR)
936 * AIX-specific login initialisation
938 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
943 getrlimit(resource, &rlim);
946 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
948 rlim.rlim_cur = RLIM_INFINITY;
949 } else if (slim != 0) {
950 /* See the wackiness below */
951 if (rlim.rlim_cur == slim * mult)
954 rlim.rlim_cur = slim * mult;
959 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
961 rlim.rlim_max = RLIM_INFINITY;
962 } else if (hlim != 0) {
963 rlim.rlim_max = hlim * mult;
968 * XXX For cpu and fsize the soft limit is set to the hard limit
969 * if the hard limit is left at its default value and the soft limit
970 * is changed from its default value, either by requesting it
971 * (slim == 0) or by setting it to the current default. At least
972 * that's how rlogind does it. If you're confused you're not alone.
973 * Bug or feature? AIX 4.3.1.2
975 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
976 && hlim == 0 && slim != 0)
977 rlim.rlim_max = rlim.rlim_cur;
978 /* A specified hard limit limits the soft limit */
979 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
980 rlim.rlim_cur = rlim.rlim_max;
981 /* A soft limit can increase a hard limit */
982 else if (rlim.rlim_cur > rlim.rlim_max)
983 rlim.rlim_max = rlim.rlim_cur;
985 if (setrlimit(resource, &rlim) != 0)
986 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
989 void set_limits_from_userattr(char *user)
994 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
995 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
996 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
997 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
998 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
999 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1000 #if defined(S_UNOFILE)
1001 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1004 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1005 /* Convert decimal to octal */
1006 (void) snprintf(buf, sizeof(buf), "%d", mask);
1007 if (sscanf(buf, "%o", &mask) == 1)
1011 #endif /* defined(HAVE_GETUSERATTR) */
1014 * Performs common processing for the child, such as setting up the
1015 * environment, closing extra file descriptors, setting the user and group
1016 * ids, and executing the command or shell.
1019 do_child(Session *s, const char *command)
1021 const char *shell, *hostname = NULL, *cp = NULL;
1022 struct passwd *pw = s->pw;
1028 extern char **environ;
1032 #ifdef WITH_IRIX_PROJECT
1034 #endif /* WITH_IRIX_PROJECT */
1035 #ifdef WITH_IRIX_JOBS
1038 #ifdef WITH_IRIX_ARRAY
1040 #endif /* WITH_IRIX_ARRAY */
1041 #endif /* WITH_IRIX_JOBS */
1044 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1046 /* remove hostkey from the child's memory */
1047 destroy_sensitive_data();
1049 /* login(1) is only called if we execute the login shell */
1050 if (options.use_login && command != NULL)
1051 options.use_login = 0;
1053 #if !defined(HAVE_OSF_SIA)
1054 if (!options.use_login) {
1055 # ifdef HAVE_LOGIN_CAP
1056 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1057 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1058 _PATH_NOLOGIN), "r");
1059 # else /* HAVE_LOGIN_CAP */
1061 f = fopen(_PATH_NOLOGIN, "r");
1062 # endif /* HAVE_LOGIN_CAP */
1064 /* /etc/nologin exists. Print its contents and exit. */
1065 while (fgets(buf, sizeof(buf), f))
1071 #endif /* HAVE_OSF_SIA */
1073 /* Set login name, uid, gid, and groups. */
1074 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1075 switch, so we let login(1) to this for us. */
1076 if (!options.use_login) {
1078 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1079 if (!check_quietlogin(s, command))
1081 #else /* HAVE_OSF_SIA */
1085 if (getuid() == 0 || geteuid() == 0) {
1087 # ifdef HAVE_GETUSERATTR
1088 set_limits_from_userattr(pw->pw_name);
1089 # endif /* HAVE_GETUSERATTR */
1090 # ifdef HAVE_LOGIN_CAP
1091 if (setusercontext(lc, pw, pw->pw_uid,
1092 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1093 perror("unable to set user context");
1096 # else /* HAVE_LOGIN_CAP */
1097 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1098 /* Sets login uid for accounting */
1099 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1100 error("setluid: %s", strerror(errno));
1101 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1103 if (setlogin(pw->pw_name) < 0)
1104 error("setlogin failed: %s", strerror(errno));
1105 if (setgid(pw->pw_gid) < 0) {
1109 /* Initialize the group list. */
1110 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1111 perror("initgroups");
1117 * PAM credentials may take the form of
1118 * supplementary groups. These will have been
1119 * wiped by the above initgroups() call.
1120 * Reestablish them here.
1123 # endif /* USE_PAM */
1124 # ifdef WITH_IRIX_JOBS
1125 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1127 fatal("Failed to create job container: %.100s",
1130 # endif /* WITH_IRIX_JOBS */
1131 # ifdef WITH_IRIX_ARRAY
1132 /* initialize array session */
1134 if (newarraysess() != 0)
1135 fatal("Failed to set up new array session: %.100s",
1138 # endif /* WITH_IRIX_ARRAY */
1139 # ifdef WITH_IRIX_PROJECT
1140 /* initialize irix project info */
1141 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1142 debug("Failed to get project id, using projid 0");
1145 if (setprid(projid))
1146 fatal("Failed to initialize project %d for %s: %.100s",
1147 (int)projid, pw->pw_name, strerror(errno));
1148 # endif /* WITH_IRIX_PROJECT */
1149 #ifdef WITH_IRIX_AUDIT
1150 if (sysconf(_SC_AUDIT)) {
1151 debug("Setting sat id to %d", (int) pw->pw_uid);
1152 if (satsetid(pw->pw_uid))
1153 debug("error setting satid: %.100s", strerror(errno));
1155 #endif /* WITH_IRIX_AUDIT */
1159 * AIX has a "usrinfo" area where logname and
1160 * other stuff is stored - a few applications
1161 * actually use this and die if it's not set
1165 cp = xmalloc(22 + strlen(s->tty) +
1166 2 * strlen(pw->pw_name));
1167 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1168 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1169 if (usrinfo(SETUINFO, cp, i) == -1)
1170 fatal("Couldn't set usrinfo: %s",
1172 debug3("AIX/UsrInfo: set len %d", i);
1176 /* Permanently switch to the desired uid. */
1177 permanently_set_uid(pw);
1178 # endif /* HAVE_LOGIN_CAP */
1180 #endif /* HAVE_OSF_SIA */
1185 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1186 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1189 * Get the shell from the password data. An empty shell field is
1190 * legal, and means /bin/sh.
1192 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1193 #ifdef HAVE_LOGIN_CAP
1194 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1198 /* Try to get AFS tokens for the local cell. */
1202 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1203 krb_afslog(cell, 0);
1209 /* Initialize the environment. */
1211 env = xmalloc(envsize * sizeof(char *));
1216 * The Windows environment contains some setting which are
1217 * important for a running system. They must not be dropped.
1219 copy_environment(&env, &envsize);
1222 if (!options.use_login) {
1223 /* Set basic environment. */
1224 child_set_env(&env, &envsize, "USER", pw->pw_name);
1225 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1226 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1227 #ifdef HAVE_LOGIN_CAP
1228 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1229 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1230 #else /* HAVE_LOGIN_CAP */
1231 # ifndef HAVE_CYGWIN
1233 * There's no standard path on Windows. The path contains
1234 * important components pointing to the system directories,
1235 * needed for loading shared libraries. So the path better
1236 * remains intact here.
1238 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1239 # endif /* HAVE_CYGWIN */
1240 #endif /* HAVE_LOGIN_CAP */
1242 snprintf(buf, sizeof buf, "%.200s/%.50s",
1243 _PATH_MAILDIR, pw->pw_name);
1244 child_set_env(&env, &envsize, "MAIL", buf);
1246 /* Normal systems set SHELL by default. */
1247 child_set_env(&env, &envsize, "SHELL", shell);
1250 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1252 /* Set custom environment options from RSA authentication. */
1253 while (custom_environment) {
1254 struct envstring *ce = custom_environment;
1257 for (i = 0; s[i] != '=' && s[i]; i++);
1260 child_set_env(&env, &envsize, s, s + i + 1);
1262 custom_environment = ce->next;
1267 snprintf(buf, sizeof buf, "%.50s %d %d",
1268 get_remote_ipaddr(), get_remote_port(), get_local_port());
1269 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1272 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1274 child_set_env(&env, &envsize, "TERM", s->term);
1276 child_set_env(&env, &envsize, "DISPLAY", s->display);
1277 if (original_command)
1278 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1282 if ((cp = getenv("AUTHSTATE")) != NULL)
1283 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1284 if ((cp = getenv("KRB5CCNAME")) != NULL)
1285 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1286 read_environment_file(&env, &envsize, "/etc/environment");
1289 if (s->authctxt->krb4_ticket_file)
1290 child_set_env(&env, &envsize, "KRBTKFILE",
1291 s->authctxt->krb4_ticket_file);
1294 if (s->authctxt->krb5_ticket_file)
1295 child_set_env(&env, &envsize, "KRB5CCNAME",
1296 s->authctxt->krb5_ticket_file);
1299 /* Pull in any environment variables that may have been set by PAM. */
1300 do_pam_environment(&env, &envsize);
1301 #endif /* USE_PAM */
1303 if (auth_get_socket_name() != NULL)
1304 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1305 auth_get_socket_name());
1307 /* read $HOME/.ssh/environment. */
1308 if (!options.use_login) {
1309 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1311 read_environment_file(&env, &envsize, buf);
1314 /* dump the environment */
1315 fprintf(stderr, "Environment:\n");
1316 for (i = 0; env[i]; i++)
1317 fprintf(stderr, " %.200s\n", env[i]);
1319 /* we have to stash the hostname before we close our socket. */
1320 if (options.use_login)
1321 hostname = get_remote_name_or_ip(utmp_len,
1322 options.reverse_mapping_check);
1324 * Close the connection descriptors; note that this is the child, and
1325 * the server will still have the socket open, and it is important
1326 * that we do not shutdown it. Note that the descriptors cannot be
1327 * closed before building the environment, as we call
1328 * get_remote_ipaddr there.
1330 if (packet_get_connection_in() == packet_get_connection_out())
1331 close(packet_get_connection_in());
1333 close(packet_get_connection_in());
1334 close(packet_get_connection_out());
1337 * Close all descriptors related to channels. They will still remain
1338 * open in the parent.
1340 /* XXX better use close-on-exec? -markus */
1341 channel_close_all();
1344 * Close any extra file descriptors. Note that there may still be
1345 * descriptors left by system functions. They will be closed later.
1350 * Close any extra open file descriptors so that we don\'t have them
1351 * hanging around in clients. Note that we want to do this after
1352 * initgroups, because at least on Solaris 2.3 it leaves file
1355 for (i = 3; i < 64; i++)
1358 /* Change current directory to the user\'s home directory. */
1359 if (chdir(pw->pw_dir) < 0) {
1360 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1361 pw->pw_dir, strerror(errno));
1362 #ifdef HAVE_LOGIN_CAP
1363 if (login_getcapbool(lc, "requirehome", 0))
1369 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1370 * xauth are run in the proper environment.
1375 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1378 if (!options.use_login) {
1379 /* ignore _PATH_SSH_USER_RC for subsystems */
1380 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1381 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1382 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1384 fprintf(stderr, "Running %s\n", cmd);
1385 f = popen(cmd, "w");
1388 fprintf(f, "%s %s\n", s->auth_proto,
1392 fprintf(stderr, "Could not run %s\n",
1394 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1396 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1397 _PATH_SSH_SYSTEM_RC);
1398 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1401 fprintf(f, "%s %s\n", s->auth_proto,
1405 fprintf(stderr, "Could not run %s\n",
1406 _PATH_SSH_SYSTEM_RC);
1407 } else if (do_xauth && options.xauth_location != NULL) {
1408 /* Add authority data to .Xauthority if appropriate. */
1409 char *screen = strchr(s->display, ':');
1413 "Running %.100s add "
1414 "%.100s %.100s %.100s\n",
1415 options.xauth_location, s->display,
1416 s->auth_proto, s->auth_data);
1419 "Adding %.*s/unix%s %s %s\n",
1420 (int)(screen - s->display),
1422 s->auth_proto, s->auth_data);
1424 snprintf(cmd, sizeof cmd, "%s -q -",
1425 options.xauth_location);
1426 f = popen(cmd, "w");
1428 fprintf(f, "add %s %s %s\n", s->display,
1429 s->auth_proto, s->auth_data);
1431 fprintf(f, "add %.*s/unix%s %s %s\n",
1432 (int)(screen - s->display),
1438 fprintf(stderr, "Could not run %s\n",
1442 /* Get the last component of the shell name. */
1443 cp = strrchr(shell, '/');
1450 /* restore SIGPIPE for child */
1451 signal(SIGPIPE, SIG_DFL);
1454 * If we have no command, execute the shell. In this case, the shell
1455 * name to be passed in argv[0] is preceded by '-' to indicate that
1456 * this is a login shell.
1459 if (!options.use_login) {
1462 /* Start the shell. Set initial character to '-'. */
1464 strncpy(buf + 1, cp, sizeof(buf) - 1);
1465 buf[sizeof(buf) - 1] = 0;
1467 /* Execute the shell. */
1470 execve(shell, argv, env);
1472 /* Executing the shell failed. */
1477 /* Launch login(1). */
1479 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1480 #ifdef LOGIN_NEEDS_TERM
1481 s->term? s->term : "unknown",
1483 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1485 /* Login couldn't be executed, die. */
1492 * Execute the command using the user's shell. This uses the -c
1493 * option to execute the command.
1495 argv[0] = (char *) cp;
1497 argv[2] = (char *) command;
1499 execve(shell, argv, env);
1508 static int did_init = 0;
1510 debug("session_new: init");
1511 for(i = 0; i < MAX_SESSIONS; i++) {
1512 sessions[i].used = 0;
1516 for(i = 0; i < MAX_SESSIONS; i++) {
1517 Session *s = &sessions[i];
1519 memset(s, 0, sizeof(*s));
1525 debug("session_new: session %d", i);
1536 for(i = 0; i < MAX_SESSIONS; i++) {
1537 Session *s = &sessions[i];
1538 debug("dump: used %d session %d %p channel %d pid %d",
1548 session_open(Authctxt *authctxt, int chanid)
1550 Session *s = session_new();
1551 debug("session_open: channel %d", chanid);
1553 error("no more sessions");
1556 s->authctxt = authctxt;
1557 s->pw = authctxt->pw;
1559 fatal("no user for session %d", s->self);
1560 debug("session_open: session %d: link with channel %d", s->self, chanid);
1566 session_by_channel(int id)
1569 for(i = 0; i < MAX_SESSIONS; i++) {
1570 Session *s = &sessions[i];
1571 if (s->used && s->chanid == id) {
1572 debug("session_by_channel: session %d channel %d", i, id);
1576 debug("session_by_channel: unknown channel %d", id);
1582 session_by_pid(pid_t pid)
1585 debug("session_by_pid: pid %d", pid);
1586 for(i = 0; i < MAX_SESSIONS; i++) {
1587 Session *s = &sessions[i];
1588 if (s->used && s->pid == pid)
1591 error("session_by_pid: unknown pid %d", pid);
1597 session_window_change_req(Session *s)
1599 s->col = packet_get_int();
1600 s->row = packet_get_int();
1601 s->xpixel = packet_get_int();
1602 s->ypixel = packet_get_int();
1604 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1609 session_pty_req(Session *s)
1615 debug("Allocating a pty not permitted for this authentication.");
1618 if (s->ttyfd != -1) {
1619 packet_disconnect("Protocol error: you already have a pty.");
1623 s->term = packet_get_string(&len);
1626 s->col = packet_get_int();
1627 s->row = packet_get_int();
1629 s->row = packet_get_int();
1630 s->col = packet_get_int();
1632 s->xpixel = packet_get_int();
1633 s->ypixel = packet_get_int();
1635 if (strcmp(s->term, "") == 0) {
1640 /* Allocate a pty and open it. */
1641 debug("Allocating pty.");
1642 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1648 error("session_pty_req: session %d alloc failed", s->self);
1651 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1653 /* for SSH1 the tty modes length is not given */
1655 n_bytes = packet_remaining();
1656 tty_parse_modes(s->ttyfd, &n_bytes);
1659 * Add a cleanup function to clear the utmp entry and record logout
1660 * time in case we call fatal() (e.g., the connection gets closed).
1662 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1663 pty_setowner(s->pw, s->tty);
1665 /* Set window size from the packet. */
1666 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1669 session_proctitle(s);
1674 session_subsystem_req(Session *s)
1678 char *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 debug("subsystem: exec() %s", options.subsystem_command[i]);
1687 s->is_subsystem = 1;
1688 do_exec_no_pty(s, options.subsystem_command[i]);
1694 log("subsystem request for %s failed, subsystem not found", subsys);
1701 session_x11_req(Session *s)
1705 s->single_connection = packet_get_char();
1706 s->auth_proto = packet_get_string(NULL);
1707 s->auth_data = packet_get_string(NULL);
1708 s->screen = packet_get_int();
1711 success = session_setup_x11fwd(s);
1713 xfree(s->auth_proto);
1714 xfree(s->auth_data);
1715 s->auth_proto = NULL;
1716 s->auth_data = NULL;
1722 session_shell_req(Session *s)
1730 session_exec_req(Session *s)
1733 char *command = packet_get_string(&len);
1735 do_exec(s, command);
1741 session_auth_agent_req(Session *s)
1743 static int called = 0;
1745 if (no_agent_forwarding_flag) {
1746 debug("session_auth_agent_req: no_agent_forwarding_flag");
1753 return auth_input_request_forwarding(s->pw);
1758 session_input_channel_req(int id, void *arg)
1767 rtype = packet_get_string(&len);
1768 reply = packet_get_char();
1770 s = session_by_channel(id);
1772 fatal("session_input_channel_req: channel %d: no session", id);
1773 c = channel_lookup(id);
1775 fatal("session_input_channel_req: channel %d: bad channel", id);
1777 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1778 s->self, id, rtype, reply);
1781 * a session is in LARVAL state until a shell, a command
1782 * or a subsystem is executed
1784 if (c->type == SSH_CHANNEL_LARVAL) {
1785 if (strcmp(rtype, "shell") == 0) {
1786 success = session_shell_req(s);
1787 } else if (strcmp(rtype, "exec") == 0) {
1788 success = session_exec_req(s);
1789 } else if (strcmp(rtype, "pty-req") == 0) {
1790 success = session_pty_req(s);
1791 } else if (strcmp(rtype, "x11-req") == 0) {
1792 success = session_x11_req(s);
1793 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1794 success = session_auth_agent_req(s);
1795 } else if (strcmp(rtype, "subsystem") == 0) {
1796 success = session_subsystem_req(s);
1799 if (strcmp(rtype, "window-change") == 0) {
1800 success = session_window_change_req(s);
1804 packet_start(success ?
1805 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1806 packet_put_int(c->remote_id);
1813 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1816 fatal("session_set_fds: called for proto != 2.0");
1818 * now that have a child and a pipe to the child,
1819 * we can activate our channel and register the fd's
1821 if (s->chanid == -1)
1822 fatal("no channel for session %d", s->self);
1823 channel_set_fds(s->chanid,
1825 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1830 * Function to perform pty cleanup. Also called if we get aborted abnormally
1831 * (e.g., due to a dropped connection).
1834 session_pty_cleanup(void *session)
1836 Session *s = session;
1839 error("session_pty_cleanup: no session");
1845 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1847 /* Record that the user has logged out. */
1849 record_logout(s->pid, s->tty);
1851 /* Release the pseudo-tty. */
1852 pty_release(s->tty);
1855 * Close the server side of the socket pairs. We must do this after
1856 * the pty cleanup, so that another process doesn't get this pty
1857 * while we're still cleaning up.
1859 if (close(s->ptymaster) < 0)
1860 error("close(s->ptymaster): %s", strerror(errno));
1864 session_exit_message(Session *s, int status)
1868 fatal("session_close: no session");
1869 c = channel_lookup(s->chanid);
1871 fatal("session_exit_message: session %d: no channel %d",
1872 s->self, s->chanid);
1873 debug("session_exit_message: session %d channel %d pid %d",
1874 s->self, s->chanid, s->pid);
1876 if (WIFEXITED(status)) {
1877 channel_request_start(s->chanid,
1879 packet_put_int(WEXITSTATUS(status));
1881 } else if (WIFSIGNALED(status)) {
1882 channel_request_start(s->chanid,
1884 packet_put_int(WTERMSIG(status));
1886 packet_put_char(WCOREDUMP(status));
1887 #else /* WCOREDUMP */
1889 #endif /* WCOREDUMP */
1890 packet_put_cstring("");
1891 packet_put_cstring("");
1894 /* Some weird exit cause. Just exit. */
1895 packet_disconnect("wait returned status %04x.", status);
1898 /* disconnect channel */
1899 debug("session_exit_message: release channel %d", s->chanid);
1900 channel_cancel_cleanup(s->chanid);
1902 * emulate a write failure with 'chan_write_failed', nobody will be
1903 * interested in data we write.
1904 * Note that we must not call 'chan_read_failed', since there could
1905 * be some more data waiting in the pipe.
1907 if (c->ostate != CHAN_OUTPUT_CLOSED)
1908 chan_write_failed(c);
1913 session_close(Session *s)
1915 debug("session_close: session %d pid %d", s->self, s->pid);
1916 if (s->ttyfd != -1) {
1917 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1918 session_pty_cleanup(s);
1925 xfree(s->auth_data);
1927 xfree(s->auth_proto);
1929 session_proctitle(s);
1933 session_close_by_pid(pid_t pid, int status)
1935 Session *s = session_by_pid(pid);
1937 debug("session_close_by_pid: no session for pid %d", pid);
1940 if (s->chanid != -1)
1941 session_exit_message(s, status);
1946 session_have_children(void)
1950 for(i = 0; i < MAX_SESSIONS; i++) {
1951 Session *s = &sessions[i];
1952 if (s->used && s->pid != -1) {
1953 debug("session_have_children: id %d pid %d", i, s->pid);
1957 debug("session_have_children: no more children");
1962 * this is called when a channel dies before
1963 * the session 'child' itself dies
1966 session_close_by_channel(int id, void *arg)
1968 Session *s = session_by_channel(id);
1970 debug("session_close_by_channel: no session for channel %d", id);
1973 /* disconnect channel */
1974 channel_cancel_cleanup(s->chanid);
1977 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1979 /* close session immediately */
1982 /* notify child, delay session cleanup */
1983 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1984 error("session_close_by_channel: kill %d: %s",
1985 s->pid, strerror(errno));
1990 session_tty_list(void)
1992 static char buf[1024];
1995 for(i = 0; i < MAX_SESSIONS; i++) {
1996 Session *s = &sessions[i];
1997 if (s->used && s->ttyfd != -1) {
1999 strlcat(buf, ",", sizeof buf);
2000 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2004 strlcpy(buf, "notty", sizeof buf);
2009 session_proctitle(Session *s)
2012 error("no user for session %d", s->self);
2014 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2018 session_setup_x11fwd(Session *s)
2022 if (no_x11_forwarding_flag) {
2023 packet_send_debug("X11 forwarding disabled in user configuration file.");
2026 if (!options.x11_forwarding) {
2027 debug("X11 forwarding disabled in server configuration file.");
2030 if (!options.xauth_location ||
2031 (stat(options.xauth_location, &st) == -1)) {
2032 packet_send_debug("No xauth program; cannot forward with spoofing.");
2035 if (options.use_login) {
2036 packet_send_debug("X11 forwarding disabled; "
2037 "not compatible with UseLogin=yes.");
2040 if (s->display != NULL) {
2041 debug("X11 display already set.");
2044 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
2045 if (s->display == NULL) {
2046 debug("x11_create_display_inet failed.");
2053 do_authenticated2(Authctxt *authctxt)
2055 server_loop2(authctxt);