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.108 2001/10/11 13:45:21 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);
435 if (is_pam_password_change_required())
436 packet_disconnect("Password change required but no "
440 /* Fork the child. */
441 if ((pid = fork()) == 0) {
442 /* Child. Reinitialize the log since the pid has changed. */
443 log_init(__progname, options.log_level, options.log_facility, log_stderr);
446 * Create a new session and process group since the 4.4BSD
447 * setlogin() affects the entire process group.
450 error("setsid failed: %.100s", strerror(errno));
454 * Redirect stdin. We close the parent side of the socket
455 * pair, and make the child side the standard input.
458 if (dup2(pin[0], 0) < 0)
459 perror("dup2 stdin");
462 /* Redirect stdout. */
464 if (dup2(pout[1], 1) < 0)
465 perror("dup2 stdout");
468 /* Redirect stderr. */
470 if (dup2(perr[1], 2) < 0)
471 perror("dup2 stderr");
473 #else /* USE_PIPES */
475 * Redirect stdin, stdout, and stderr. Stdin and stdout will
476 * use the same socket, as some programs (particularly rdist)
477 * seem to depend on it.
481 if (dup2(inout[0], 0) < 0) /* stdin */
482 perror("dup2 stdin");
483 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
484 perror("dup2 stdout");
485 if (dup2(err[0], 2) < 0) /* stderr */
486 perror("dup2 stderr");
487 #endif /* USE_PIPES */
489 /* Do processing for the child (exec command etc). */
490 do_child(s, command);
495 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
498 packet_disconnect("fork failed: %.100s", strerror(errno));
500 /* Set interactive/non-interactive mode. */
501 packet_set_interactive(s->display != NULL);
503 /* We are the parent. Close the child sides of the pipes. */
509 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
511 /* Enter the interactive session. */
512 server_loop(pid, pin[1], pout[0], perr[0]);
513 /* server_loop has closed pin[1], pout[0], and perr[0]. */
515 #else /* USE_PIPES */
516 /* We are the parent. Close the child sides of the socket pairs. */
521 * Enter the interactive session. Note: server_loop must be able to
522 * handle the case that fdin and fdout are the same.
525 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
527 server_loop(pid, inout[1], inout[1], err[1]);
528 /* server_loop has closed inout[1] and err[1]. */
530 #endif /* USE_PIPES */
534 * This is called to fork and execute a command when we have a tty. This
535 * will call do_child from the child, and server_loop from the parent after
536 * setting up file descriptors, controlling tty, updating wtmp, utmp,
537 * lastlog, and other such operations.
540 do_exec_pty(Session *s, const char *command)
542 int fdout, ptyfd, ttyfd, ptymaster;
546 fatal("do_exec_pty: no session");
551 do_pam_session(s->pw->pw_name, s->tty);
555 /* Fork the child. */
556 if ((pid = fork()) == 0) {
558 /* Child. Reinitialize the log because the pid has changed. */
559 log_init(__progname, options.log_level, options.log_facility, log_stderr);
560 /* Close the master side of the pseudo tty. */
563 /* Make the pseudo tty our controlling tty. */
564 pty_make_controlling_tty(&ttyfd, s->tty);
566 /* Redirect stdin/stdout/stderr from the pseudo tty. */
567 if (dup2(ttyfd, 0) < 0)
568 error("dup2 stdin: %s", strerror(errno));
569 if (dup2(ttyfd, 1) < 0)
570 error("dup2 stdout: %s", strerror(errno));
571 if (dup2(ttyfd, 2) < 0)
572 error("dup2 stderr: %s", strerror(errno));
574 /* Close the extra descriptor for the pseudo tty. */
577 /* record login, etc. similar to login(1) */
579 if (!(options.use_login && command == NULL))
580 do_login(s, command);
581 # ifdef LOGIN_NEEDS_UTMPX
587 /* Do common processing for the child, such as execing the command. */
588 do_child(s, command);
593 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
596 packet_disconnect("fork failed: %.100s", strerror(errno));
599 /* Parent. Close the slave side of the pseudo tty. */
603 * Create another descriptor of the pty master side for use as the
604 * standard input. We could use the original descriptor, but this
605 * simplifies code in server_loop. The descriptor is bidirectional.
609 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
611 /* we keep a reference to the pty master */
612 ptymaster = dup(ptyfd);
614 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
615 s->ptymaster = ptymaster;
617 /* Enter interactive session. */
618 packet_set_interactive(1);
620 session_set_fds(s, ptyfd, fdout, -1);
622 server_loop(pid, ptyfd, fdout, -1);
623 /* server_loop _has_ closed ptyfd and fdout. */
627 #ifdef LOGIN_NEEDS_UTMPX
629 do_pre_login(Session *s)
632 struct sockaddr_storage from;
633 pid_t pid = getpid();
636 * Get IP address of client. If the connection is not a socket, let
637 * the address be 0.0.0.0.
639 memset(&from, 0, sizeof(from));
640 if (packet_connection_is_on_socket()) {
641 fromlen = sizeof(from);
642 if (getpeername(packet_get_connection_in(),
643 (struct sockaddr *) & from, &fromlen) < 0) {
644 debug("getpeername: %.100s", strerror(errno));
649 record_utmp_only(pid, s->tty, s->pw->pw_name,
650 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
651 (struct sockaddr *)&from);
656 * This is called to fork and execute a command. If another command is
657 * to be forced, execute that instead.
660 do_exec(Session *s, const char *command)
662 if (forced_command) {
663 original_command = command;
664 command = forced_command;
665 debug("Forced command '%.900s'", command);
669 do_exec_pty(s, command);
671 do_exec_no_pty(s, command);
673 original_command = NULL;
676 /* administrative, login(1)-like work */
678 do_login(Session *s, const char *command)
681 char hostname[MAXHOSTNAMELEN];
683 struct sockaddr_storage from;
684 time_t last_login_time;
685 struct passwd * pw = s->pw;
686 pid_t pid = getpid();
689 * Get IP address of client. If the connection is not a socket, let
690 * the address be 0.0.0.0.
692 memset(&from, 0, sizeof(from));
693 if (packet_connection_is_on_socket()) {
694 fromlen = sizeof(from);
695 if (getpeername(packet_get_connection_in(),
696 (struct sockaddr *) & from, &fromlen) < 0) {
697 debug("getpeername: %.100s", strerror(errno));
702 /* Get the time and hostname when the user last logged in. */
703 if (options.print_lastlog) {
705 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
706 hostname, sizeof(hostname));
709 /* Record that there was a login on that tty from the remote host. */
710 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
711 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
712 (struct sockaddr *)&from);
716 * If password change is needed, do it now.
717 * This needs to occur before the ~/.hushlogin check.
719 if (is_pam_password_change_required()) {
720 print_pam_messages();
725 if (check_quietlogin(s, command))
729 if (!is_pam_password_change_required())
730 print_pam_messages();
732 #ifdef WITH_AIXAUTHENTICATE
733 if (aixloginmsg && *aixloginmsg)
734 printf("%s\n", aixloginmsg);
735 #endif /* WITH_AIXAUTHENTICATE */
737 if (options.print_lastlog && last_login_time != 0) {
738 time_string = ctime(&last_login_time);
739 if (strchr(time_string, '\n'))
740 *strchr(time_string, '\n') = 0;
741 if (strcmp(hostname, "") == 0)
742 printf("Last login: %s\r\n", time_string);
744 printf("Last login: %s from %s\r\n", time_string, hostname);
751 * Display the message of the day.
759 if (options.print_motd) {
760 #ifdef HAVE_LOGIN_CAP
761 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
764 f = fopen("/etc/motd", "r");
767 while (fgets(buf, sizeof(buf), f))
776 * Check for quiet login, either .hushlogin or command given.
779 check_quietlogin(Session *s, const char *command)
782 struct passwd *pw = s->pw;
785 /* Return 1 if .hushlogin exists or a command given. */
788 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
789 #ifdef HAVE_LOGIN_CAP
790 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
793 if (stat(buf, &st) >= 0)
800 * Sets the value of the given variable in the environment. If the variable
801 * already exists, its value is overriden.
804 child_set_env(char ***envp, u_int *envsizep, const char *name,
811 * Find the slot where the value should be stored. If the variable
812 * already exists, we reuse the slot; otherwise we append a new slot
813 * at the end of the array, expanding if necessary.
816 namelen = strlen(name);
817 for (i = 0; env[i]; i++)
818 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
821 /* Reuse the slot. */
824 /* New variable. Expand if necessary. */
825 if (i >= (*envsizep) - 1) {
827 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
829 /* Need to set the NULL pointer at end of array beyond the new slot. */
833 /* Allocate space and format the variable in the appropriate slot. */
834 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
835 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
839 * Reads environment variables from the given file and adds/overrides them
840 * into the environment. If the file does not exist, this does nothing.
841 * Otherwise, it must consist of empty lines, comments (line starts with '#')
842 * and assignments of the form name=value. No other forms are allowed.
845 read_environment_file(char ***env, u_int *envsize,
846 const char *filename)
852 f = fopen(filename, "r");
856 while (fgets(buf, sizeof(buf), f)) {
857 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
859 if (!*cp || *cp == '#' || *cp == '\n')
861 if (strchr(cp, '\n'))
862 *strchr(cp, '\n') = '\0';
863 value = strchr(cp, '=');
865 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
869 * Replace the equals sign by nul, and advance value to
874 child_set_env(env, envsize, cp, value);
881 * Sets any environment variables which have been specified by PAM
883 void do_pam_environment(char ***env, u_int *envsize)
885 char *equals, var_name[512], var_val[512];
889 if ((pam_env = fetch_pam_environment()) == NULL)
892 for(i = 0; pam_env[i] != NULL; i++) {
893 if ((equals = strstr(pam_env[i], "=")) == NULL)
896 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
897 memset(var_name, '\0', sizeof(var_name));
898 memset(var_val, '\0', sizeof(var_val));
900 strncpy(var_name, pam_env[i], equals - pam_env[i]);
901 strcpy(var_val, equals + 1);
903 debug3("PAM environment: %s=%s", var_name, var_val);
905 child_set_env(env, envsize, var_name, var_val);
912 void copy_environment(char ***env, u_int *envsize)
914 char *equals, var_name[512], var_val[512];
917 for(i = 0; environ[i] != NULL; i++) {
918 if ((equals = strstr(environ[i], "=")) == NULL)
921 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
922 memset(var_name, '\0', sizeof(var_name));
923 memset(var_val, '\0', sizeof(var_val));
925 strncpy(var_name, environ[i], equals - environ[i]);
926 strcpy(var_val, equals + 1);
928 debug3("Copy environment: %s=%s", var_name, var_val);
930 child_set_env(env, envsize, var_name, var_val);
936 #if defined(HAVE_GETUSERATTR)
938 * AIX-specific login initialisation
940 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
945 getrlimit(resource, &rlim);
948 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
950 rlim.rlim_cur = RLIM_INFINITY;
951 } else if (slim != 0) {
952 /* See the wackiness below */
953 if (rlim.rlim_cur == slim * mult)
956 rlim.rlim_cur = slim * mult;
961 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
963 rlim.rlim_max = RLIM_INFINITY;
964 } else if (hlim != 0) {
965 rlim.rlim_max = hlim * mult;
970 * XXX For cpu and fsize the soft limit is set to the hard limit
971 * if the hard limit is left at its default value and the soft limit
972 * is changed from its default value, either by requesting it
973 * (slim == 0) or by setting it to the current default. At least
974 * that's how rlogind does it. If you're confused you're not alone.
975 * Bug or feature? AIX 4.3.1.2
977 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
978 && hlim == 0 && slim != 0)
979 rlim.rlim_max = rlim.rlim_cur;
980 /* A specified hard limit limits the soft limit */
981 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
982 rlim.rlim_cur = rlim.rlim_max;
983 /* A soft limit can increase a hard limit */
984 else if (rlim.rlim_cur > rlim.rlim_max)
985 rlim.rlim_max = rlim.rlim_cur;
987 if (setrlimit(resource, &rlim) != 0)
988 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
991 void set_limits_from_userattr(char *user)
996 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
997 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
998 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
999 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
1000 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
1001 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1002 #if defined(S_UNOFILE)
1003 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1006 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1007 /* Convert decimal to octal */
1008 (void) snprintf(buf, sizeof(buf), "%d", mask);
1009 if (sscanf(buf, "%o", &mask) == 1)
1013 #endif /* defined(HAVE_GETUSERATTR) */
1016 * Performs common processing for the child, such as setting up the
1017 * environment, closing extra file descriptors, setting the user and group
1018 * ids, and executing the command or shell.
1021 do_child(Session *s, const char *command)
1023 const char *shell, *hostname = NULL, *cp = NULL;
1024 struct passwd *pw = s->pw;
1030 extern char **environ;
1034 #ifdef WITH_IRIX_PROJECT
1036 #endif /* WITH_IRIX_PROJECT */
1037 #ifdef WITH_IRIX_JOBS
1040 #ifdef WITH_IRIX_ARRAY
1042 #endif /* WITH_IRIX_ARRAY */
1043 #endif /* WITH_IRIX_JOBS */
1046 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1048 /* remove hostkey from the child's memory */
1049 destroy_sensitive_data();
1051 /* login(1) is only called if we execute the login shell */
1052 if (options.use_login && command != NULL)
1053 options.use_login = 0;
1055 #if !defined(HAVE_OSF_SIA)
1056 if (!options.use_login) {
1057 # ifdef HAVE_LOGIN_CAP
1058 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1059 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1060 _PATH_NOLOGIN), "r");
1061 # else /* HAVE_LOGIN_CAP */
1063 f = fopen(_PATH_NOLOGIN, "r");
1064 # endif /* HAVE_LOGIN_CAP */
1066 /* /etc/nologin exists. Print its contents and exit. */
1067 while (fgets(buf, sizeof(buf), f))
1073 #endif /* HAVE_OSF_SIA */
1075 /* Set login name, uid, gid, and groups. */
1076 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1077 switch, so we let login(1) to this for us. */
1078 if (!options.use_login) {
1080 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1081 if (!check_quietlogin(s, command))
1083 #else /* HAVE_OSF_SIA */
1087 if (getuid() == 0 || geteuid() == 0) {
1089 # ifdef HAVE_GETUSERATTR
1090 set_limits_from_userattr(pw->pw_name);
1091 # endif /* HAVE_GETUSERATTR */
1092 # ifdef HAVE_LOGIN_CAP
1093 if (setusercontext(lc, pw, pw->pw_uid,
1094 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1095 perror("unable to set user context");
1098 # else /* HAVE_LOGIN_CAP */
1099 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1100 /* Sets login uid for accounting */
1101 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1102 error("setluid: %s", strerror(errno));
1103 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1105 if (setlogin(pw->pw_name) < 0)
1106 error("setlogin failed: %s", strerror(errno));
1107 if (setgid(pw->pw_gid) < 0) {
1111 /* Initialize the group list. */
1112 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1113 perror("initgroups");
1119 * PAM credentials may take the form of
1120 * supplementary groups. These will have been
1121 * wiped by the above initgroups() call.
1122 * Reestablish them here.
1125 # endif /* USE_PAM */
1126 # ifdef WITH_IRIX_JOBS
1127 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1129 fatal("Failed to create job container: %.100s",
1132 # endif /* WITH_IRIX_JOBS */
1133 # ifdef WITH_IRIX_ARRAY
1134 /* initialize array session */
1136 if (newarraysess() != 0)
1137 fatal("Failed to set up new array session: %.100s",
1140 # endif /* WITH_IRIX_ARRAY */
1141 # ifdef WITH_IRIX_PROJECT
1142 /* initialize irix project info */
1143 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1144 debug("Failed to get project id, using projid 0");
1147 if (setprid(projid))
1148 fatal("Failed to initialize project %d for %s: %.100s",
1149 (int)projid, pw->pw_name, strerror(errno));
1150 # endif /* WITH_IRIX_PROJECT */
1151 #ifdef WITH_IRIX_AUDIT
1152 if (sysconf(_SC_AUDIT)) {
1153 debug("Setting sat id to %d", (int) pw->pw_uid);
1154 if (satsetid(pw->pw_uid))
1155 debug("error setting satid: %.100s", strerror(errno));
1157 #endif /* WITH_IRIX_AUDIT */
1161 * AIX has a "usrinfo" area where logname and
1162 * other stuff is stored - a few applications
1163 * actually use this and die if it's not set
1167 cp = xmalloc(22 + strlen(s->tty) +
1168 2 * strlen(pw->pw_name));
1169 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1170 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1171 if (usrinfo(SETUINFO, cp, i) == -1)
1172 fatal("Couldn't set usrinfo: %s",
1174 debug3("AIX/UsrInfo: set len %d", i);
1178 /* Permanently switch to the desired uid. */
1179 permanently_set_uid(pw);
1180 # endif /* HAVE_LOGIN_CAP */
1182 #endif /* HAVE_OSF_SIA */
1187 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1188 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1191 * Get the shell from the password data. An empty shell field is
1192 * legal, and means /bin/sh.
1194 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1195 #ifdef HAVE_LOGIN_CAP
1196 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1199 /* Initialize the environment. */
1201 env = xmalloc(envsize * sizeof(char *));
1206 * The Windows environment contains some setting which are
1207 * important for a running system. They must not be dropped.
1209 copy_environment(&env, &envsize);
1212 if (!options.use_login) {
1213 /* Set basic environment. */
1214 child_set_env(&env, &envsize, "USER", pw->pw_name);
1215 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1216 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1217 #ifdef HAVE_LOGIN_CAP
1218 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1219 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1220 #else /* HAVE_LOGIN_CAP */
1221 # ifndef HAVE_CYGWIN
1223 * There's no standard path on Windows. The path contains
1224 * important components pointing to the system directories,
1225 * needed for loading shared libraries. So the path better
1226 * remains intact here.
1228 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1229 # endif /* HAVE_CYGWIN */
1230 #endif /* HAVE_LOGIN_CAP */
1232 snprintf(buf, sizeof buf, "%.200s/%.50s",
1233 _PATH_MAILDIR, pw->pw_name);
1234 child_set_env(&env, &envsize, "MAIL", buf);
1236 /* Normal systems set SHELL by default. */
1237 child_set_env(&env, &envsize, "SHELL", shell);
1240 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1242 /* Set custom environment options from RSA authentication. */
1243 while (custom_environment) {
1244 struct envstring *ce = custom_environment;
1247 for (i = 0; s[i] != '=' && s[i]; i++);
1250 child_set_env(&env, &envsize, s, s + i + 1);
1252 custom_environment = ce->next;
1257 snprintf(buf, sizeof buf, "%.50s %d %d",
1258 get_remote_ipaddr(), get_remote_port(), get_local_port());
1259 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1262 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1264 child_set_env(&env, &envsize, "TERM", s->term);
1266 child_set_env(&env, &envsize, "DISPLAY", s->display);
1267 if (original_command)
1268 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1272 if ((cp = getenv("AUTHSTATE")) != NULL)
1273 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1274 if ((cp = getenv("KRB5CCNAME")) != NULL)
1275 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1276 read_environment_file(&env, &envsize, "/etc/environment");
1279 if (s->authctxt->krb4_ticket_file)
1280 child_set_env(&env, &envsize, "KRBTKFILE",
1281 s->authctxt->krb4_ticket_file);
1284 if (s->authctxt->krb5_ticket_file)
1285 child_set_env(&env, &envsize, "KRB5CCNAME",
1286 s->authctxt->krb5_ticket_file);
1289 /* Pull in any environment variables that may have been set by PAM. */
1290 do_pam_environment(&env, &envsize);
1291 #endif /* USE_PAM */
1293 if (auth_get_socket_name() != NULL)
1294 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1295 auth_get_socket_name());
1297 /* read $HOME/.ssh/environment. */
1298 if (!options.use_login) {
1299 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1301 read_environment_file(&env, &envsize, buf);
1304 /* dump the environment */
1305 fprintf(stderr, "Environment:\n");
1306 for (i = 0; env[i]; i++)
1307 fprintf(stderr, " %.200s\n", env[i]);
1309 /* we have to stash the hostname before we close our socket. */
1310 if (options.use_login)
1311 hostname = get_remote_name_or_ip(utmp_len,
1312 options.reverse_mapping_check);
1314 * Close the connection descriptors; note that this is the child, and
1315 * the server will still have the socket open, and it is important
1316 * that we do not shutdown it. Note that the descriptors cannot be
1317 * closed before building the environment, as we call
1318 * get_remote_ipaddr there.
1320 if (packet_get_connection_in() == packet_get_connection_out())
1321 close(packet_get_connection_in());
1323 close(packet_get_connection_in());
1324 close(packet_get_connection_out());
1327 * Close all descriptors related to channels. They will still remain
1328 * open in the parent.
1330 /* XXX better use close-on-exec? -markus */
1331 channel_close_all();
1334 * Close any extra file descriptors. Note that there may still be
1335 * descriptors left by system functions. They will be closed later.
1340 * Close any extra open file descriptors so that we don\'t have them
1341 * hanging around in clients. Note that we want to do this after
1342 * initgroups, because at least on Solaris 2.3 it leaves file
1345 for (i = 3; i < 64; i++)
1349 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1350 * xauth are run in the proper environment.
1355 /* Try to get AFS tokens for the local cell. */
1359 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1360 krb_afslog(cell, 0);
1366 /* Change current directory to the user\'s home directory. */
1367 if (chdir(pw->pw_dir) < 0) {
1368 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1369 pw->pw_dir, strerror(errno));
1370 #ifdef HAVE_LOGIN_CAP
1371 if (login_getcapbool(lc, "requirehome", 0))
1377 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1380 if (!options.use_login) {
1381 /* ignore _PATH_SSH_USER_RC for subsystems */
1382 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1383 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1384 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1386 fprintf(stderr, "Running %s\n", cmd);
1387 f = popen(cmd, "w");
1390 fprintf(f, "%s %s\n", s->auth_proto,
1394 fprintf(stderr, "Could not run %s\n",
1396 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1398 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1399 _PATH_SSH_SYSTEM_RC);
1400 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1403 fprintf(f, "%s %s\n", s->auth_proto,
1407 fprintf(stderr, "Could not run %s\n",
1408 _PATH_SSH_SYSTEM_RC);
1409 } else if (do_xauth && options.xauth_location != NULL) {
1410 /* Add authority data to .Xauthority if appropriate. */
1411 char *screen = strchr(s->display, ':');
1415 "Running %.100s add "
1416 "%.100s %.100s %.100s\n",
1417 options.xauth_location, s->display,
1418 s->auth_proto, s->auth_data);
1421 "Adding %.*s/unix%s %s %s\n",
1422 (int)(screen - s->display),
1424 s->auth_proto, s->auth_data);
1426 snprintf(cmd, sizeof cmd, "%s -q -",
1427 options.xauth_location);
1428 f = popen(cmd, "w");
1430 fprintf(f, "add %s %s %s\n", s->display,
1431 s->auth_proto, s->auth_data);
1433 fprintf(f, "add %.*s/unix%s %s %s\n",
1434 (int)(screen - s->display),
1440 fprintf(stderr, "Could not run %s\n",
1444 /* Get the last component of the shell name. */
1445 cp = strrchr(shell, '/');
1452 /* restore SIGPIPE for child */
1453 signal(SIGPIPE, SIG_DFL);
1456 * If we have no command, execute the shell. In this case, the shell
1457 * name to be passed in argv[0] is preceded by '-' to indicate that
1458 * this is a login shell.
1461 if (!options.use_login) {
1464 /* Start the shell. Set initial character to '-'. */
1466 strncpy(buf + 1, cp, sizeof(buf) - 1);
1467 buf[sizeof(buf) - 1] = 0;
1469 /* Execute the shell. */
1472 execve(shell, argv, env);
1474 /* Executing the shell failed. */
1479 /* Launch login(1). */
1481 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1482 #ifdef LOGIN_NEEDS_TERM
1483 s->term? s->term : "unknown",
1485 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1487 /* Login couldn't be executed, die. */
1494 * Execute the command using the user's shell. This uses the -c
1495 * option to execute the command.
1497 argv[0] = (char *) cp;
1499 argv[2] = (char *) command;
1501 execve(shell, argv, env);
1510 static int did_init = 0;
1512 debug("session_new: init");
1513 for(i = 0; i < MAX_SESSIONS; i++) {
1514 sessions[i].used = 0;
1518 for(i = 0; i < MAX_SESSIONS; i++) {
1519 Session *s = &sessions[i];
1521 memset(s, 0, sizeof(*s));
1527 debug("session_new: session %d", i);
1538 for(i = 0; i < MAX_SESSIONS; i++) {
1539 Session *s = &sessions[i];
1540 debug("dump: used %d session %d %p channel %d pid %d",
1550 session_open(Authctxt *authctxt, int chanid)
1552 Session *s = session_new();
1553 debug("session_open: channel %d", chanid);
1555 error("no more sessions");
1558 s->authctxt = authctxt;
1559 s->pw = authctxt->pw;
1561 fatal("no user for session %d", s->self);
1562 debug("session_open: session %d: link with channel %d", s->self, chanid);
1568 session_by_channel(int id)
1571 for(i = 0; i < MAX_SESSIONS; i++) {
1572 Session *s = &sessions[i];
1573 if (s->used && s->chanid == id) {
1574 debug("session_by_channel: session %d channel %d", i, id);
1578 debug("session_by_channel: unknown channel %d", id);
1584 session_by_pid(pid_t pid)
1587 debug("session_by_pid: pid %d", pid);
1588 for(i = 0; i < MAX_SESSIONS; i++) {
1589 Session *s = &sessions[i];
1590 if (s->used && s->pid == pid)
1593 error("session_by_pid: unknown pid %d", pid);
1599 session_window_change_req(Session *s)
1601 s->col = packet_get_int();
1602 s->row = packet_get_int();
1603 s->xpixel = packet_get_int();
1604 s->ypixel = packet_get_int();
1606 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1611 session_pty_req(Session *s)
1617 debug("Allocating a pty not permitted for this authentication.");
1620 if (s->ttyfd != -1) {
1621 packet_disconnect("Protocol error: you already have a pty.");
1625 s->term = packet_get_string(&len);
1628 s->col = packet_get_int();
1629 s->row = packet_get_int();
1631 s->row = packet_get_int();
1632 s->col = packet_get_int();
1634 s->xpixel = packet_get_int();
1635 s->ypixel = packet_get_int();
1637 if (strcmp(s->term, "") == 0) {
1642 /* Allocate a pty and open it. */
1643 debug("Allocating pty.");
1644 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1650 error("session_pty_req: session %d alloc failed", s->self);
1653 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1655 /* for SSH1 the tty modes length is not given */
1657 n_bytes = packet_remaining();
1658 tty_parse_modes(s->ttyfd, &n_bytes);
1661 * Add a cleanup function to clear the utmp entry and record logout
1662 * time in case we call fatal() (e.g., the connection gets closed).
1664 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1665 pty_setowner(s->pw, s->tty);
1667 /* Set window size from the packet. */
1668 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1671 session_proctitle(s);
1676 session_subsystem_req(Session *s)
1681 char *cmd, *subsys = packet_get_string(&len);
1685 log("subsystem request for %s", subsys);
1687 for (i = 0; i < options.num_subsystems; i++) {
1688 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1689 cmd = options.subsystem_command[i];
1690 if (stat(cmd, &st) < 0) {
1691 error("subsystem: cannot stat %s: %s", cmd,
1695 debug("subsystem: exec() %s", cmd);
1696 s->is_subsystem = 1;
1703 log("subsystem request for %s failed, subsystem not found",
1711 session_x11_req(Session *s)
1715 s->single_connection = packet_get_char();
1716 s->auth_proto = packet_get_string(NULL);
1717 s->auth_data = packet_get_string(NULL);
1718 s->screen = packet_get_int();
1721 success = session_setup_x11fwd(s);
1723 xfree(s->auth_proto);
1724 xfree(s->auth_data);
1725 s->auth_proto = NULL;
1726 s->auth_data = NULL;
1732 session_shell_req(Session *s)
1740 session_exec_req(Session *s)
1743 char *command = packet_get_string(&len);
1745 do_exec(s, command);
1751 session_auth_agent_req(Session *s)
1753 static int called = 0;
1755 if (no_agent_forwarding_flag) {
1756 debug("session_auth_agent_req: no_agent_forwarding_flag");
1763 return auth_input_request_forwarding(s->pw);
1768 session_input_channel_req(int id, void *arg)
1777 rtype = packet_get_string(&len);
1778 reply = packet_get_char();
1780 s = session_by_channel(id);
1782 fatal("session_input_channel_req: channel %d: no session", id);
1783 c = channel_lookup(id);
1785 fatal("session_input_channel_req: channel %d: bad channel", id);
1787 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1788 s->self, id, rtype, reply);
1791 * a session is in LARVAL state until a shell, a command
1792 * or a subsystem is executed
1794 if (c->type == SSH_CHANNEL_LARVAL) {
1795 if (strcmp(rtype, "shell") == 0) {
1796 success = session_shell_req(s);
1797 } else if (strcmp(rtype, "exec") == 0) {
1798 success = session_exec_req(s);
1799 } else if (strcmp(rtype, "pty-req") == 0) {
1800 success = session_pty_req(s);
1801 } else if (strcmp(rtype, "x11-req") == 0) {
1802 success = session_x11_req(s);
1803 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1804 success = session_auth_agent_req(s);
1805 } else if (strcmp(rtype, "subsystem") == 0) {
1806 success = session_subsystem_req(s);
1809 if (strcmp(rtype, "window-change") == 0) {
1810 success = session_window_change_req(s);
1814 packet_start(success ?
1815 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1816 packet_put_int(c->remote_id);
1823 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1826 fatal("session_set_fds: called for proto != 2.0");
1828 * now that have a child and a pipe to the child,
1829 * we can activate our channel and register the fd's
1831 if (s->chanid == -1)
1832 fatal("no channel for session %d", s->self);
1833 channel_set_fds(s->chanid,
1835 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1840 * Function to perform pty cleanup. Also called if we get aborted abnormally
1841 * (e.g., due to a dropped connection).
1844 session_pty_cleanup(void *session)
1846 Session *s = session;
1849 error("session_pty_cleanup: no session");
1855 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1857 /* Record that the user has logged out. */
1859 record_logout(s->pid, s->tty);
1861 /* Release the pseudo-tty. */
1862 pty_release(s->tty);
1865 * Close the server side of the socket pairs. We must do this after
1866 * the pty cleanup, so that another process doesn't get this pty
1867 * while we're still cleaning up.
1869 if (close(s->ptymaster) < 0)
1870 error("close(s->ptymaster): %s", strerror(errno));
1872 /* unlink pty from session */
1877 session_exit_message(Session *s, int status)
1881 fatal("session_close: no session");
1882 c = channel_lookup(s->chanid);
1884 fatal("session_exit_message: session %d: no channel %d",
1885 s->self, s->chanid);
1886 debug("session_exit_message: session %d channel %d pid %d",
1887 s->self, s->chanid, s->pid);
1889 if (WIFEXITED(status)) {
1890 channel_request_start(s->chanid,
1892 packet_put_int(WEXITSTATUS(status));
1894 } else if (WIFSIGNALED(status)) {
1895 channel_request_start(s->chanid,
1897 packet_put_int(WTERMSIG(status));
1899 packet_put_char(WCOREDUMP(status));
1900 #else /* WCOREDUMP */
1902 #endif /* WCOREDUMP */
1903 packet_put_cstring("");
1904 packet_put_cstring("");
1907 /* Some weird exit cause. Just exit. */
1908 packet_disconnect("wait returned status %04x.", status);
1911 /* disconnect channel */
1912 debug("session_exit_message: release channel %d", s->chanid);
1913 channel_cancel_cleanup(s->chanid);
1915 * emulate a write failure with 'chan_write_failed', nobody will be
1916 * interested in data we write.
1917 * Note that we must not call 'chan_read_failed', since there could
1918 * be some more data waiting in the pipe.
1920 if (c->ostate != CHAN_OUTPUT_CLOSED)
1921 chan_write_failed(c);
1926 session_close(Session *s)
1928 debug("session_close: session %d pid %d", s->self, s->pid);
1929 if (s->ttyfd != -1) {
1930 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1931 session_pty_cleanup(s);
1938 xfree(s->auth_data);
1940 xfree(s->auth_proto);
1942 session_proctitle(s);
1946 session_close_by_pid(pid_t pid, int status)
1948 Session *s = session_by_pid(pid);
1950 debug("session_close_by_pid: no session for pid %d", pid);
1953 if (s->chanid != -1)
1954 session_exit_message(s, status);
1959 * this is called when a channel dies before
1960 * the session 'child' itself dies
1963 session_close_by_channel(int id, void *arg)
1965 Session *s = session_by_channel(id);
1967 debug("session_close_by_channel: no session for id %d", id);
1970 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1972 debug("session_close_by_channel: channel %d: has child", id);
1974 * delay detach of session, but release pty, since
1975 * the fd's to the child are already closed
1977 if (s->ttyfd != -1) {
1978 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1979 session_pty_cleanup(s);
1983 /* detach by removing callback */
1984 channel_cancel_cleanup(s->chanid);
1990 session_destroy_all(void)
1993 for(i = 0; i < MAX_SESSIONS; i++) {
1994 Session *s = &sessions[i];
2001 session_tty_list(void)
2003 static char buf[1024];
2006 for(i = 0; i < MAX_SESSIONS; i++) {
2007 Session *s = &sessions[i];
2008 if (s->used && s->ttyfd != -1) {
2010 strlcat(buf, ",", sizeof buf);
2011 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2015 strlcpy(buf, "notty", sizeof buf);
2020 session_proctitle(Session *s)
2023 error("no user for session %d", s->self);
2025 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2029 session_setup_x11fwd(Session *s)
2033 if (no_x11_forwarding_flag) {
2034 packet_send_debug("X11 forwarding disabled in user configuration file.");
2037 if (!options.x11_forwarding) {
2038 debug("X11 forwarding disabled in server configuration file.");
2041 if (!options.xauth_location ||
2042 (stat(options.xauth_location, &st) == -1)) {
2043 packet_send_debug("No xauth program; cannot forward with spoofing.");
2046 if (options.use_login) {
2047 packet_send_debug("X11 forwarding disabled; "
2048 "not compatible with UseLogin=yes.");
2051 if (s->display != NULL) {
2052 debug("X11 display already set.");
2055 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
2056 if (s->display == NULL) {
2057 debug("x11_create_display_inet failed.");
2064 do_authenticated2(Authctxt *authctxt)
2066 server_loop2(authctxt);