2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * SSH2 support by Markus Friedl.
7 * Copyright (c) 2000 Markus Friedl. All rights reserved.
11 RCSID("$OpenBSD: session.c,v 1.29 2000/08/21 16:23:31 millert Exp $");
29 #include "auth-options.h"
31 #ifdef WITH_IRIX_PROJECT
33 #endif /* WITH_IRIX_PROJECT */
35 #if defined(HAVE_USERSEC_H)
45 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
46 # define S_UFSIZE_HARD S_UFSIZE "_hard"
47 # define S_UCPU_HARD S_UCPU "_hard"
48 # define S_UDATA_HARD S_UDATA "_hard"
49 # define S_USTACK_HARD S_USTACK "_hard"
50 # define S_URSS_HARD S_URSS "_hard"
51 # define S_UCORE_HARD S_UCORE "_hard"
52 # define S_UNOFILE_HARD S_UNOFILE "_hard"
56 #include <login_cap.h>
62 typedef struct Session Session;
71 int ptyfd, ttyfd, ptymaster;
72 int row, col, xpixel, ypixel;
79 int single_connection;
86 Session *session_new(void);
87 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
88 void session_pty_cleanup(Session *s);
89 void session_proctitle(Session *s);
90 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
91 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
92 void do_login(Session *s);
95 do_child(const char *command, struct passwd * pw, const char *term,
96 const char *display, const char *auth_proto,
97 const char *auth_data, const char *ttyname);
100 extern ServerOptions options;
101 #ifdef HAVE___PROGNAME
102 extern char *__progname;
103 #else /* HAVE___PROGNAME */
104 static const char *__progname = "sshd";
105 #endif /* HAVE___PROGNAME */
107 extern int log_stderr;
108 extern int debug_flag;
109 extern unsigned int utmp_len;
111 extern int startup_pipe;
113 /* Local Xauthority file. */
114 static char *xauthfile;
117 #define MAX_SESSIONS 10
118 Session sessions[MAX_SESSIONS];
119 #ifdef WITH_AIXAUTHENTICATE
120 /* AIX's lastlogin message, set in auth1.c */
122 #endif /* WITH_AIXAUTHENTICATE */
124 #ifdef HAVE_LOGIN_CAP
125 static login_cap_t *lc;
129 * Remove local Xauthority file.
132 xauthfile_cleanup_proc(void *ignore)
134 debug("xauthfile_cleanup_proc called");
136 if (xauthfile != NULL) {
139 p = strrchr(xauthfile, '/');
150 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
151 * dropped connection).
154 pty_cleanup_proc(void *session)
158 fatal("pty_cleanup_proc: no session");
159 debug("pty_cleanup_proc: %s", s->tty);
162 /* Record that the user has logged out. */
163 record_logout(s->pid, s->tty);
166 /* Release the pseudo-tty. */
171 * Prepares for an interactive session. This is called after the user has
172 * been successfully authenticated. During this message exchange, pseudo
173 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
174 * are requested, etc.
177 do_authenticated(struct passwd * pw)
181 int compression_level = 0, enable_compression_after_reply = 0;
186 unsigned int proto_len, data_len, dlen;
189 * Cancel the alarm we set to limit the time taken for
193 if (startup_pipe != -1) {
199 * Inform the channel mechanism that we are the server side and that
200 * the client may request to connect to any port at all. (The user
201 * could do it anyway, and we wouldn\'t know what is permitted except
202 * by the client telling us, so we can equally well trust the client
203 * not to request anything bogus.)
205 if (!no_port_forwarding_flag)
206 channel_permit_all_opens();
211 #ifdef HAVE_LOGIN_CAP
212 if ((lc = login_getclass(pw->pw_class)) == NULL) {
213 error("unable to get login class");
219 * We stay in this loop until the client requests to execute a shell
225 /* Get a packet from the client. */
226 type = packet_read(&plen);
228 /* Process the packet. */
230 case SSH_CMSG_REQUEST_COMPRESSION:
231 packet_integrity_check(plen, 4, type);
232 compression_level = packet_get_int();
233 if (compression_level < 1 || compression_level > 9) {
234 packet_send_debug("Received illegal compression level %d.",
238 /* Enable compression after we have responded with SUCCESS. */
239 enable_compression_after_reply = 1;
243 case SSH_CMSG_REQUEST_PTY:
245 debug("Allocating a pty not permitted for this authentication.");
249 packet_disconnect("Protocol error: you already have a pty.");
251 debug("Allocating pty.");
253 /* Allocate a pty and open it. */
254 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
256 error("Failed to allocate pty.");
259 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
260 pty_setowner(pw, s->tty);
262 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
263 s->term = packet_get_string(&dlen);
264 packet_integrity_check(dlen, strlen(s->term), type);
265 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
266 /* Remaining bytes */
267 n_bytes = plen - (4 + dlen + 4 * 4);
269 if (strcmp(s->term, "") == 0) {
273 /* Get window size from the packet. */
274 s->row = packet_get_int();
275 s->col = packet_get_int();
276 s->xpixel = packet_get_int();
277 s->ypixel = packet_get_int();
278 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
280 /* Get tty modes from the packet. */
281 tty_parse_modes(s->ttyfd, &n_bytes);
282 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
284 session_proctitle(s);
286 /* Indicate that we now have a pty. */
291 case SSH_CMSG_X11_REQUEST_FORWARDING:
292 if (!options.x11_forwarding) {
293 packet_send_debug("X11 forwarding disabled in server configuration file.");
296 if (!options.xauth_location) {
297 packet_send_debug("No xauth program; cannot forward with spoofing.");
300 if (no_x11_forwarding_flag) {
301 packet_send_debug("X11 forwarding not permitted for this authentication.");
304 debug("Received request for X11 forwarding with auth spoofing.");
305 if (s->display != NULL)
306 packet_disconnect("Protocol error: X11 display already set.");
308 s->auth_proto = packet_get_string(&proto_len);
309 s->auth_data = packet_get_string(&data_len);
310 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
312 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
313 s->screen = packet_get_int();
316 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
318 if (s->display == NULL)
321 /* Setup to always have a local .Xauthority. */
322 xauthfile = xmalloc(MAXPATHLEN);
323 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
324 temporarily_use_uid(pw->pw_uid);
325 if (mkdtemp(xauthfile) == NULL) {
327 error("private X11 dir: mkdtemp %s failed: %s",
328 xauthfile, strerror(errno));
331 /* XXXX remove listening channels */
334 strlcat(xauthfile, "/cookies", MAXPATHLEN);
335 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
337 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
341 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
342 if (no_agent_forwarding_flag || compat13) {
343 debug("Authentication agent forwarding not permitted for this authentication.");
346 debug("Received authentication agent forwarding request.");
347 success = auth_input_request_forwarding(pw);
350 case SSH_CMSG_PORT_FORWARD_REQUEST:
351 if (no_port_forwarding_flag) {
352 debug("Port forwarding not permitted for this authentication.");
355 debug("Received TCP/IP port forwarding request.");
356 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
360 case SSH_CMSG_MAX_PACKET_SIZE:
361 if (packet_set_maxsize(packet_get_int()) > 0)
365 case SSH_CMSG_EXEC_SHELL:
366 case SSH_CMSG_EXEC_CMD:
367 /* Set interactive/non-interactive mode. */
368 packet_set_interactive(have_pty || s->display != NULL,
371 if (type == SSH_CMSG_EXEC_CMD) {
372 command = packet_get_string(&dlen);
373 debug("Exec command '%.500s'", command);
374 packet_integrity_check(plen, 4 + dlen, type);
377 packet_integrity_check(plen, 0, type);
379 if (forced_command != NULL) {
380 command = forced_command;
381 debug("Forced command '%.500s'", forced_command);
384 do_exec_pty(s, command, pw);
386 do_exec_no_pty(s, command, pw);
390 /* Cleanup user's local Xauthority file. */
392 xauthfile_cleanup_proc(NULL);
397 * Any unknown messages in this phase are ignored,
398 * and a failure message is returned.
400 log("Unknown packet type received after authentication: %d", type);
402 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
406 /* Enable compression now that we have replied if appropriate. */
407 if (enable_compression_after_reply) {
408 enable_compression_after_reply = 0;
409 packet_start_compression(compression_level);
415 * This is called to fork and execute a command when we have no tty. This
416 * will call do_child from the child, and server_loop from the parent after
417 * setting up file descriptors and such.
420 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
425 int pin[2], pout[2], perr[2];
426 /* Allocate pipes for communicating with the program. */
427 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
428 packet_disconnect("Could not create pipes: %.100s",
430 #else /* USE_PIPES */
431 int inout[2], err[2];
432 /* Uses socket pairs to communicate with the program. */
433 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
434 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
435 packet_disconnect("Could not create socket pairs: %.100s",
437 #endif /* USE_PIPES */
439 fatal("do_exec_no_pty: no session");
441 session_proctitle(s);
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(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
501 packet_disconnect("fork failed: %.100s", strerror(errno));
504 /* We are the parent. Close the child sides of the pipes. */
510 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
512 /* Enter the interactive session. */
513 server_loop(pid, pin[1], pout[0], perr[0]);
514 /* server_loop has closed pin[1], pout[1], and perr[1]. */
516 #else /* USE_PIPES */
517 /* We are the parent. Close the child sides of the socket pairs. */
522 * Enter the interactive session. Note: server_loop must be able to
523 * handle the case that fdin and fdout are the same.
526 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
528 server_loop(pid, inout[1], inout[1], err[1]);
529 /* server_loop has closed inout[1] and err[1]. */
531 #endif /* USE_PIPES */
535 * This is called to fork and execute a command when we have a tty. This
536 * will call do_child from the child, and server_loop from the parent after
537 * setting up file descriptors, controlling tty, updating wtmp, utmp,
538 * lastlog, and other such operations.
541 do_exec_pty(Session *s, const char *command, struct passwd * pw)
543 int fdout, ptyfd, ttyfd, ptymaster;
547 fatal("do_exec_pty: no session");
552 do_pam_session(pw->pw_name, s->tty);
556 /* Fork the child. */
557 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);
561 /* Close the master side of the pseudo tty. */
564 /* Make the pseudo tty our controlling tty. */
565 pty_make_controlling_tty(&ttyfd, s->tty);
567 /* Redirect stdin from the pseudo tty. */
568 if (dup2(ttyfd, fileno(stdin)) < 0)
569 error("dup2 stdin failed: %.100s", strerror(errno));
571 /* Redirect stdout to the pseudo tty. */
572 if (dup2(ttyfd, fileno(stdout)) < 0)
573 error("dup2 stdin failed: %.100s", strerror(errno));
575 /* Redirect stderr to the pseudo tty. */
576 if (dup2(ttyfd, fileno(stderr)) < 0)
577 error("dup2 stdin failed: %.100s", strerror(errno));
579 /* Close the extra descriptor for the pseudo tty. */
582 /* record login, etc. similar to login(1) */
583 if (command == NULL && !options.use_login)
586 /* Do common processing for the child, such as execing the command. */
587 do_child(command, pw, s->term, s->display, s->auth_proto,
588 s->auth_data, s->tty);
592 packet_disconnect("fork failed: %.100s", strerror(errno));
595 /* Parent. Close the slave side of the pseudo tty. */
599 * Create another descriptor of the pty master side for use as the
600 * standard input. We could use the original descriptor, but this
601 * simplifies code in server_loop. The descriptor is bidirectional.
605 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
607 /* we keep a reference to the pty master */
608 ptymaster = dup(ptyfd);
610 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
611 s->ptymaster = ptymaster;
613 /* Enter interactive session. */
615 session_set_fds(s, ptyfd, fdout, -1);
617 server_loop(pid, ptyfd, fdout, -1);
618 /* server_loop _has_ closed ptyfd and fdout. */
619 session_pty_cleanup(s);
624 get_remote_name_or_ip(void)
626 static const char *remote = "";
628 remote = get_canonical_hostname();
629 if (utmp_len == 0 || strlen(remote) > utmp_len)
630 remote = get_remote_ipaddr();
634 /* administrative, login(1)-like work */
642 struct sockaddr_storage from;
644 time_t last_login_time;
645 struct passwd * pw = s->pw;
646 pid_t pid = getpid();
649 * Get IP address of client. If the connection is not a socket, let
650 * the address be 0.0.0.0.
652 memset(&from, 0, sizeof(from));
653 if (packet_connection_is_on_socket()) {
654 fromlen = sizeof(from);
655 if (getpeername(packet_get_connection_in(),
656 (struct sockaddr *) & from, &fromlen) < 0) {
657 debug("getpeername: %.100s", strerror(errno));
662 /* Record that there was a login on that tty from the remote host. */
663 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
664 get_remote_name_or_ip(), (struct sockaddr *)&from);
666 /* Done if .hushlogin exists. */
667 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
668 #ifdef HAVE_LOGIN_CAP
669 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
671 if (stat(buf, &st) >= 0)
676 print_pam_messages();
678 #ifdef WITH_AIXAUTHENTICATE
679 if (aixloginmsg && *aixloginmsg)
680 printf("%s\n", aixloginmsg);
681 #endif /* WITH_AIXAUTHENTICATE */
684 * Get the time when the user last logged in. 'buf' will be set
685 * to contain the hostname the last login was from.
687 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
689 if (last_login_time != 0) {
690 time_string = ctime(&last_login_time);
691 if (strchr(time_string, '\n'))
692 *strchr(time_string, '\n') = 0;
693 if (strcmp(buf, "") == 0)
694 printf("Last login: %s\r\n", time_string);
696 printf("Last login: %s from %s\r\n", time_string, buf);
698 if (options.print_motd) {
699 #ifdef HAVE_LOGIN_CAP
700 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
703 f = fopen("/etc/motd", "r");
706 while (fgets(buf, sizeof(buf), f))
714 * Sets the value of the given variable in the environment. If the variable
715 * already exists, its value is overriden.
718 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
721 unsigned int i, namelen;
725 * Find the slot where the value should be stored. If the variable
726 * already exists, we reuse the slot; otherwise we append a new slot
727 * at the end of the array, expanding if necessary.
730 namelen = strlen(name);
731 for (i = 0; env[i]; i++)
732 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
735 /* Reuse the slot. */
738 /* New variable. Expand if necessary. */
739 if (i >= (*envsizep) - 1) {
741 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
743 /* Need to set the NULL pointer at end of array beyond the new slot. */
747 /* Allocate space and format the variable in the appropriate slot. */
748 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
749 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
753 * Reads environment variables from the given file and adds/overrides them
754 * into the environment. If the file does not exist, this does nothing.
755 * Otherwise, it must consist of empty lines, comments (line starts with '#')
756 * and assignments of the form name=value. No other forms are allowed.
759 read_environment_file(char ***env, unsigned int *envsize,
760 const char *filename)
766 f = fopen(filename, "r");
770 while (fgets(buf, sizeof(buf), f)) {
771 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
773 if (!*cp || *cp == '#' || *cp == '\n')
775 if (strchr(cp, '\n'))
776 *strchr(cp, '\n') = '\0';
777 value = strchr(cp, '=');
779 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
783 * Replace the equals sign by nul, and advance value to
788 child_set_env(env, envsize, cp, value);
795 * Sets any environment variables which have been specified by PAM
797 void do_pam_environment(char ***env, int *envsize)
799 char *equals, var_name[512], var_val[512];
803 if ((pam_env = fetch_pam_environment()) == NULL)
806 for(i = 0; pam_env[i] != NULL; i++) {
807 if ((equals = strstr(pam_env[i], "=")) == NULL)
810 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
811 memset(var_name, '\0', sizeof(var_name));
812 memset(var_val, '\0', sizeof(var_val));
814 strncpy(var_name, pam_env[i], equals - pam_env[i]);
815 strcpy(var_val, equals + 1);
817 debug("PAM environment: %s=%s", var_name, var_val);
819 child_set_env(env, envsize, var_name, var_val);
825 #if defined(HAVE_GETUSERATTR)
827 * AIX-specific login initialisation
829 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
834 getrlimit(resource, &rlim);
837 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
839 rlim.rlim_cur = RLIM_INFINITY;
840 } else if (slim != 0) {
841 /* See the wackiness below */
842 if (rlim.rlim_cur == slim * mult)
845 rlim.rlim_cur = slim * mult;
850 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
852 rlim.rlim_max = RLIM_INFINITY;
853 } else if (hlim != 0) {
854 rlim.rlim_max = hlim * mult;
859 * XXX For cpu and fsize the soft limit is set to the hard limit
860 * if the hard limit is left at its default value and the soft limit
861 * is changed from its default value, either by requesting it
862 * (slim == 0) or by setting it to the current default. At least
863 * that's how rlogind does it. If you're confused you're not alone.
864 * Bug or feature? AIX 4.3.1.2
866 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
867 && hlim == 0 && slim != 0)
868 rlim.rlim_max = rlim.rlim_cur;
869 /* A specified hard limit limits the soft limit */
870 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
871 rlim.rlim_cur = rlim.rlim_max;
872 /* A soft limit can increase a hard limit */
873 else if (rlim.rlim_cur > rlim.rlim_max)
874 rlim.rlim_max = rlim.rlim_cur;
876 if (setrlimit(resource, &rlim) != 0)
877 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
880 void set_limits_from_userattr(char *user)
885 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
886 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
887 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
888 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
889 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
890 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
891 #if defined(S_UNOFILE)
892 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
895 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
896 /* Convert decimal to octal */
897 (void) snprintf(buf, sizeof(buf), "%d", mask);
898 if (sscanf(buf, "%o", &mask) == 1)
902 #endif /* defined(HAVE_GETUSERATTR) */
905 * Performs common processing for the child, such as setting up the
906 * environment, closing extra file descriptors, setting the user and group
907 * ids, and executing the command or shell.
910 do_child(const char *command, struct passwd * pw, const char *term,
911 const char *display, const char *auth_proto,
912 const char *auth_data, const char *ttyname)
914 const char *shell, *hostname, *cp = NULL;
918 unsigned int envsize, i;
920 extern char **environ;
923 #ifdef WITH_IRIX_PROJECT
925 #endif /* WITH_IRIX_PROJECT */
927 /* login(1) is only called if we execute the login shell */
928 if (options.use_login && command != NULL)
929 options.use_login = 0;
931 #ifndef USE_PAM /* pam_nologin handles this */
932 if (!options.use_login) {
933 # ifdef HAVE_LOGIN_CAP
934 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
935 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
936 _PATH_NOLOGIN), "r");
937 # else /* HAVE_LOGIN_CAP */
939 f = fopen(_PATH_NOLOGIN, "r");
940 # endif /* HAVE_LOGIN_CAP */
942 /* /etc/nologin exists. Print its contents and exit. */
943 while (fgets(buf, sizeof(buf), f))
951 /* Set login name, uid, gid, and groups. */
952 /* Login(1) does this as well, and it needs uid 0 for the "-h"
953 switch, so we let login(1) to this for us. */
954 if (!options.use_login) {
956 extern char **saved_argv;
957 extern int saved_argc;
958 char *host = get_canonical_hostname ();
960 if (sia_become_user(NULL, saved_argc, saved_argv, host,
961 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
963 perror("sia_become_user");
966 if (setreuid(geteuid(), geteuid()) < 0) {
970 #else /* HAVE_OSF_SIA */
971 if (getuid() == 0 || geteuid() == 0) {
972 # ifdef HAVE_GETUSERATTR
973 set_limits_from_userattr(pw->pw_name);
974 # endif /* HAVE_GETUSERATTR */
975 # ifdef HAVE_LOGIN_CAP
976 if (setusercontext(lc, pw, pw->pw_uid,
977 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
978 perror("unable to set user context");
981 # else /* HAVE_LOGIN_CAP */
982 if (setlogin(pw->pw_name) < 0)
983 error("setlogin failed: %s", strerror(errno));
984 if (setgid(pw->pw_gid) < 0) {
988 /* Initialize the group list. */
989 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
990 perror("initgroups");
994 # ifdef WITH_IRIX_ARRAY
995 /* initialize array session */
996 if (newarraysess() != 0)
997 fatal("Failed to set up new array session: %.100s",
999 # endif /* WITH_IRIX_ARRAY */
1000 # ifdef WITH_IRIX_PROJECT
1001 /* initialize irix project info */
1002 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1003 debug("Failed to get project id, using projid 0");
1006 if (setprid(projid))
1007 fatal("Failed to initialize project %d for %s: %.100s",
1008 (int)projid, pw->pw_name, strerror(errno));
1009 # endif /* WITH_IRIX_PROJECT */
1010 /* Permanently switch to the desired uid. */
1011 permanently_set_uid(pw->pw_uid);
1012 # endif /* HAVE_LOGIN_CAP */
1014 #endif /* HAVE_OSF_SIA */
1016 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1017 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
1020 * Get the shell from the password data. An empty shell field is
1021 * legal, and means /bin/sh.
1023 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1024 #ifdef HAVE_LOGIN_CAP
1025 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1029 /* Try to get AFS tokens for the local cell. */
1033 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1034 krb_afslog(cell, 0);
1040 /* Initialize the environment. */
1042 env = xmalloc(envsize * sizeof(char *));
1045 if (!options.use_login) {
1046 /* Set basic environment. */
1047 child_set_env(&env, &envsize, "USER", pw->pw_name);
1048 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1049 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1050 #ifdef HAVE_LOGIN_CAP
1051 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1052 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1054 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1057 snprintf(buf, sizeof buf, "%.200s/%.50s",
1058 _PATH_MAILDIR, pw->pw_name);
1059 child_set_env(&env, &envsize, "MAIL", buf);
1061 /* Normal systems set SHELL by default. */
1062 child_set_env(&env, &envsize, "SHELL", shell);
1065 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1067 /* Set custom environment options from RSA authentication. */
1068 while (custom_environment) {
1069 struct envstring *ce = custom_environment;
1072 for (i = 0; s[i] != '=' && s[i]; i++);
1075 child_set_env(&env, &envsize, s, s + i + 1);
1077 custom_environment = ce->next;
1082 snprintf(buf, sizeof buf, "%.50s %d %d",
1083 get_remote_ipaddr(), get_remote_port(), get_local_port());
1084 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1087 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1089 child_set_env(&env, &envsize, "TERM", term);
1091 child_set_env(&env, &envsize, "DISPLAY", display);
1095 char *authstate,*krb5cc;
1097 if ((authstate = getenv("AUTHSTATE")) != NULL)
1098 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1100 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1101 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1107 extern char *ticket;
1110 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1115 /* Pull in any environment variables that may have been set by PAM. */
1116 do_pam_environment(&env, &envsize);
1117 #endif /* USE_PAM */
1119 read_environment_file(&env,&envsize,"/etc/environment");
1122 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1123 if (auth_get_socket_name() != NULL)
1124 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1125 auth_get_socket_name());
1127 /* read $HOME/.ssh/environment. */
1128 if (!options.use_login) {
1129 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1131 read_environment_file(&env, &envsize, buf);
1134 /* dump the environment */
1135 fprintf(stderr, "Environment:\n");
1136 for (i = 0; env[i]; i++)
1137 fprintf(stderr, " %.200s\n", env[i]);
1139 /* we have to stash the hostname before we close our socket. */
1140 if (options.use_login)
1141 hostname = get_remote_name_or_ip();
1143 * Close the connection descriptors; note that this is the child, and
1144 * the server will still have the socket open, and it is important
1145 * that we do not shutdown it. Note that the descriptors cannot be
1146 * closed before building the environment, as we call
1147 * get_remote_ipaddr there.
1149 if (packet_get_connection_in() == packet_get_connection_out())
1150 close(packet_get_connection_in());
1152 close(packet_get_connection_in());
1153 close(packet_get_connection_out());
1156 * Close all descriptors related to channels. They will still remain
1157 * open in the parent.
1159 /* XXX better use close-on-exec? -markus */
1160 channel_close_all();
1163 * Close any extra file descriptors. Note that there may still be
1164 * descriptors left by system functions. They will be closed later.
1169 * Close any extra open file descriptors so that we don\'t have them
1170 * hanging around in clients. Note that we want to do this after
1171 * initgroups, because at least on Solaris 2.3 it leaves file
1174 for (i = 3; i < 64; i++)
1177 /* Change current directory to the user\'s home directory. */
1178 if (chdir(pw->pw_dir) < 0) {
1179 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1180 pw->pw_dir, strerror(errno));
1181 #ifdef HAVE_LOGIN_CAP
1182 if (login_getcapbool(lc, "requirehome", 0))
1188 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1189 * xauth are run in the proper environment.
1194 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1197 if (!options.use_login) {
1198 if (stat(SSH_USER_RC, &st) >= 0) {
1200 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1202 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1204 if (auth_proto != NULL && auth_data != NULL)
1205 fprintf(f, "%s %s\n", auth_proto, auth_data);
1208 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1209 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1211 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1213 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1215 if (auth_proto != NULL && auth_data != NULL)
1216 fprintf(f, "%s %s\n", auth_proto, auth_data);
1219 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1220 } else if (options.xauth_location != NULL) {
1221 /* Add authority data to .Xauthority if appropriate. */
1222 if (auth_proto != NULL && auth_data != NULL) {
1223 char *screen = strchr(display, ':');
1226 "Running %.100s add %.100s %.100s %.100s\n",
1227 options.xauth_location, display,
1228 auth_proto, auth_data);
1231 "Adding %.*s/unix%s %s %s\n",
1232 screen-display, display,
1233 screen, auth_proto, auth_data);
1235 snprintf(cmd, sizeof cmd, "%s -q -",
1236 options.xauth_location);
1237 f = popen(cmd, "w");
1239 fprintf(f, "add %s %s %s\n", display,
1240 auth_proto, auth_data);
1242 fprintf(f, "add %.*s/unix%s %s %s\n",
1243 screen-display, display,
1244 screen, auth_proto, auth_data);
1247 fprintf(stderr, "Could not run %s\n",
1252 /* Get the last component of the shell name. */
1253 cp = strrchr(shell, '/');
1260 * If we have no command, execute the shell. In this case, the shell
1261 * name to be passed in argv[0] is preceded by '-' to indicate that
1262 * this is a login shell.
1265 if (!options.use_login) {
1269 * Check for mail if we have a tty and it was enabled
1270 * in server options.
1272 if (ttyname && options.check_mail) {
1274 struct stat mailstat;
1275 mailbox = getenv("MAIL");
1276 if (mailbox != NULL) {
1277 if (stat(mailbox, &mailstat) != 0 ||
1278 mailstat.st_size == 0)
1279 printf("No mail.\n");
1280 else if (mailstat.st_mtime < mailstat.st_atime)
1281 printf("You have mail.\n");
1283 printf("You have new mail.\n");
1286 /* Start the shell. Set initial character to '-'. */
1288 strncpy(buf + 1, cp, sizeof(buf) - 1);
1289 buf[sizeof(buf) - 1] = 0;
1291 /* Execute the shell. */
1294 execve(shell, argv, env);
1296 /* Executing the shell failed. */
1301 /* Launch login(1). */
1303 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1304 "-p", "-f", "--", pw->pw_name, NULL);
1306 /* Login couldn't be executed, die. */
1313 * Execute the command using the user's shell. This uses the -c
1314 * option to execute the command.
1316 argv[0] = (char *) cp;
1318 argv[2] = (char *) command;
1320 execve(shell, argv, env);
1329 static int did_init = 0;
1331 debug("session_new: init");
1332 for(i = 0; i < MAX_SESSIONS; i++) {
1333 sessions[i].used = 0;
1334 sessions[i].self = i;
1338 for(i = 0; i < MAX_SESSIONS; i++) {
1339 Session *s = &sessions[i];
1350 s->auth_data = NULL;
1351 s->auth_proto = NULL;
1354 debug("session_new: session %d", i);
1365 for(i = 0; i < MAX_SESSIONS; i++) {
1366 Session *s = &sessions[i];
1367 debug("dump: used %d session %d %p channel %d pid %d",
1377 session_open(int chanid)
1379 Session *s = session_new();
1380 debug("session_open: channel %d", chanid);
1382 error("no more sessions");
1385 s->pw = auth_get_user();
1387 fatal("no user for session %i", s->self);
1388 debug("session_open: session %d: link with channel %d", s->self, chanid);
1394 session_by_channel(int id)
1397 for(i = 0; i < MAX_SESSIONS; i++) {
1398 Session *s = &sessions[i];
1399 if (s->used && s->chanid == id) {
1400 debug("session_by_channel: session %d channel %d", i, id);
1404 debug("session_by_channel: unknown channel %d", id);
1410 session_by_pid(pid_t pid)
1413 debug("session_by_pid: pid %d", pid);
1414 for(i = 0; i < MAX_SESSIONS; i++) {
1415 Session *s = &sessions[i];
1416 if (s->used && s->pid == pid)
1419 error("session_by_pid: unknown pid %d", pid);
1425 session_window_change_req(Session *s)
1427 s->col = packet_get_int();
1428 s->row = packet_get_int();
1429 s->xpixel = packet_get_int();
1430 s->ypixel = packet_get_int();
1432 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1437 session_pty_req(Session *s)
1440 char *term_modes; /* encoded terminal modes */
1446 s->term = packet_get_string(&len);
1447 s->col = packet_get_int();
1448 s->row = packet_get_int();
1449 s->xpixel = packet_get_int();
1450 s->ypixel = packet_get_int();
1451 term_modes = packet_get_string(&len);
1454 if (strcmp(s->term, "") == 0) {
1458 /* Allocate a pty and open it. */
1459 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1464 error("session_pty_req: session %d alloc failed", s->self);
1468 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1470 * Add a cleanup function to clear the utmp entry and record logout
1471 * time in case we call fatal() (e.g., the connection gets closed).
1473 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1474 pty_setowner(s->pw, s->tty);
1475 /* Get window size from the packet. */
1476 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1478 session_proctitle(s);
1480 /* XXX parse and set terminal modes */
1486 session_subsystem_req(Session *s)
1490 char *subsys = packet_get_string(&len);
1494 log("subsystem request for %s", subsys);
1496 for (i = 0; i < options.num_subsystems; i++) {
1497 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1498 debug("subsystem: exec() %s", options.subsystem_command[i]);
1499 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1505 log("subsystem request for %s failed, subsystem not found", subsys);
1512 session_x11_req(Session *s)
1514 if (no_x11_forwarding_flag) {
1515 debug("X11 forwarding disabled in user configuration file.");
1518 if (!options.x11_forwarding) {
1519 debug("X11 forwarding disabled in server configuration file.");
1522 if (xauthfile != NULL) {
1523 debug("X11 fwd already started.");
1527 debug("Received request for X11 forwarding with auth spoofing.");
1528 if (s->display != NULL)
1529 packet_disconnect("Protocol error: X11 display already set.");
1531 s->single_connection = packet_get_char();
1532 s->auth_proto = packet_get_string(NULL);
1533 s->auth_data = packet_get_string(NULL);
1534 s->screen = packet_get_int();
1537 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1538 if (s->display == NULL) {
1539 xfree(s->auth_proto);
1540 xfree(s->auth_data);
1543 xauthfile = xmalloc(MAXPATHLEN);
1544 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1545 temporarily_use_uid(s->pw->pw_uid);
1546 if (mkdtemp(xauthfile) == NULL) {
1548 error("private X11 dir: mkdtemp %s failed: %s",
1549 xauthfile, strerror(errno));
1552 xfree(s->auth_proto);
1553 xfree(s->auth_data);
1554 /* XXXX remove listening channels */
1557 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1558 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1560 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1565 session_shell_req(Session *s)
1567 /* if forced_command == NULL, the shell is execed */
1568 char *shell = forced_command;
1572 do_exec_no_pty(s, shell, s->pw);
1574 do_exec_pty(s, shell, s->pw);
1579 session_exec_req(Session *s)
1582 char *command = packet_get_string(&len);
1584 if (forced_command) {
1586 command = forced_command;
1587 debug("Forced command '%.500s'", forced_command);
1591 do_exec_no_pty(s, command, s->pw);
1593 do_exec_pty(s, command, s->pw);
1594 if (forced_command == NULL)
1600 session_input_channel_req(int id, void *arg)
1609 rtype = packet_get_string(&len);
1610 reply = packet_get_char();
1612 s = session_by_channel(id);
1614 fatal("session_input_channel_req: channel %d: no session", id);
1615 c = channel_lookup(id);
1617 fatal("session_input_channel_req: channel %d: bad channel", id);
1619 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1620 s->self, id, rtype, reply);
1623 * a session is in LARVAL state until a shell
1624 * or programm is executed
1626 if (c->type == SSH_CHANNEL_LARVAL) {
1627 if (strcmp(rtype, "shell") == 0) {
1628 success = session_shell_req(s);
1629 } else if (strcmp(rtype, "exec") == 0) {
1630 success = session_exec_req(s);
1631 } else if (strcmp(rtype, "pty-req") == 0) {
1632 success = session_pty_req(s);
1633 } else if (strcmp(rtype, "x11-req") == 0) {
1634 success = session_x11_req(s);
1635 } else if (strcmp(rtype, "subsystem") == 0) {
1636 success = session_subsystem_req(s);
1639 if (strcmp(rtype, "window-change") == 0) {
1640 success = session_window_change_req(s);
1644 packet_start(success ?
1645 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1646 packet_put_int(c->remote_id);
1653 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1656 fatal("session_set_fds: called for proto != 2.0");
1658 * now that have a child and a pipe to the child,
1659 * we can activate our channel and register the fd's
1661 if (s->chanid == -1)
1662 fatal("no channel for session %d", s->self);
1663 channel_set_fds(s->chanid,
1665 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1669 session_pty_cleanup(Session *s)
1671 if (s == NULL || s->ttyfd == -1)
1674 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1676 /* Cancel the cleanup function. */
1677 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1679 /* Record that the user has logged out. */
1680 record_logout(s->pid, s->tty);
1682 /* Release the pseudo-tty. */
1683 pty_release(s->tty);
1686 * Close the server side of the socket pairs. We must do this after
1687 * the pty cleanup, so that another process doesn't get this pty
1688 * while we're still cleaning up.
1690 if (close(s->ptymaster) < 0)
1691 error("close(s->ptymaster): %s", strerror(errno));
1695 session_exit_message(Session *s, int status)
1699 fatal("session_close: no session");
1700 c = channel_lookup(s->chanid);
1702 fatal("session_close: session %d: no channel %d",
1703 s->self, s->chanid);
1704 debug("session_exit_message: session %d channel %d pid %d",
1705 s->self, s->chanid, s->pid);
1707 if (WIFEXITED(status)) {
1708 channel_request_start(s->chanid,
1710 packet_put_int(WEXITSTATUS(status));
1712 } else if (WIFSIGNALED(status)) {
1713 channel_request_start(s->chanid,
1715 packet_put_int(WTERMSIG(status));
1717 packet_put_char(WCOREDUMP(status));
1718 #else /* WCOREDUMP */
1720 #endif /* WCOREDUMP */
1721 packet_put_cstring("");
1722 packet_put_cstring("");
1725 /* Some weird exit cause. Just exit. */
1726 packet_disconnect("wait returned status %04x.", status);
1729 /* disconnect channel */
1730 debug("session_exit_message: release channel %d", s->chanid);
1731 channel_cancel_cleanup(s->chanid);
1733 * emulate a write failure with 'chan_write_failed', nobody will be
1734 * interested in data we write.
1735 * Note that we must not call 'chan_read_failed', since there could
1736 * be some more data waiting in the pipe.
1738 if (c->ostate != CHAN_OUTPUT_CLOSED)
1739 chan_write_failed(c);
1744 session_free(Session *s)
1746 debug("session_free: session %d pid %d", s->self, s->pid);
1752 xfree(s->auth_data);
1754 xfree(s->auth_proto);
1759 session_close(Session *s)
1761 session_pty_cleanup(s);
1763 session_proctitle(s);
1767 session_close_by_pid(pid_t pid, int status)
1769 Session *s = session_by_pid(pid);
1771 debug("session_close_by_pid: no session for pid %d", s->pid);
1774 if (s->chanid != -1)
1775 session_exit_message(s, status);
1780 * this is called when a channel dies before
1781 * the session 'child' itself dies
1784 session_close_by_channel(int id, void *arg)
1786 Session *s = session_by_channel(id);
1788 debug("session_close_by_channel: no session for channel %d", id);
1791 /* disconnect channel */
1792 channel_cancel_cleanup(s->chanid);
1795 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1797 /* close session immediately */
1800 /* notify child, delay session cleanup */
1802 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1803 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1804 error("session_close_by_channel: kill %d: %s",
1805 s->pid, strerror(errno));
1810 session_tty_list(void)
1812 static char buf[1024];
1815 for(i = 0; i < MAX_SESSIONS; i++) {
1816 Session *s = &sessions[i];
1817 if (s->used && s->ttyfd != -1) {
1819 strlcat(buf, ",", sizeof buf);
1820 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1824 strlcpy(buf, "notty", sizeof buf);
1829 session_proctitle(Session *s)
1832 error("no user for session %d", s->self);
1834 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1838 do_authenticated2(void)
1843 * Cancel the alarm we set to limit the time taken for
1847 if (startup_pipe != -1) {
1848 close(startup_pipe);
1851 #ifdef HAVE_LOGIN_CAP
1852 pw = auth_get_user();
1853 if ((lc = login_getclass(pw->pw_class)) == NULL) {
1854 error("unable to get login class");
1860 xauthfile_cleanup_proc(NULL);