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.6 2000/04/27 15:23:02 markus Exp $");
33 typedef struct Session Session;
41 int ptyfd, ttyfd, ptymaster;
42 int row, col, xpixel, ypixel;
55 Session *session_new(void);
56 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
57 void session_pty_cleanup(Session *s);
58 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
59 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
62 do_child(const char *command, struct passwd * pw, const char *term,
63 const char *display, const char *auth_proto,
64 const char *auth_data, const char *ttyname);
67 extern ServerOptions options;
68 #ifdef HAVE___PROGNAME
69 extern char *__progname;
70 #else /* HAVE___PROGNAME */
71 const char *__progname = "sshd";
72 #endif /* HAVE___PROGNAME */
74 extern int log_stderr;
75 extern int debug_flag;
77 /* Local Xauthority file. */
78 static char *xauthfile;
81 #define MAX_SESSIONS 10
82 Session sessions[MAX_SESSIONS];
84 /* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
85 int no_port_forwarding_flag = 0;
86 int no_agent_forwarding_flag = 0;
87 int no_x11_forwarding_flag = 0;
90 /* RSA authentication "command=" option. */
91 char *forced_command = NULL;
93 /* RSA authentication "environment=" options. */
94 struct envstring *custom_environment = NULL;
97 * Remove local Xauthority file.
100 xauthfile_cleanup_proc(void *ignore)
102 debug("xauthfile_cleanup_proc called");
104 if (xauthfile != NULL) {
107 p = strrchr(xauthfile, '/');
118 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
119 * dropped connection).
122 pty_cleanup_proc(void *session)
126 fatal("pty_cleanup_proc: no session");
127 debug("pty_cleanup_proc: %s", s->tty);
130 /* Record that the user has logged out. */
131 record_logout(s->pid, s->tty);
134 /* Release the pseudo-tty. */
139 * Prepares for an interactive session. This is called after the user has
140 * been successfully authenticated. During this message exchange, pseudo
141 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
142 * are requested, etc.
145 do_authenticated(struct passwd * pw)
149 int compression_level = 0, enable_compression_after_reply = 0;
154 unsigned int proto_len, data_len, dlen;
157 * Cancel the alarm we set to limit the time taken for
163 * Inform the channel mechanism that we are the server side and that
164 * the client may request to connect to any port at all. (The user
165 * could do it anyway, and we wouldn\'t know what is permitted except
166 * by the client telling us, so we can equally well trust the client
167 * not to request anything bogus.)
169 if (!no_port_forwarding_flag)
170 channel_permit_all_opens();
175 * We stay in this loop until the client requests to execute a shell
181 /* Get a packet from the client. */
182 type = packet_read(&plen);
184 /* Process the packet. */
186 case SSH_CMSG_REQUEST_COMPRESSION:
187 packet_integrity_check(plen, 4, type);
188 compression_level = packet_get_int();
189 if (compression_level < 1 || compression_level > 9) {
190 packet_send_debug("Received illegal compression level %d.",
194 /* Enable compression after we have responded with SUCCESS. */
195 enable_compression_after_reply = 1;
199 case SSH_CMSG_REQUEST_PTY:
201 debug("Allocating a pty not permitted for this authentication.");
205 packet_disconnect("Protocol error: you already have a pty.");
207 debug("Allocating pty.");
209 /* Allocate a pty and open it. */
210 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
212 error("Failed to allocate pty.");
215 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
216 pty_setowner(pw, s->tty);
218 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
219 s->term = packet_get_string(&dlen);
220 packet_integrity_check(dlen, strlen(s->term), type);
221 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
222 /* Remaining bytes */
223 n_bytes = plen - (4 + dlen + 4 * 4);
225 if (strcmp(s->term, "") == 0) {
229 /* Get window size from the packet. */
230 s->row = packet_get_int();
231 s->col = packet_get_int();
232 s->xpixel = packet_get_int();
233 s->ypixel = packet_get_int();
234 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
236 /* Get tty modes from the packet. */
237 tty_parse_modes(s->ttyfd, &n_bytes);
238 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
240 /* Indicate that we now have a pty. */
245 case SSH_CMSG_X11_REQUEST_FORWARDING:
246 if (!options.x11_forwarding) {
247 packet_send_debug("X11 forwarding disabled in server configuration file.");
251 if (no_x11_forwarding_flag) {
252 packet_send_debug("X11 forwarding not permitted for this authentication.");
255 debug("Received request for X11 forwarding with auth spoofing.");
256 if (s->display != NULL)
257 packet_disconnect("Protocol error: X11 display already set.");
259 s->auth_proto = packet_get_string(&proto_len);
260 s->auth_data = packet_get_string(&data_len);
261 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
263 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
264 s->screen = packet_get_int();
267 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
269 if (s->display == NULL)
272 /* Setup to always have a local .Xauthority. */
273 xauthfile = xmalloc(MAXPATHLEN);
274 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
275 temporarily_use_uid(pw->pw_uid);
276 if (mkdtemp(xauthfile) == NULL) {
278 error("private X11 dir: mkdtemp %s failed: %s",
279 xauthfile, strerror(errno));
284 strlcat(xauthfile, "/cookies", MAXPATHLEN);
285 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
287 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
290 #else /* XAUTH_PATH */
291 packet_send_debug("No xauth program; cannot forward with spoofing.");
293 #endif /* XAUTH_PATH */
295 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
296 if (no_agent_forwarding_flag || compat13) {
297 debug("Authentication agent forwarding not permitted for this authentication.");
300 debug("Received authentication agent forwarding request.");
301 auth_input_request_forwarding(pw);
305 case SSH_CMSG_PORT_FORWARD_REQUEST:
306 if (no_port_forwarding_flag) {
307 debug("Port forwarding not permitted for this authentication.");
310 debug("Received TCP/IP port forwarding request.");
311 channel_input_port_forward_request(pw->pw_uid == 0);
315 case SSH_CMSG_MAX_PACKET_SIZE:
316 if (packet_set_maxsize(packet_get_int()) > 0)
320 case SSH_CMSG_EXEC_SHELL:
321 case SSH_CMSG_EXEC_CMD:
322 /* Set interactive/non-interactive mode. */
323 packet_set_interactive(have_pty || s->display != NULL,
326 if (type == SSH_CMSG_EXEC_CMD) {
327 command = packet_get_string(&dlen);
328 debug("Exec command '%.500s'", command);
329 packet_integrity_check(plen, 4 + dlen, type);
332 packet_integrity_check(plen, 0, type);
334 if (forced_command != NULL) {
335 command = forced_command;
336 debug("Forced command '%.500s'", forced_command);
339 do_exec_pty(s, command, pw);
341 do_exec_no_pty(s, command, pw);
345 /* Cleanup user's local Xauthority file. */
347 xauthfile_cleanup_proc(NULL);
352 * Any unknown messages in this phase are ignored,
353 * and a failure message is returned.
355 log("Unknown packet type received after authentication: %d", type);
357 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
361 /* Enable compression now that we have replied if appropriate. */
362 if (enable_compression_after_reply) {
363 enable_compression_after_reply = 0;
364 packet_start_compression(compression_level);
370 * This is called to fork and execute a command when we have no tty. This
371 * will call do_child from the child, and server_loop from the parent after
372 * setting up file descriptors and such.
375 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
380 int pin[2], pout[2], perr[2];
381 /* Allocate pipes for communicating with the program. */
382 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
383 packet_disconnect("Could not create pipes: %.100s",
385 #else /* USE_PIPES */
386 int inout[2], err[2];
387 /* Uses socket pairs to communicate with the program. */
388 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
389 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
390 packet_disconnect("Could not create socket pairs: %.100s",
392 #endif /* USE_PIPES */
394 fatal("do_exec_no_pty: no session");
396 setproctitle("%s@notty", pw->pw_name);
402 /* Fork the child. */
403 if ((pid = fork()) == 0) {
404 /* Child. Reinitialize the log since the pid has changed. */
405 log_init(__progname, options.log_level, options.log_facility, log_stderr);
408 * Create a new session and process group since the 4.4BSD
409 * setlogin() affects the entire process group.
412 error("setsid failed: %.100s", strerror(errno));
416 * Redirect stdin. We close the parent side of the socket
417 * pair, and make the child side the standard input.
420 if (dup2(pin[0], 0) < 0)
421 perror("dup2 stdin");
424 /* Redirect stdout. */
426 if (dup2(pout[1], 1) < 0)
427 perror("dup2 stdout");
430 /* Redirect stderr. */
432 if (dup2(perr[1], 2) < 0)
433 perror("dup2 stderr");
435 #else /* USE_PIPES */
437 * Redirect stdin, stdout, and stderr. Stdin and stdout will
438 * use the same socket, as some programs (particularly rdist)
439 * seem to depend on it.
443 if (dup2(inout[0], 0) < 0) /* stdin */
444 perror("dup2 stdin");
445 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
446 perror("dup2 stdout");
447 if (dup2(err[0], 2) < 0) /* stderr */
448 perror("dup2 stderr");
449 #endif /* USE_PIPES */
451 /* Do processing for the child (exec command etc). */
452 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
456 packet_disconnect("fork failed: %.100s", strerror(errno));
459 /* We are the parent. Close the child sides of the pipes. */
465 session_set_fds(s, pin[1], pout[0], perr[0]);
467 /* Enter the interactive session. */
468 server_loop(pid, pin[1], pout[0], perr[0]);
469 /* server_loop has closed pin[1], pout[1], and perr[1]. */
471 #else /* USE_PIPES */
472 /* We are the parent. Close the child sides of the socket pairs. */
477 * Enter the interactive session. Note: server_loop must be able to
478 * handle the case that fdin and fdout are the same.
481 session_set_fds(s, inout[1], inout[1], err[1]);
483 server_loop(pid, inout[1], inout[1], err[1]);
484 /* server_loop has closed inout[1] and err[1]. */
486 #endif /* USE_PIPES */
490 * This is called to fork and execute a command when we have a tty. This
491 * will call do_child from the child, and server_loop from the parent after
492 * setting up file descriptors, controlling tty, updating wtmp, utmp,
493 * lastlog, and other such operations.
496 do_exec_pty(Session *s, const char *command, struct passwd * pw)
499 char buf[100], *time_string;
501 const char *hostname;
502 int fdout, ptyfd, ttyfd, ptymaster;
506 struct sockaddr_storage from;
508 time_t last_login_time;
511 fatal("do_exec_pty: no session");
515 /* Get remote host name. */
516 hostname = get_canonical_hostname();
519 * Get the time when the user last logged in. Buf will be set to
520 * contain the hostname the last login was from.
522 if (!options.use_login) {
523 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
526 setproctitle("%s@%s", pw->pw_name, strrchr(s->tty, '/') + 1);
529 do_pam_session(pw->pw_name, s->tty);
533 /* Fork the child. */
534 if ((pid = fork()) == 0) {
537 /* Child. Reinitialize the log because the pid has
539 log_init(__progname, options.log_level, options.log_facility, log_stderr);
541 /* Close the master side of the pseudo tty. */
544 /* Make the pseudo tty our controlling tty. */
545 pty_make_controlling_tty(&ttyfd, s->tty);
547 /* Redirect stdin from the pseudo tty. */
548 if (dup2(ttyfd, fileno(stdin)) < 0)
549 error("dup2 stdin failed: %.100s", strerror(errno));
551 /* Redirect stdout to the pseudo tty. */
552 if (dup2(ttyfd, fileno(stdout)) < 0)
553 error("dup2 stdin failed: %.100s", strerror(errno));
555 /* Redirect stderr to the pseudo tty. */
556 if (dup2(ttyfd, fileno(stderr)) < 0)
557 error("dup2 stdin failed: %.100s", strerror(errno));
559 /* Close the extra descriptor for the pseudo tty. */
562 ///XXXX ? move to do_child() ??
564 * Get IP address of client. This is needed because we want
565 * to record where the user logged in from. If the
566 * connection is not a socket, let the ip address be 0.0.0.0.
568 memset(&from, 0, sizeof(from));
569 if (packet_connection_is_on_socket()) {
570 fromlen = sizeof(from);
571 if (getpeername(packet_get_connection_in(),
572 (struct sockaddr *) & from, &fromlen) < 0) {
573 debug("getpeername: %.100s", strerror(errno));
577 /* Record that there was a login on that terminal. */
578 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
579 (struct sockaddr *)&from);
581 /* Check if .hushlogin exists. */
582 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
583 quiet_login = stat(line, &st) >= 0;
587 print_pam_messages();
591 * If the user has logged in before, display the time of last
592 * login. However, don't display anything extra if a command
593 * has been specified (so that ssh can be used to execute
594 * commands on a remote machine without users knowing they
595 * are going to another machine). Login(1) will do this for
596 * us as well, so check if login(1) is used
598 if (command == NULL && last_login_time != 0 && !quiet_login &&
599 !options.use_login) {
600 /* Convert the date to a string. */
601 time_string = ctime(&last_login_time);
602 /* Remove the trailing newline. */
603 if (strchr(time_string, '\n'))
604 *strchr(time_string, '\n') = 0;
605 /* Display the last login time. Host if displayed
607 if (strcmp(buf, "") == 0)
608 printf("Last login: %s\r\n", time_string);
610 printf("Last login: %s from %s\r\n", time_string, buf);
613 * Print /etc/motd unless a command was specified or printing
614 * it was disabled in server options or login(1) will be
615 * used. Note that some machines appear to print it in
616 * /etc/profile or similar.
618 if (command == NULL && options.print_motd && !quiet_login &&
619 !options.use_login) {
620 /* Print /etc/motd if it exists. */
621 f = fopen("/etc/motd", "r");
623 while (fgets(line, sizeof(line), f))
628 /* Do common processing for the child, such as execing the command. */
629 do_child(command, pw, s->term, s->display, s->auth_proto, s->auth_data, s->tty);
633 packet_disconnect("fork failed: %.100s", strerror(errno));
636 /* Parent. Close the slave side of the pseudo tty. */
640 * Create another descriptor of the pty master side for use as the
641 * standard input. We could use the original descriptor, but this
642 * simplifies code in server_loop. The descriptor is bidirectional.
646 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
648 /* we keep a reference to the pty master */
649 ptymaster = dup(ptyfd);
651 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
652 s->ptymaster = ptymaster;
654 /* Enter interactive session. */
656 session_set_fds(s, ptyfd, fdout, -1);
658 server_loop(pid, ptyfd, fdout, -1);
659 /* server_loop _has_ closed ptyfd and fdout. */
660 session_pty_cleanup(s);
665 * Sets the value of the given variable in the environment. If the variable
666 * already exists, its value is overriden.
669 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
672 unsigned int i, namelen;
676 * Find the slot where the value should be stored. If the variable
677 * already exists, we reuse the slot; otherwise we append a new slot
678 * at the end of the array, expanding if necessary.
681 namelen = strlen(name);
682 for (i = 0; env[i]; i++)
683 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
686 /* Reuse the slot. */
689 /* New variable. Expand if necessary. */
690 if (i >= (*envsizep) - 1) {
692 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
694 /* Need to set the NULL pointer at end of array beyond the new slot. */
698 /* Allocate space and format the variable in the appropriate slot. */
699 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
700 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
704 * Reads environment variables from the given file and adds/overrides them
705 * into the environment. If the file does not exist, this does nothing.
706 * Otherwise, it must consist of empty lines, comments (line starts with '#')
707 * and assignments of the form name=value. No other forms are allowed.
710 read_environment_file(char ***env, unsigned int *envsize,
711 const char *filename)
717 f = fopen(filename, "r");
721 while (fgets(buf, sizeof(buf), f)) {
722 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
724 if (!*cp || *cp == '#' || *cp == '\n')
726 if (strchr(cp, '\n'))
727 *strchr(cp, '\n') = '\0';
728 value = strchr(cp, '=');
730 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
733 /* Replace the equals sign by nul, and advance value to the value string. */
736 child_set_env(env, envsize, cp, value);
743 * Sets any environment variables which have been specified by PAM
745 void do_pam_environment(char ***env, int *envsize)
747 char *equals, var_name[512], var_val[512];
751 if ((pam_env = fetch_pam_environment()) == NULL)
754 for(i = 0; pam_env[i] != NULL; i++) {
755 if ((equals = strstr(pam_env[i], "=")) == NULL)
758 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
759 memset(var_name, '\0', sizeof(var_name));
760 memset(var_val, '\0', sizeof(var_val));
762 strncpy(var_name, pam_env[i], equals - pam_env[i]);
763 strcpy(var_val, equals + 1);
765 debug("PAM environment: %s=%s", var_name, var_val);
767 child_set_env(env, envsize, var_name, var_val);
774 * Performs common processing for the child, such as setting up the
775 * environment, closing extra file descriptors, setting the user and group
776 * ids, and executing the command or shell.
779 do_child(const char *command, struct passwd * pw, const char *term,
780 const char *display, const char *auth_proto,
781 const char *auth_data, const char *ttyname)
783 const char *shell, *cp = NULL;
786 unsigned int envsize, i;
788 extern char **environ;
792 #ifndef USE_PAM /* pam_nologin handles this */
793 f = fopen("/etc/nologin", "r");
795 /* /etc/nologin exists. Print its contents and exit. */
796 while (fgets(buf, sizeof(buf), f))
804 /* Set login name in the kernel. */
805 if (setlogin(pw->pw_name) < 0)
806 error("setlogin failed: %s", strerror(errno));
808 /* Set uid, gid, and groups. */
809 /* Login(1) does this as well, and it needs uid 0 for the "-h"
810 switch, so we let login(1) to this for us. */
811 if (!options.use_login) {
812 if (getuid() == 0 || geteuid() == 0) {
813 if (setgid(pw->pw_gid) < 0) {
817 /* Initialize the group list. */
818 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
819 perror("initgroups");
824 /* Permanently switch to the desired uid. */
825 permanently_set_uid(pw->pw_uid);
827 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
828 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
831 * Get the shell from the password data. An empty shell field is
832 * legal, and means /bin/sh.
834 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
837 /* Try to get AFS tokens for the local cell. */
841 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
848 /* Initialize the environment. */
850 env = xmalloc(envsize * sizeof(char *));
853 if (!options.use_login) {
854 /* Set basic environment. */
855 child_set_env(&env, &envsize, "USER", pw->pw_name);
856 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
857 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
858 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
860 snprintf(buf, sizeof buf, "%.200s/%.50s",
861 _PATH_MAILDIR, pw->pw_name);
862 child_set_env(&env, &envsize, "MAIL", buf);
864 /* Normal systems set SHELL by default. */
865 child_set_env(&env, &envsize, "SHELL", shell);
868 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
870 /* Set custom environment options from RSA authentication. */
871 while (custom_environment) {
872 struct envstring *ce = custom_environment;
875 for (i = 0; s[i] != '=' && s[i]; i++);
878 child_set_env(&env, &envsize, s, s + i + 1);
880 custom_environment = ce->next;
885 snprintf(buf, sizeof buf, "%.50s %d %d",
886 get_remote_ipaddr(), get_remote_port(), get_local_port());
887 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
890 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
892 child_set_env(&env, &envsize, "TERM", term);
894 child_set_env(&env, &envsize, "DISPLAY", display);
898 char *authstate,*krb5cc;
900 if ((authstate = getenv("AUTHSTATE")) != NULL)
901 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
903 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
904 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
913 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
918 /* Pull in any environment variables that may have been set by PAM. */
919 do_pam_environment(&env, &envsize);
922 read_environment_file(&env,&envsize,"/etc/environment");
925 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
926 if (auth_get_socket_name() != NULL)
927 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
928 auth_get_socket_name());
930 /* read $HOME/.ssh/environment. */
931 if (!options.use_login) {
932 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
933 read_environment_file(&env, &envsize, buf);
936 /* dump the environment */
937 fprintf(stderr, "Environment:\n");
938 for (i = 0; env[i]; i++)
939 fprintf(stderr, " %.200s\n", env[i]);
942 * Close the connection descriptors; note that this is the child, and
943 * the server will still have the socket open, and it is important
944 * that we do not shutdown it. Note that the descriptors cannot be
945 * closed before building the environment, as we call
946 * get_remote_ipaddr there.
948 if (packet_get_connection_in() == packet_get_connection_out())
949 close(packet_get_connection_in());
951 close(packet_get_connection_in());
952 close(packet_get_connection_out());
955 * Close all descriptors related to channels. They will still remain
956 * open in the parent.
958 /* XXX better use close-on-exec? -markus */
962 * Close any extra file descriptors. Note that there may still be
963 * descriptors left by system functions. They will be closed later.
968 * Close any extra open file descriptors so that we don\'t have them
969 * hanging around in clients. Note that we want to do this after
970 * initgroups, because at least on Solaris 2.3 it leaves file
973 for (i = 3; i < 64; i++)
976 /* Change current directory to the user\'s home directory. */
977 if (chdir(pw->pw_dir) < 0)
978 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
979 pw->pw_dir, strerror(errno));
982 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
983 * xauth are run in the proper environment.
988 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
991 if (!options.use_login) {
992 if (stat(SSH_USER_RC, &st) >= 0) {
994 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
996 f = popen("/bin/sh " SSH_USER_RC, "w");
998 if (auth_proto != NULL && auth_data != NULL)
999 fprintf(f, "%s %s\n", auth_proto, auth_data);
1002 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1003 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1005 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1007 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1009 if (auth_proto != NULL && auth_data != NULL)
1010 fprintf(f, "%s %s\n", auth_proto, auth_data);
1013 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1017 /* Add authority data to .Xauthority if appropriate. */
1018 if (auth_proto != NULL && auth_data != NULL) {
1020 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
1021 XAUTH_PATH, display, auth_proto, auth_data);
1023 f = popen(XAUTH_PATH " -q -", "w");
1025 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
1028 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
1031 #endif /* XAUTH_PATH */
1033 /* Get the last component of the shell name. */
1034 cp = strrchr(shell, '/');
1041 * If we have no command, execute the shell. In this case, the shell
1042 * name to be passed in argv[0] is preceded by '-' to indicate that
1043 * this is a login shell.
1046 if (!options.use_login) {
1050 * Check for mail if we have a tty and it was enabled
1051 * in server options.
1053 if (ttyname && options.check_mail) {
1055 struct stat mailstat;
1056 mailbox = getenv("MAIL");
1057 if (mailbox != NULL) {
1058 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
1059 printf("No mail.\n");
1060 else if (mailstat.st_mtime < mailstat.st_atime)
1061 printf("You have mail.\n");
1063 printf("You have new mail.\n");
1066 /* Start the shell. Set initial character to '-'. */
1068 strncpy(buf + 1, cp, sizeof(buf) - 1);
1069 buf[sizeof(buf) - 1] = 0;
1071 /* Execute the shell. */
1074 execve(shell, argv, env);
1076 /* Executing the shell failed. */
1081 /* Launch login(1). */
1083 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1084 "-p", "-f", "--", pw->pw_name, NULL);
1086 /* Login couldn't be executed, die. */
1093 * Execute the command using the user's shell. This uses the -c
1094 * option to execute the command.
1096 argv[0] = (char *) cp;
1098 argv[2] = (char *) command;
1100 execve(shell, argv, env);
1109 static int did_init = 0;
1111 debug("session_new: init");
1112 for(i = 0; i < MAX_SESSIONS; i++) {
1113 sessions[i].used = 0;
1114 sessions[i].self = i;
1118 for(i = 0; i < MAX_SESSIONS; i++) {
1119 Session *s = &sessions[i];
1129 s->auth_data = NULL;
1130 s->auth_proto = NULL;
1132 debug("session_new: session %d", i);
1143 for(i = 0; i < MAX_SESSIONS; i++) {
1144 Session *s = &sessions[i];
1145 debug("dump: used %d session %d %p channel %d pid %d",
1155 session_open(int chanid)
1157 Session *s = session_new();
1158 debug("session_open: channel %d", chanid);
1160 error("no more sessions");
1163 debug("session_open: session %d: link with channel %d", s->self, chanid);
1165 s->pw = auth_get_user();
1167 fatal("no user for session %i channel %d",
1168 s->self, s->chanid);
1173 session_by_channel(int id)
1176 for(i = 0; i < MAX_SESSIONS; i++) {
1177 Session *s = &sessions[i];
1178 if (s->used && s->chanid == id) {
1179 debug("session_by_channel: session %d channel %d", i, id);
1183 debug("session_by_channel: unknown channel %d", id);
1189 session_by_pid(pid_t pid)
1192 debug("session_by_pid: pid %d", pid);
1193 for(i = 0; i < MAX_SESSIONS; i++) {
1194 Session *s = &sessions[i];
1195 if (s->used && s->pid == pid)
1198 error("session_by_pid: unknown pid %d", pid);
1204 session_window_change_req(Session *s)
1206 s->col = packet_get_int();
1207 s->row = packet_get_int();
1208 s->xpixel = packet_get_int();
1209 s->ypixel = packet_get_int();
1211 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1216 session_pty_req(Session *s)
1219 char *term_modes; /* encoded terminal modes */
1223 s->term = packet_get_string(&len);
1224 s->col = packet_get_int();
1225 s->row = packet_get_int();
1226 s->xpixel = packet_get_int();
1227 s->ypixel = packet_get_int();
1228 term_modes = packet_get_string(&len);
1231 if (strcmp(s->term, "") == 0) {
1235 /* Allocate a pty and open it. */
1236 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1241 error("session_pty_req: session %d alloc failed", s->self);
1245 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1247 * Add a cleanup function to clear the utmp entry and record logout
1248 * time in case we call fatal() (e.g., the connection gets closed).
1250 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1251 pty_setowner(s->pw, s->tty);
1252 /* Get window size from the packet. */
1253 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1255 /* XXX parse and set terminal modes */
1261 session_input_channel_req(int id, void *arg)
1270 rtype = packet_get_string(&len);
1271 reply = packet_get_char();
1273 s = session_by_channel(id);
1275 fatal("session_input_channel_req: channel %d: no session", id);
1276 c = channel_lookup(id);
1278 fatal("session_input_channel_req: channel %d: bad channel", id);
1280 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1281 s->self, id, rtype, reply);
1284 * a session is in LARVAL state until a shell
1285 * or programm is executed
1287 if (c->type == SSH_CHANNEL_LARVAL) {
1288 if (strcmp(rtype, "shell") == 0) {
1290 do_exec_no_pty(s, NULL, s->pw);
1292 do_exec_pty(s, NULL, s->pw);
1294 } else if (strcmp(rtype, "exec") == 0) {
1295 char *command = packet_get_string(&len);
1298 do_exec_no_pty(s, command, s->pw);
1300 do_exec_pty(s, command, s->pw);
1303 } else if (strcmp(rtype, "pty-req") == 0) {
1304 success = session_pty_req(s);
1307 if (strcmp(rtype, "window-change") == 0) {
1308 success = session_window_change_req(s);
1312 packet_start(success ?
1313 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1314 packet_put_int(c->remote_id);
1321 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1324 fatal("session_set_fds: called for proto != 2.0");
1326 * now that have a child and a pipe to the child,
1327 * we can activate our channel and register the fd's
1329 if (s->chanid == -1)
1330 fatal("no channel for session %d", s->self);
1331 channel_set_fds(s->chanid,
1333 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1337 session_pty_cleanup(Session *s)
1339 if (s == NULL || s->ttyfd == -1)
1342 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1344 /* Cancel the cleanup function. */
1345 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1347 /* Record that the user has logged out. */
1348 record_logout(s->pid, s->tty);
1350 /* Release the pseudo-tty. */
1351 pty_release(s->tty);
1354 * Close the server side of the socket pairs. We must do this after
1355 * the pty cleanup, so that another process doesn't get this pty
1356 * while we're still cleaning up.
1358 if (close(s->ptymaster) < 0)
1359 error("close(s->ptymaster): %s", strerror(errno));
1363 session_exit_message(Session *s, int status)
1367 fatal("session_close: no session");
1368 c = channel_lookup(s->chanid);
1370 fatal("session_close: session %d: no channel %d",
1371 s->self, s->chanid);
1372 debug("session_exit_message: session %d channel %d pid %d",
1373 s->self, s->chanid, s->pid);
1375 if (WIFEXITED(status)) {
1376 channel_request_start(s->chanid,
1378 packet_put_int(WEXITSTATUS(status));
1380 } else if (WIFSIGNALED(status)) {
1381 channel_request_start(s->chanid,
1383 packet_put_int(WTERMSIG(status));
1384 packet_put_char(WCOREDUMP(status));
1385 packet_put_cstring("");
1386 packet_put_cstring("");
1389 /* Some weird exit cause. Just exit. */
1390 packet_disconnect("wait returned status %04x.", status);
1393 /* disconnect channel */
1394 debug("session_exit_message: release channel %d", s->chanid);
1395 channel_cancel_cleanup(s->chanid);
1397 * emulate a write failure with 'chan_write_failed', nobody will be
1398 * interested in data we write.
1399 * Note that we must not call 'chan_read_failed', since there could
1400 * be some more data waiting in the pipe.
1402 chan_write_failed(c);
1407 session_free(Session *s)
1409 debug("session_free: session %d pid %d", s->self, s->pid);
1415 xfree(s->auth_data);
1417 xfree(s->auth_proto);
1422 session_close(Session *s)
1424 session_pty_cleanup(s);
1429 session_close_by_pid(pid_t pid, int status)
1431 Session *s = session_by_pid(pid);
1433 debug("session_close_by_pid: no session for pid %d", s->pid);
1436 if (s->chanid != -1)
1437 session_exit_message(s, status);
1442 * this is called when a channel dies before
1443 * the session 'child' itself dies
1446 session_close_by_channel(int id, void *arg)
1448 Session *s = session_by_channel(id);
1450 debug("session_close_by_channel: no session for channel %d", id);
1453 /* disconnect channel */
1454 channel_cancel_cleanup(s->chanid);
1457 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1459 /* close session immediately */
1462 /* notify child, delay session cleanup */
1463 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1464 error("session_close_by_channel: kill %d: %s",
1465 s->pid, strerror(errno));
1470 do_authenticated2(void)
1473 * Cancel the alarm we set to limit the time taken for