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
163 #endif /* WITH_AIXAUTHENTICATE */
165 #ifdef HAVE_LOGIN_CAP
166 static login_cap_t *lc;
170 do_authenticated(Authctxt *authctxt)
173 * Cancel the alarm we set to limit the time taken for
177 if (startup_pipe != -1) {
181 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
182 if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
183 error("unable to get login class");
187 if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
188 packet_disconnect("Approval failure for %s",
189 authctxt->pw->pw_name);
193 #ifdef WITH_AIXAUTHENTICATE
194 /* We don't have a pty yet, so just label the line as "ssh" */
195 if (loginsuccess(authctxt->user,
196 get_canonical_hostname(options.reverse_mapping_check),
197 "ssh", &aixloginmsg) < 0)
199 #endif /* WITH_AIXAUTHENTICATE */
201 /* setup the channel layer */
202 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
203 channel_permit_all_opens();
206 do_authenticated2(authctxt);
208 do_authenticated1(authctxt);
210 /* remove agent socket */
211 if (auth_get_socket_name())
212 auth_sock_cleanup_proc(authctxt->pw);
214 if (options.kerberos_ticket_cleanup)
215 krb4_cleanup_proc(authctxt);
218 if (options.kerberos_ticket_cleanup)
219 krb5_cleanup_proc(authctxt);
224 * Prepares for an interactive session. This is called after the user has
225 * been successfully authenticated. During this message exchange, pseudo
226 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
227 * are requested, etc.
230 do_authenticated1(Authctxt *authctxt)
234 int success, type, plen, screen_flag;
235 int compression_level = 0, enable_compression_after_reply = 0;
236 u_int proto_len, data_len, dlen;
239 s->authctxt = authctxt;
240 s->pw = authctxt->pw;
243 * We stay in this loop until the client requests to execute a shell
249 /* Get a packet from the client. */
250 type = packet_read(&plen);
252 /* Process the packet. */
254 case SSH_CMSG_REQUEST_COMPRESSION:
255 packet_integrity_check(plen, 4, type);
256 compression_level = packet_get_int();
257 if (compression_level < 1 || compression_level > 9) {
258 packet_send_debug("Received illegal compression level %d.",
262 /* Enable compression after we have responded with SUCCESS. */
263 enable_compression_after_reply = 1;
267 case SSH_CMSG_REQUEST_PTY:
268 success = session_pty_req(s);
271 case SSH_CMSG_X11_REQUEST_FORWARDING:
272 s->auth_proto = packet_get_string(&proto_len);
273 s->auth_data = packet_get_string(&data_len);
275 screen_flag = packet_get_protocol_flags() &
276 SSH_PROTOFLAG_SCREEN_NUMBER;
277 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
279 if (packet_remaining() == 4) {
281 debug2("Buggy client: "
282 "X11 screen flag missing");
283 s->screen = packet_get_int();
288 success = session_setup_x11fwd(s);
290 xfree(s->auth_proto);
292 s->auth_proto = NULL;
297 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
298 if (no_agent_forwarding_flag || compat13) {
299 debug("Authentication agent forwarding not permitted for this authentication.");
302 debug("Received authentication agent forwarding request.");
303 success = auth_input_request_forwarding(s->pw);
306 case SSH_CMSG_PORT_FORWARD_REQUEST:
307 if (no_port_forwarding_flag) {
308 debug("Port forwarding not permitted for this authentication.");
311 if (!options.allow_tcp_forwarding) {
312 debug("Port forwarding not permitted.");
315 debug("Received TCP/IP port forwarding request.");
316 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
320 case SSH_CMSG_MAX_PACKET_SIZE:
321 if (packet_set_maxsize(packet_get_int()) > 0)
325 #if defined(AFS) || defined(KRB5)
326 case SSH_CMSG_HAVE_KERBEROS_TGT:
327 if (!options.kerberos_tgt_passing) {
328 verbose("Kerberos TGT passing disabled.");
330 char *kdata = packet_get_string(&dlen);
331 packet_integrity_check(plen, 4 + dlen, type);
333 /* XXX - 0x41, see creds_to_radix version */
334 if (kdata[0] != 0x41) {
340 if (auth_krb5_tgt(s->authctxt, &tgt))
343 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
347 if (auth_krb4_tgt(s->authctxt, kdata))
350 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
356 #endif /* AFS || KRB5 */
359 case SSH_CMSG_HAVE_AFS_TOKEN:
360 if (!options.afs_token_passing || !k_hasafs()) {
361 verbose("AFS token passing disabled.");
363 /* Accept AFS token. */
364 char *token = packet_get_string(&dlen);
365 packet_integrity_check(plen, 4 + dlen, type);
367 if (auth_afs_token(s->authctxt, token))
370 verbose("AFS token refused for %.100s",
377 case SSH_CMSG_EXEC_SHELL:
378 case SSH_CMSG_EXEC_CMD:
379 if (type == SSH_CMSG_EXEC_CMD) {
380 command = packet_get_string(&dlen);
381 debug("Exec command '%.500s'", command);
393 * Any unknown messages in this phase are ignored,
394 * and a failure message is returned.
396 log("Unknown packet type received after authentication: %d", type);
398 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
402 /* Enable compression now that we have replied if appropriate. */
403 if (enable_compression_after_reply) {
404 enable_compression_after_reply = 0;
405 packet_start_compression(compression_level);
411 * This is called to fork and execute a command when we have no tty. This
412 * will call do_child from the child, and server_loop from the parent after
413 * setting up file descriptors and such.
416 do_exec_no_pty(Session *s, const char *command)
421 int pin[2], pout[2], perr[2];
422 /* Allocate pipes for communicating with the program. */
423 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
424 packet_disconnect("Could not create pipes: %.100s",
426 #else /* USE_PIPES */
427 int inout[2], err[2];
428 /* Uses socket pairs to communicate with the program. */
429 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
430 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
431 packet_disconnect("Could not create socket pairs: %.100s",
433 #endif /* USE_PIPES */
435 fatal("do_exec_no_pty: no session");
437 session_proctitle(s);
440 do_pam_session(s->pw->pw_name, NULL);
442 if (is_pam_password_change_required())
443 packet_disconnect("Password change required but no "
447 /* Fork the child. */
448 if ((pid = fork()) == 0) {
449 /* Child. Reinitialize the log since the pid has changed. */
450 log_init(__progname, options.log_level, options.log_facility, log_stderr);
453 * Create a new session and process group since the 4.4BSD
454 * setlogin() affects the entire process group.
457 error("setsid failed: %.100s", strerror(errno));
461 * Redirect stdin. We close the parent side of the socket
462 * pair, and make the child side the standard input.
465 if (dup2(pin[0], 0) < 0)
466 perror("dup2 stdin");
469 /* Redirect stdout. */
471 if (dup2(pout[1], 1) < 0)
472 perror("dup2 stdout");
475 /* Redirect stderr. */
477 if (dup2(perr[1], 2) < 0)
478 perror("dup2 stderr");
480 #else /* USE_PIPES */
482 * Redirect stdin, stdout, and stderr. Stdin and stdout will
483 * use the same socket, as some programs (particularly rdist)
484 * seem to depend on it.
488 if (dup2(inout[0], 0) < 0) /* stdin */
489 perror("dup2 stdin");
490 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
491 perror("dup2 stdout");
492 if (dup2(err[0], 2) < 0) /* stderr */
493 perror("dup2 stderr");
494 #endif /* USE_PIPES */
496 /* Do processing for the child (exec command etc). */
497 do_child(s, command);
502 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
505 packet_disconnect("fork failed: %.100s", strerror(errno));
507 /* Set interactive/non-interactive mode. */
508 packet_set_interactive(s->display != NULL);
510 /* We are the parent. Close the child sides of the pipes. */
516 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
518 /* Enter the interactive session. */
519 server_loop(pid, pin[1], pout[0], perr[0]);
520 /* server_loop has closed pin[1], pout[0], and perr[0]. */
522 #else /* USE_PIPES */
523 /* We are the parent. Close the child sides of the socket pairs. */
528 * Enter the interactive session. Note: server_loop must be able to
529 * handle the case that fdin and fdout are the same.
532 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
534 server_loop(pid, inout[1], inout[1], err[1]);
535 /* server_loop has closed inout[1] and err[1]. */
537 #endif /* USE_PIPES */
541 * This is called to fork and execute a command when we have a tty. This
542 * will call do_child from the child, and server_loop from the parent after
543 * setting up file descriptors, controlling tty, updating wtmp, utmp,
544 * lastlog, and other such operations.
547 do_exec_pty(Session *s, const char *command)
549 int fdout, ptyfd, ttyfd, ptymaster;
553 fatal("do_exec_pty: no session");
558 do_pam_session(s->pw->pw_name, s->tty);
562 /* Fork the child. */
563 if ((pid = fork()) == 0) {
565 /* Child. Reinitialize the log because the pid has changed. */
566 log_init(__progname, options.log_level, options.log_facility, log_stderr);
567 /* Close the master side of the pseudo tty. */
570 /* Make the pseudo tty our controlling tty. */
571 pty_make_controlling_tty(&ttyfd, s->tty);
573 /* Redirect stdin/stdout/stderr from the pseudo tty. */
574 if (dup2(ttyfd, 0) < 0)
575 error("dup2 stdin: %s", strerror(errno));
576 if (dup2(ttyfd, 1) < 0)
577 error("dup2 stdout: %s", strerror(errno));
578 if (dup2(ttyfd, 2) < 0)
579 error("dup2 stderr: %s", strerror(errno));
581 /* Close the extra descriptor for the pseudo tty. */
584 /* record login, etc. similar to login(1) */
586 if (!(options.use_login && command == NULL))
587 do_login(s, command);
588 # ifdef LOGIN_NEEDS_UTMPX
594 /* Do common processing for the child, such as execing the command. */
595 do_child(s, command);
600 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
603 packet_disconnect("fork failed: %.100s", strerror(errno));
606 /* Parent. Close the slave side of the pseudo tty. */
610 * Create another descriptor of the pty master side for use as the
611 * standard input. We could use the original descriptor, but this
612 * simplifies code in server_loop. The descriptor is bidirectional.
616 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
618 /* we keep a reference to the pty master */
619 ptymaster = dup(ptyfd);
621 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
622 s->ptymaster = ptymaster;
624 /* Enter interactive session. */
625 packet_set_interactive(1);
627 session_set_fds(s, ptyfd, fdout, -1);
629 server_loop(pid, ptyfd, fdout, -1);
630 /* server_loop _has_ closed ptyfd and fdout. */
634 #ifdef LOGIN_NEEDS_UTMPX
636 do_pre_login(Session *s)
639 struct sockaddr_storage from;
640 pid_t pid = getpid();
643 * Get IP address of client. If the connection is not a socket, let
644 * the address be 0.0.0.0.
646 memset(&from, 0, sizeof(from));
647 if (packet_connection_is_on_socket()) {
648 fromlen = sizeof(from);
649 if (getpeername(packet_get_connection_in(),
650 (struct sockaddr *) & from, &fromlen) < 0) {
651 debug("getpeername: %.100s", strerror(errno));
656 record_utmp_only(pid, s->tty, s->pw->pw_name,
657 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
658 (struct sockaddr *)&from);
663 * This is called to fork and execute a command. If another command is
664 * to be forced, execute that instead.
667 do_exec(Session *s, const char *command)
669 if (forced_command) {
670 original_command = command;
671 command = forced_command;
672 debug("Forced command '%.900s'", command);
676 do_exec_pty(s, command);
678 do_exec_no_pty(s, command);
680 original_command = NULL;
683 /* administrative, login(1)-like work */
685 do_login(Session *s, const char *command)
688 char hostname[MAXHOSTNAMELEN];
690 struct sockaddr_storage from;
691 time_t last_login_time;
692 struct passwd * pw = s->pw;
693 pid_t pid = getpid();
696 * Get IP address of client. If the connection is not a socket, let
697 * the address be 0.0.0.0.
699 memset(&from, 0, sizeof(from));
700 if (packet_connection_is_on_socket()) {
701 fromlen = sizeof(from);
702 if (getpeername(packet_get_connection_in(),
703 (struct sockaddr *) & from, &fromlen) < 0) {
704 debug("getpeername: %.100s", strerror(errno));
709 /* Get the time and hostname when the user last logged in. */
710 if (options.print_lastlog) {
712 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
713 hostname, sizeof(hostname));
716 /* Record that there was a login on that tty from the remote host. */
717 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
718 get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
719 (struct sockaddr *)&from);
723 * If password change is needed, do it now.
724 * This needs to occur before the ~/.hushlogin check.
726 if (is_pam_password_change_required()) {
727 print_pam_messages();
732 if (check_quietlogin(s, command))
736 if (!is_pam_password_change_required())
737 print_pam_messages();
739 #ifdef WITH_AIXAUTHENTICATE
740 if (aixloginmsg && *aixloginmsg)
741 printf("%s\n", aixloginmsg);
742 #endif /* WITH_AIXAUTHENTICATE */
744 if (options.print_lastlog && last_login_time != 0) {
745 time_string = ctime(&last_login_time);
746 if (strchr(time_string, '\n'))
747 *strchr(time_string, '\n') = 0;
748 if (strcmp(hostname, "") == 0)
749 printf("Last login: %s\r\n", time_string);
751 printf("Last login: %s from %s\r\n", time_string, hostname);
758 * Display the message of the day.
766 if (options.print_motd) {
767 #ifdef HAVE_LOGIN_CAP
768 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
771 f = fopen("/etc/motd", "r");
774 while (fgets(buf, sizeof(buf), f))
783 * Check for quiet login, either .hushlogin or command given.
786 check_quietlogin(Session *s, const char *command)
789 struct passwd *pw = s->pw;
792 /* Return 1 if .hushlogin exists or a command given. */
795 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
796 #ifdef HAVE_LOGIN_CAP
797 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
800 if (stat(buf, &st) >= 0)
807 * Sets the value of the given variable in the environment. If the variable
808 * already exists, its value is overriden.
811 child_set_env(char ***envp, u_int *envsizep, const char *name,
818 * Find the slot where the value should be stored. If the variable
819 * already exists, we reuse the slot; otherwise we append a new slot
820 * at the end of the array, expanding if necessary.
823 namelen = strlen(name);
824 for (i = 0; env[i]; i++)
825 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
828 /* Reuse the slot. */
831 /* New variable. Expand if necessary. */
832 if (i >= (*envsizep) - 1) {
834 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
836 /* Need to set the NULL pointer at end of array beyond the new slot. */
840 /* Allocate space and format the variable in the appropriate slot. */
841 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
842 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
846 * Reads environment variables from the given file and adds/overrides them
847 * into the environment. If the file does not exist, this does nothing.
848 * Otherwise, it must consist of empty lines, comments (line starts with '#')
849 * and assignments of the form name=value. No other forms are allowed.
852 read_environment_file(char ***env, u_int *envsize,
853 const char *filename)
859 f = fopen(filename, "r");
863 while (fgets(buf, sizeof(buf), f)) {
864 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
866 if (!*cp || *cp == '#' || *cp == '\n')
868 if (strchr(cp, '\n'))
869 *strchr(cp, '\n') = '\0';
870 value = strchr(cp, '=');
872 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
876 * Replace the equals sign by nul, and advance value to
881 child_set_env(env, envsize, cp, value);
888 * Sets any environment variables which have been specified by PAM
890 void do_pam_environment(char ***env, u_int *envsize)
892 char *equals, var_name[512], var_val[512];
896 if ((pam_env = fetch_pam_environment()) == NULL)
899 for(i = 0; pam_env[i] != NULL; i++) {
900 if ((equals = strstr(pam_env[i], "=")) == NULL)
903 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
904 memset(var_name, '\0', sizeof(var_name));
905 memset(var_val, '\0', sizeof(var_val));
907 strncpy(var_name, pam_env[i], equals - pam_env[i]);
908 strcpy(var_val, equals + 1);
910 debug3("PAM environment: %s=%s", var_name, var_val);
912 child_set_env(env, envsize, var_name, var_val);
919 void copy_environment(char ***env, u_int *envsize)
921 char *equals, var_name[512], var_val[512];
924 for(i = 0; environ[i] != NULL; i++) {
925 if ((equals = strstr(environ[i], "=")) == NULL)
928 if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
929 memset(var_name, '\0', sizeof(var_name));
930 memset(var_val, '\0', sizeof(var_val));
932 strncpy(var_name, environ[i], equals - environ[i]);
933 strcpy(var_val, equals + 1);
935 debug3("Copy environment: %s=%s", var_name, var_val);
937 child_set_env(env, envsize, var_name, var_val);
943 #if defined(HAVE_GETUSERATTR)
945 * AIX-specific login initialisation
947 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
952 getrlimit(resource, &rlim);
955 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
957 rlim.rlim_cur = RLIM_INFINITY;
958 } else if (slim != 0) {
959 /* See the wackiness below */
960 if (rlim.rlim_cur == slim * mult)
963 rlim.rlim_cur = slim * mult;
968 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
970 rlim.rlim_max = RLIM_INFINITY;
971 } else if (hlim != 0) {
972 rlim.rlim_max = hlim * mult;
977 * XXX For cpu and fsize the soft limit is set to the hard limit
978 * if the hard limit is left at its default value and the soft limit
979 * is changed from its default value, either by requesting it
980 * (slim == 0) or by setting it to the current default. At least
981 * that's how rlogind does it. If you're confused you're not alone.
982 * Bug or feature? AIX 4.3.1.2
984 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
985 && hlim == 0 && slim != 0)
986 rlim.rlim_max = rlim.rlim_cur;
987 /* A specified hard limit limits the soft limit */
988 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
989 rlim.rlim_cur = rlim.rlim_max;
990 /* A soft limit can increase a hard limit */
991 else if (rlim.rlim_cur > rlim.rlim_max)
992 rlim.rlim_max = rlim.rlim_cur;
994 if (setrlimit(resource, &rlim) != 0)
995 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
998 void set_limits_from_userattr(char *user)
1003 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
1004 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
1005 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
1006 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
1007 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
1008 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
1009 #if defined(S_UNOFILE)
1010 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
1013 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
1014 /* Convert decimal to octal */
1015 (void) snprintf(buf, sizeof(buf), "%d", mask);
1016 if (sscanf(buf, "%o", &mask) == 1)
1020 #endif /* defined(HAVE_GETUSERATTR) */
1023 * Performs common processing for the child, such as setting up the
1024 * environment, closing extra file descriptors, setting the user and group
1025 * ids, and executing the command or shell.
1028 do_child(Session *s, const char *command)
1030 const char *shell, *hostname = NULL, *cp = NULL;
1031 struct passwd *pw = s->pw;
1037 extern char **environ;
1041 #ifdef WITH_IRIX_PROJECT
1043 #endif /* WITH_IRIX_PROJECT */
1044 #ifdef WITH_IRIX_JOBS
1047 #ifdef WITH_IRIX_ARRAY
1049 #endif /* WITH_IRIX_ARRAY */
1050 #endif /* WITH_IRIX_JOBS */
1053 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1055 /* remove hostkey from the child's memory */
1056 destroy_sensitive_data();
1058 /* login(1) is only called if we execute the login shell */
1059 if (options.use_login && command != NULL)
1060 options.use_login = 0;
1062 #if !defined(HAVE_OSF_SIA)
1063 if (!options.use_login) {
1064 # ifdef HAVE_LOGIN_CAP
1065 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1066 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1067 _PATH_NOLOGIN), "r");
1068 # else /* HAVE_LOGIN_CAP */
1070 f = fopen(_PATH_NOLOGIN, "r");
1071 # endif /* HAVE_LOGIN_CAP */
1073 /* /etc/nologin exists. Print its contents and exit. */
1074 while (fgets(buf, sizeof(buf), f))
1080 #endif /* HAVE_OSF_SIA */
1082 /* Set login name, uid, gid, and groups. */
1083 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1084 switch, so we let login(1) to this for us. */
1085 if (!options.use_login) {
1087 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1088 if (!check_quietlogin(s, command))
1090 #else /* HAVE_OSF_SIA */
1094 if (getuid() == 0 || geteuid() == 0) {
1096 # ifdef HAVE_GETUSERATTR
1097 set_limits_from_userattr(pw->pw_name);
1098 # endif /* HAVE_GETUSERATTR */
1099 # ifdef HAVE_LOGIN_CAP
1100 if (setusercontext(lc, pw, pw->pw_uid,
1101 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1102 perror("unable to set user context");
1105 # else /* HAVE_LOGIN_CAP */
1106 #if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1107 /* Sets login uid for accounting */
1108 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1109 error("setluid: %s", strerror(errno));
1110 #endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1112 if (setlogin(pw->pw_name) < 0)
1113 error("setlogin failed: %s", strerror(errno));
1114 if (setgid(pw->pw_gid) < 0) {
1118 /* Initialize the group list. */
1119 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1120 perror("initgroups");
1126 * PAM credentials may take the form of
1127 * supplementary groups. These will have been
1128 * wiped by the above initgroups() call.
1129 * Reestablish them here.
1132 # endif /* USE_PAM */
1133 # ifdef WITH_IRIX_JOBS
1134 jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
1136 fatal("Failed to create job container: %.100s",
1139 # endif /* WITH_IRIX_JOBS */
1140 # ifdef WITH_IRIX_ARRAY
1141 /* initialize array session */
1143 if (newarraysess() != 0)
1144 fatal("Failed to set up new array session: %.100s",
1147 # endif /* WITH_IRIX_ARRAY */
1148 # ifdef WITH_IRIX_PROJECT
1149 /* initialize irix project info */
1150 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1151 debug("Failed to get project id, using projid 0");
1154 if (setprid(projid))
1155 fatal("Failed to initialize project %d for %s: %.100s",
1156 (int)projid, pw->pw_name, strerror(errno));
1157 # endif /* WITH_IRIX_PROJECT */
1158 #ifdef WITH_IRIX_AUDIT
1159 if (sysconf(_SC_AUDIT)) {
1160 debug("Setting sat id to %d", (int) pw->pw_uid);
1161 if (satsetid(pw->pw_uid))
1162 debug("error setting satid: %.100s", strerror(errno));
1164 #endif /* WITH_IRIX_AUDIT */
1168 * AIX has a "usrinfo" area where logname and
1169 * other stuff is stored - a few applications
1170 * actually use this and die if it's not set
1174 cp = xmalloc(22 + strlen(s->tty) +
1175 2 * strlen(pw->pw_name));
1176 i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
1177 pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
1178 if (usrinfo(SETUINFO, cp, i) == -1)
1179 fatal("Couldn't set usrinfo: %s",
1181 debug3("AIX/UsrInfo: set len %d", i);
1185 /* Permanently switch to the desired uid. */
1186 permanently_set_uid(pw);
1187 # endif /* HAVE_LOGIN_CAP */
1189 #endif /* HAVE_OSF_SIA */
1194 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1195 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1198 * Get the shell from the password data. An empty shell field is
1199 * legal, and means /bin/sh.
1201 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1202 #ifdef HAVE_LOGIN_CAP
1203 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1206 /* Initialize the environment. */
1208 env = xmalloc(envsize * sizeof(char *));
1213 * The Windows environment contains some setting which are
1214 * important for a running system. They must not be dropped.
1216 copy_environment(&env, &envsize);
1219 if (!options.use_login) {
1220 /* Set basic environment. */
1221 child_set_env(&env, &envsize, "USER", pw->pw_name);
1222 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1223 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1224 #ifdef HAVE_LOGIN_CAP
1225 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1226 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1227 #else /* HAVE_LOGIN_CAP */
1228 # ifndef HAVE_CYGWIN
1230 * There's no standard path on Windows. The path contains
1231 * important components pointing to the system directories,
1232 * needed for loading shared libraries. So the path better
1233 * remains intact here.
1235 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1236 # endif /* HAVE_CYGWIN */
1237 #endif /* HAVE_LOGIN_CAP */
1239 snprintf(buf, sizeof buf, "%.200s/%.50s",
1240 _PATH_MAILDIR, pw->pw_name);
1241 child_set_env(&env, &envsize, "MAIL", buf);
1243 /* Normal systems set SHELL by default. */
1244 child_set_env(&env, &envsize, "SHELL", shell);
1247 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1249 /* Set custom environment options from RSA authentication. */
1250 if (!options.use_login) {
1251 while (custom_environment) {
1252 struct envstring *ce = custom_environment;
1255 for (i = 0; s[i] != '=' && s[i]; i++)
1259 child_set_env(&env, &envsize, s, s + i + 1);
1261 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++)
1359 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1360 * xauth are run in the proper environment.
1365 /* Try to get AFS tokens for the local cell. */
1369 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1370 krb_afslog(cell, 0);
1376 /* Change current directory to the user\'s home directory. */
1377 if (chdir(pw->pw_dir) < 0) {
1378 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1379 pw->pw_dir, strerror(errno));
1380 #ifdef HAVE_LOGIN_CAP
1381 if (login_getcapbool(lc, "requirehome", 0))
1387 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1390 if (!options.use_login) {
1391 /* ignore _PATH_SSH_USER_RC for subsystems */
1392 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1393 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1394 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1396 fprintf(stderr, "Running %s\n", cmd);
1397 f = popen(cmd, "w");
1400 fprintf(f, "%s %s\n", s->auth_proto,
1404 fprintf(stderr, "Could not run %s\n",
1406 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1408 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1409 _PATH_SSH_SYSTEM_RC);
1410 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1413 fprintf(f, "%s %s\n", s->auth_proto,
1417 fprintf(stderr, "Could not run %s\n",
1418 _PATH_SSH_SYSTEM_RC);
1419 } else if (do_xauth && options.xauth_location != NULL) {
1420 /* Add authority data to .Xauthority if appropriate. */
1421 char *screen = strchr(s->display, ':');
1425 "Running %.100s add "
1426 "%.100s %.100s %.100s\n",
1427 options.xauth_location, s->display,
1428 s->auth_proto, s->auth_data);
1431 "Adding %.*s/unix%s %s %s\n",
1432 (int)(screen - s->display),
1434 s->auth_proto, s->auth_data);
1436 snprintf(cmd, sizeof cmd, "%s -q -",
1437 options.xauth_location);
1438 f = popen(cmd, "w");
1440 fprintf(f, "add %s %s %s\n", s->display,
1441 s->auth_proto, s->auth_data);
1443 fprintf(f, "add %.*s/unix%s %s %s\n",
1444 (int)(screen - s->display),
1450 fprintf(stderr, "Could not run %s\n",
1454 /* Get the last component of the shell name. */
1455 cp = strrchr(shell, '/');
1462 /* restore SIGPIPE for child */
1463 signal(SIGPIPE, SIG_DFL);
1466 * If we have no command, execute the shell. In this case, the shell
1467 * name to be passed in argv[0] is preceded by '-' to indicate that
1468 * this is a login shell.
1471 if (!options.use_login) {
1474 /* Start the shell. Set initial character to '-'. */
1476 strncpy(buf + 1, cp, sizeof(buf) - 1);
1477 buf[sizeof(buf) - 1] = 0;
1479 /* Execute the shell. */
1482 execve(shell, argv, env);
1484 /* Executing the shell failed. */
1489 /* Launch login(1). */
1491 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1492 #ifdef LOGIN_NEEDS_TERM
1493 s->term? s->term : "unknown",
1495 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1497 /* Login couldn't be executed, die. */
1504 * Execute the command using the user's shell. This uses the -c
1505 * option to execute the command.
1507 argv[0] = (char *) cp;
1509 argv[2] = (char *) command;
1511 execve(shell, argv, env);
1520 static int did_init = 0;
1522 debug("session_new: init");
1523 for(i = 0; i < MAX_SESSIONS; i++) {
1524 sessions[i].used = 0;
1528 for(i = 0; i < MAX_SESSIONS; i++) {
1529 Session *s = &sessions[i];
1531 memset(s, 0, sizeof(*s));
1537 debug("session_new: session %d", i);
1548 for(i = 0; i < MAX_SESSIONS; i++) {
1549 Session *s = &sessions[i];
1550 debug("dump: used %d session %d %p channel %d pid %d",
1560 session_open(Authctxt *authctxt, int chanid)
1562 Session *s = session_new();
1563 debug("session_open: channel %d", chanid);
1565 error("no more sessions");
1568 s->authctxt = authctxt;
1569 s->pw = authctxt->pw;
1571 fatal("no user for session %d", s->self);
1572 debug("session_open: session %d: link with channel %d", s->self, chanid);
1578 session_by_channel(int id)
1581 for(i = 0; i < MAX_SESSIONS; i++) {
1582 Session *s = &sessions[i];
1583 if (s->used && s->chanid == id) {
1584 debug("session_by_channel: session %d channel %d", i, id);
1588 debug("session_by_channel: unknown channel %d", id);
1594 session_by_pid(pid_t pid)
1597 debug("session_by_pid: pid %d", pid);
1598 for(i = 0; i < MAX_SESSIONS; i++) {
1599 Session *s = &sessions[i];
1600 if (s->used && s->pid == pid)
1603 error("session_by_pid: unknown pid %d", pid);
1609 session_window_change_req(Session *s)
1611 s->col = packet_get_int();
1612 s->row = packet_get_int();
1613 s->xpixel = packet_get_int();
1614 s->ypixel = packet_get_int();
1616 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1621 session_pty_req(Session *s)
1627 debug("Allocating a pty not permitted for this authentication.");
1630 if (s->ttyfd != -1) {
1631 packet_disconnect("Protocol error: you already have a pty.");
1635 s->term = packet_get_string(&len);
1638 s->col = packet_get_int();
1639 s->row = packet_get_int();
1641 s->row = packet_get_int();
1642 s->col = packet_get_int();
1644 s->xpixel = packet_get_int();
1645 s->ypixel = packet_get_int();
1647 if (strcmp(s->term, "") == 0) {
1652 /* Allocate a pty and open it. */
1653 debug("Allocating pty.");
1654 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1660 error("session_pty_req: session %d alloc failed", s->self);
1663 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1665 /* for SSH1 the tty modes length is not given */
1667 n_bytes = packet_remaining();
1668 tty_parse_modes(s->ttyfd, &n_bytes);
1671 * Add a cleanup function to clear the utmp entry and record logout
1672 * time in case we call fatal() (e.g., the connection gets closed).
1674 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1675 pty_setowner(s->pw, s->tty);
1677 /* Set window size from the packet. */
1678 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1681 session_proctitle(s);
1686 session_subsystem_req(Session *s)
1691 char *cmd, *subsys = packet_get_string(&len);
1695 log("subsystem request for %s", subsys);
1697 for (i = 0; i < options.num_subsystems; i++) {
1698 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1699 cmd = options.subsystem_command[i];
1700 if (stat(cmd, &st) < 0) {
1701 error("subsystem: cannot stat %s: %s", cmd,
1705 debug("subsystem: exec() %s", cmd);
1706 s->is_subsystem = 1;
1713 log("subsystem request for %s failed, subsystem not found",
1721 session_x11_req(Session *s)
1725 s->single_connection = packet_get_char();
1726 s->auth_proto = packet_get_string(NULL);
1727 s->auth_data = packet_get_string(NULL);
1728 s->screen = packet_get_int();
1731 success = session_setup_x11fwd(s);
1733 xfree(s->auth_proto);
1734 xfree(s->auth_data);
1735 s->auth_proto = NULL;
1736 s->auth_data = NULL;
1742 session_shell_req(Session *s)
1750 session_exec_req(Session *s)
1753 char *command = packet_get_string(&len);
1755 do_exec(s, command);
1761 session_auth_agent_req(Session *s)
1763 static int called = 0;
1765 if (no_agent_forwarding_flag) {
1766 debug("session_auth_agent_req: no_agent_forwarding_flag");
1773 return auth_input_request_forwarding(s->pw);
1778 session_input_channel_req(int id, void *arg)
1787 rtype = packet_get_string(&len);
1788 reply = packet_get_char();
1790 s = session_by_channel(id);
1792 fatal("session_input_channel_req: channel %d: no session", id);
1793 c = channel_lookup(id);
1795 fatal("session_input_channel_req: channel %d: bad channel", id);
1797 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1798 s->self, id, rtype, reply);
1801 * a session is in LARVAL state until a shell, a command
1802 * or a subsystem is executed
1804 if (c->type == SSH_CHANNEL_LARVAL) {
1805 if (strcmp(rtype, "shell") == 0) {
1806 success = session_shell_req(s);
1807 } else if (strcmp(rtype, "exec") == 0) {
1808 success = session_exec_req(s);
1809 } else if (strcmp(rtype, "pty-req") == 0) {
1810 success = session_pty_req(s);
1811 } else if (strcmp(rtype, "x11-req") == 0) {
1812 success = session_x11_req(s);
1813 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1814 success = session_auth_agent_req(s);
1815 } else if (strcmp(rtype, "subsystem") == 0) {
1816 success = session_subsystem_req(s);
1819 if (strcmp(rtype, "window-change") == 0) {
1820 success = session_window_change_req(s);
1824 packet_start(success ?
1825 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1826 packet_put_int(c->remote_id);
1833 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1836 fatal("session_set_fds: called for proto != 2.0");
1838 * now that have a child and a pipe to the child,
1839 * we can activate our channel and register the fd's
1841 if (s->chanid == -1)
1842 fatal("no channel for session %d", s->self);
1843 channel_set_fds(s->chanid,
1845 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1850 * Function to perform pty cleanup. Also called if we get aborted abnormally
1851 * (e.g., due to a dropped connection).
1854 session_pty_cleanup(void *session)
1856 Session *s = session;
1859 error("session_pty_cleanup: no session");
1865 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1867 /* Record that the user has logged out. */
1869 record_logout(s->pid, s->tty);
1871 /* Release the pseudo-tty. */
1872 pty_release(s->tty);
1875 * Close the server side of the socket pairs. We must do this after
1876 * the pty cleanup, so that another process doesn't get this pty
1877 * while we're still cleaning up.
1879 if (close(s->ptymaster) < 0)
1880 error("close(s->ptymaster): %s", strerror(errno));
1882 /* unlink pty from session */
1887 session_exit_message(Session *s, int status)
1891 fatal("session_close: no session");
1892 c = channel_lookup(s->chanid);
1894 fatal("session_exit_message: session %d: no channel %d",
1895 s->self, s->chanid);
1896 debug("session_exit_message: session %d channel %d pid %d",
1897 s->self, s->chanid, s->pid);
1899 if (WIFEXITED(status)) {
1900 channel_request_start(s->chanid,
1902 packet_put_int(WEXITSTATUS(status));
1904 } else if (WIFSIGNALED(status)) {
1905 channel_request_start(s->chanid,
1907 packet_put_int(WTERMSIG(status));
1909 packet_put_char(WCOREDUMP(status));
1910 #else /* WCOREDUMP */
1912 #endif /* WCOREDUMP */
1913 packet_put_cstring("");
1914 packet_put_cstring("");
1917 /* Some weird exit cause. Just exit. */
1918 packet_disconnect("wait returned status %04x.", status);
1921 /* disconnect channel */
1922 debug("session_exit_message: release channel %d", s->chanid);
1923 channel_cancel_cleanup(s->chanid);
1925 * emulate a write failure with 'chan_write_failed', nobody will be
1926 * interested in data we write.
1927 * Note that we must not call 'chan_read_failed', since there could
1928 * be some more data waiting in the pipe.
1930 if (c->ostate != CHAN_OUTPUT_CLOSED)
1931 chan_write_failed(c);
1936 session_close(Session *s)
1938 debug("session_close: session %d pid %d", s->self, s->pid);
1939 if (s->ttyfd != -1) {
1940 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1941 session_pty_cleanup(s);
1948 xfree(s->auth_data);
1950 xfree(s->auth_proto);
1952 session_proctitle(s);
1956 session_close_by_pid(pid_t pid, int status)
1958 Session *s = session_by_pid(pid);
1960 debug("session_close_by_pid: no session for pid %d", pid);
1963 if (s->chanid != -1)
1964 session_exit_message(s, status);
1969 * this is called when a channel dies before
1970 * the session 'child' itself dies
1973 session_close_by_channel(int id, void *arg)
1975 Session *s = session_by_channel(id);
1977 debug("session_close_by_channel: no session for id %d", id);
1980 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1982 debug("session_close_by_channel: channel %d: has child", id);
1984 * delay detach of session, but release pty, since
1985 * the fd's to the child are already closed
1987 if (s->ttyfd != -1) {
1988 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1989 session_pty_cleanup(s);
1993 /* detach by removing callback */
1994 channel_cancel_cleanup(s->chanid);
2000 session_destroy_all(void)
2003 for(i = 0; i < MAX_SESSIONS; i++) {
2004 Session *s = &sessions[i];
2011 session_tty_list(void)
2013 static char buf[1024];
2016 for(i = 0; i < MAX_SESSIONS; i++) {
2017 Session *s = &sessions[i];
2018 if (s->used && s->ttyfd != -1) {
2020 strlcat(buf, ",", sizeof buf);
2021 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2025 strlcpy(buf, "notty", sizeof buf);
2030 session_proctitle(Session *s)
2033 error("no user for session %d", s->self);
2035 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2039 session_setup_x11fwd(Session *s)
2043 if (no_x11_forwarding_flag) {
2044 packet_send_debug("X11 forwarding disabled in user configuration file.");
2047 if (!options.x11_forwarding) {
2048 debug("X11 forwarding disabled in server configuration file.");
2051 if (!options.xauth_location ||
2052 (stat(options.xauth_location, &st) == -1)) {
2053 packet_send_debug("No xauth program; cannot forward with spoofing.");
2056 if (options.use_login) {
2057 packet_send_debug("X11 forwarding disabled; "
2058 "not compatible with UseLogin=yes.");
2061 if (s->display != NULL) {
2062 debug("X11 display already set.");
2065 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
2066 if (s->display == NULL) {
2067 debug("x11_create_display_inet failed.");
2074 do_authenticated2(Authctxt *authctxt)
2076 server_loop2(authctxt);