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;
42 int ptyfd, ttyfd, ptymaster;
43 int row, col, xpixel, ypixel;
50 int single_connection;
57 Session *session_new(void);
58 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
59 void session_pty_cleanup(Session *s);
60 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
61 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
64 do_child(const char *command, struct passwd * pw, const char *term,
65 const char *display, const char *auth_proto,
66 const char *auth_data, const char *ttyname);
69 extern ServerOptions options;
70 #ifdef HAVE___PROGNAME
71 extern char *__progname;
72 #else /* HAVE___PROGNAME */
73 const char *__progname = "sshd";
74 #endif /* HAVE___PROGNAME */
76 extern int log_stderr;
77 extern int debug_flag;
79 /* Local Xauthority file. */
80 static char *xauthfile;
83 #define MAX_SESSIONS 10
84 Session sessions[MAX_SESSIONS];
86 /* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
87 int no_port_forwarding_flag = 0;
88 int no_agent_forwarding_flag = 0;
89 int no_x11_forwarding_flag = 0;
92 /* RSA authentication "command=" option. */
93 char *forced_command = NULL;
95 /* RSA authentication "environment=" options. */
96 struct envstring *custom_environment = NULL;
99 * Remove local Xauthority file.
102 xauthfile_cleanup_proc(void *ignore)
104 debug("xauthfile_cleanup_proc called");
106 if (xauthfile != NULL) {
109 p = strrchr(xauthfile, '/');
120 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
121 * dropped connection).
124 pty_cleanup_proc(void *session)
128 fatal("pty_cleanup_proc: no session");
129 debug("pty_cleanup_proc: %s", s->tty);
132 /* Record that the user has logged out. */
133 record_logout(s->pid, s->tty);
136 /* Release the pseudo-tty. */
141 * Prepares for an interactive session. This is called after the user has
142 * been successfully authenticated. During this message exchange, pseudo
143 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
144 * are requested, etc.
147 do_authenticated(struct passwd * pw)
151 int compression_level = 0, enable_compression_after_reply = 0;
156 unsigned int proto_len, data_len, dlen;
159 * Cancel the alarm we set to limit the time taken for
165 * Inform the channel mechanism that we are the server side and that
166 * the client may request to connect to any port at all. (The user
167 * could do it anyway, and we wouldn\'t know what is permitted except
168 * by the client telling us, so we can equally well trust the client
169 * not to request anything bogus.)
171 if (!no_port_forwarding_flag)
172 channel_permit_all_opens();
178 * We stay in this loop until the client requests to execute a shell
184 /* Get a packet from the client. */
185 type = packet_read(&plen);
187 /* Process the packet. */
189 case SSH_CMSG_REQUEST_COMPRESSION:
190 packet_integrity_check(plen, 4, type);
191 compression_level = packet_get_int();
192 if (compression_level < 1 || compression_level > 9) {
193 packet_send_debug("Received illegal compression level %d.",
197 /* Enable compression after we have responded with SUCCESS. */
198 enable_compression_after_reply = 1;
202 case SSH_CMSG_REQUEST_PTY:
204 debug("Allocating a pty not permitted for this authentication.");
208 packet_disconnect("Protocol error: you already have a pty.");
210 debug("Allocating pty.");
212 /* Allocate a pty and open it. */
213 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
215 error("Failed to allocate pty.");
218 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
219 pty_setowner(pw, s->tty);
221 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
222 s->term = packet_get_string(&dlen);
223 packet_integrity_check(dlen, strlen(s->term), type);
224 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
225 /* Remaining bytes */
226 n_bytes = plen - (4 + dlen + 4 * 4);
228 if (strcmp(s->term, "") == 0) {
232 /* Get window size from the packet. */
233 s->row = packet_get_int();
234 s->col = packet_get_int();
235 s->xpixel = packet_get_int();
236 s->ypixel = packet_get_int();
237 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
239 /* Get tty modes from the packet. */
240 tty_parse_modes(s->ttyfd, &n_bytes);
241 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
243 /* Indicate that we now have a pty. */
248 case SSH_CMSG_X11_REQUEST_FORWARDING:
249 if (!options.x11_forwarding) {
250 packet_send_debug("X11 forwarding disabled in server configuration file.");
254 if (no_x11_forwarding_flag) {
255 packet_send_debug("X11 forwarding not permitted for this authentication.");
258 debug("Received request for X11 forwarding with auth spoofing.");
259 if (s->display != NULL)
260 packet_disconnect("Protocol error: X11 display already set.");
262 s->auth_proto = packet_get_string(&proto_len);
263 s->auth_data = packet_get_string(&data_len);
264 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
266 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
267 s->screen = packet_get_int();
270 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
272 if (s->display == NULL)
275 /* Setup to always have a local .Xauthority. */
276 xauthfile = xmalloc(MAXPATHLEN);
277 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
278 temporarily_use_uid(pw->pw_uid);
279 if (mkdtemp(xauthfile) == NULL) {
281 error("private X11 dir: mkdtemp %s failed: %s",
282 xauthfile, strerror(errno));
285 /* XXXX remove listening channels */
288 strlcat(xauthfile, "/cookies", MAXPATHLEN);
289 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
291 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
294 #else /* XAUTH_PATH */
295 packet_send_debug("No xauth program; cannot forward with spoofing.");
297 #endif /* XAUTH_PATH */
299 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
300 if (no_agent_forwarding_flag || compat13) {
301 debug("Authentication agent forwarding not permitted for this authentication.");
304 debug("Received authentication agent forwarding request.");
305 auth_input_request_forwarding(pw);
309 case SSH_CMSG_PORT_FORWARD_REQUEST:
310 if (no_port_forwarding_flag) {
311 debug("Port forwarding not permitted for this authentication.");
314 debug("Received TCP/IP port forwarding request.");
315 channel_input_port_forward_request(pw->pw_uid == 0);
319 case SSH_CMSG_MAX_PACKET_SIZE:
320 if (packet_set_maxsize(packet_get_int()) > 0)
324 case SSH_CMSG_EXEC_SHELL:
325 case SSH_CMSG_EXEC_CMD:
326 /* Set interactive/non-interactive mode. */
327 packet_set_interactive(have_pty || s->display != NULL,
330 if (type == SSH_CMSG_EXEC_CMD) {
331 command = packet_get_string(&dlen);
332 debug("Exec command '%.500s'", command);
333 packet_integrity_check(plen, 4 + dlen, type);
336 packet_integrity_check(plen, 0, type);
338 if (forced_command != NULL) {
339 command = forced_command;
340 debug("Forced command '%.500s'", forced_command);
343 do_exec_pty(s, command, pw);
345 do_exec_no_pty(s, command, pw);
349 /* Cleanup user's local Xauthority file. */
351 xauthfile_cleanup_proc(NULL);
356 * Any unknown messages in this phase are ignored,
357 * and a failure message is returned.
359 log("Unknown packet type received after authentication: %d", type);
361 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
365 /* Enable compression now that we have replied if appropriate. */
366 if (enable_compression_after_reply) {
367 enable_compression_after_reply = 0;
368 packet_start_compression(compression_level);
374 * This is called to fork and execute a command when we have no tty. This
375 * will call do_child from the child, and server_loop from the parent after
376 * setting up file descriptors and such.
379 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
384 int pin[2], pout[2], perr[2];
385 /* Allocate pipes for communicating with the program. */
386 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
387 packet_disconnect("Could not create pipes: %.100s",
389 #else /* USE_PIPES */
390 int inout[2], err[2];
391 /* Uses socket pairs to communicate with the program. */
392 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
393 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
394 packet_disconnect("Could not create socket pairs: %.100s",
396 #endif /* USE_PIPES */
398 fatal("do_exec_no_pty: no session");
400 setproctitle("%s@notty", pw->pw_name);
406 /* Fork the child. */
407 if ((pid = fork()) == 0) {
408 /* Child. Reinitialize the log since the pid has changed. */
409 log_init(__progname, options.log_level, options.log_facility, log_stderr);
412 * Create a new session and process group since the 4.4BSD
413 * setlogin() affects the entire process group.
416 error("setsid failed: %.100s", strerror(errno));
420 * Redirect stdin. We close the parent side of the socket
421 * pair, and make the child side the standard input.
424 if (dup2(pin[0], 0) < 0)
425 perror("dup2 stdin");
428 /* Redirect stdout. */
430 if (dup2(pout[1], 1) < 0)
431 perror("dup2 stdout");
434 /* Redirect stderr. */
436 if (dup2(perr[1], 2) < 0)
437 perror("dup2 stderr");
439 #else /* USE_PIPES */
441 * Redirect stdin, stdout, and stderr. Stdin and stdout will
442 * use the same socket, as some programs (particularly rdist)
443 * seem to depend on it.
447 if (dup2(inout[0], 0) < 0) /* stdin */
448 perror("dup2 stdin");
449 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
450 perror("dup2 stdout");
451 if (dup2(err[0], 2) < 0) /* stderr */
452 perror("dup2 stderr");
453 #endif /* USE_PIPES */
455 /* Do processing for the child (exec command etc). */
456 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
460 packet_disconnect("fork failed: %.100s", strerror(errno));
463 /* We are the parent. Close the child sides of the pipes. */
469 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
471 /* Enter the interactive session. */
472 server_loop(pid, pin[1], pout[0], perr[0]);
473 /* server_loop has closed pin[1], pout[1], and perr[1]. */
475 #else /* USE_PIPES */
476 /* We are the parent. Close the child sides of the socket pairs. */
481 * Enter the interactive session. Note: server_loop must be able to
482 * handle the case that fdin and fdout are the same.
485 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
487 server_loop(pid, inout[1], inout[1], err[1]);
488 /* server_loop has closed inout[1] and err[1]. */
490 #endif /* USE_PIPES */
494 * This is called to fork and execute a command when we have a tty. This
495 * will call do_child from the child, and server_loop from the parent after
496 * setting up file descriptors, controlling tty, updating wtmp, utmp,
497 * lastlog, and other such operations.
500 do_exec_pty(Session *s, const char *command, struct passwd * pw)
503 char buf[100], *time_string;
505 const char *hostname;
506 int fdout, ptyfd, ttyfd, ptymaster;
510 struct sockaddr_storage from;
512 time_t last_login_time;
515 fatal("do_exec_pty: no session");
519 /* Get remote host name. */
520 hostname = get_canonical_hostname();
523 * Get the time when the user last logged in. Buf will be set to
524 * contain the hostname the last login was from.
526 if (!options.use_login) {
527 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
530 setproctitle("%s@%s", pw->pw_name, strrchr(s->tty, '/') + 1);
533 do_pam_session(pw->pw_name, s->tty);
537 /* Fork the child. */
538 if ((pid = fork()) == 0) {
541 /* Child. Reinitialize the log because the pid has
543 log_init(__progname, options.log_level, options.log_facility, log_stderr);
545 /* Close the master side of the pseudo tty. */
548 /* Make the pseudo tty our controlling tty. */
549 pty_make_controlling_tty(&ttyfd, s->tty);
551 /* Redirect stdin from the pseudo tty. */
552 if (dup2(ttyfd, fileno(stdin)) < 0)
553 error("dup2 stdin failed: %.100s", strerror(errno));
555 /* Redirect stdout to the pseudo tty. */
556 if (dup2(ttyfd, fileno(stdout)) < 0)
557 error("dup2 stdin failed: %.100s", strerror(errno));
559 /* Redirect stderr to the pseudo tty. */
560 if (dup2(ttyfd, fileno(stderr)) < 0)
561 error("dup2 stdin failed: %.100s", strerror(errno));
563 /* Close the extra descriptor for the pseudo tty. */
566 ///XXXX ? move to do_child() ??
568 * Get IP address of client. This is needed because we want
569 * to record where the user logged in from. If the
570 * connection is not a socket, let the ip address be 0.0.0.0.
572 memset(&from, 0, sizeof(from));
573 if (packet_connection_is_on_socket()) {
574 fromlen = sizeof(from);
575 if (getpeername(packet_get_connection_in(),
576 (struct sockaddr *) & from, &fromlen) < 0) {
577 debug("getpeername: %.100s", strerror(errno));
581 /* Record that there was a login on that terminal. */
582 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
583 (struct sockaddr *)&from);
585 /* Check if .hushlogin exists. */
586 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
587 quiet_login = stat(line, &st) >= 0;
591 print_pam_messages();
595 * If the user has logged in before, display the time of last
596 * login. However, don't display anything extra if a command
597 * has been specified (so that ssh can be used to execute
598 * commands on a remote machine without users knowing they
599 * are going to another machine). Login(1) will do this for
600 * us as well, so check if login(1) is used
602 if (command == NULL && last_login_time != 0 && !quiet_login &&
603 !options.use_login) {
604 /* Convert the date to a string. */
605 time_string = ctime(&last_login_time);
606 /* Remove the trailing newline. */
607 if (strchr(time_string, '\n'))
608 *strchr(time_string, '\n') = 0;
609 /* Display the last login time. Host if displayed
611 if (strcmp(buf, "") == 0)
612 printf("Last login: %s\r\n", time_string);
614 printf("Last login: %s from %s\r\n", time_string, buf);
617 * Print /etc/motd unless a command was specified or printing
618 * it was disabled in server options or login(1) will be
619 * used. Note that some machines appear to print it in
620 * /etc/profile or similar.
622 if (command == NULL && options.print_motd && !quiet_login &&
623 !options.use_login) {
624 /* Print /etc/motd if it exists. */
625 f = fopen("/etc/motd", "r");
627 while (fgets(line, sizeof(line), f))
632 /* Do common processing for the child, such as execing the command. */
633 do_child(command, pw, s->term, s->display, s->auth_proto, s->auth_data, s->tty);
637 packet_disconnect("fork failed: %.100s", strerror(errno));
640 /* Parent. Close the slave side of the pseudo tty. */
644 * Create another descriptor of the pty master side for use as the
645 * standard input. We could use the original descriptor, but this
646 * simplifies code in server_loop. The descriptor is bidirectional.
650 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
652 /* we keep a reference to the pty master */
653 ptymaster = dup(ptyfd);
655 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
656 s->ptymaster = ptymaster;
658 /* Enter interactive session. */
660 session_set_fds(s, ptyfd, fdout, -1);
662 server_loop(pid, ptyfd, fdout, -1);
663 /* server_loop _has_ closed ptyfd and fdout. */
664 session_pty_cleanup(s);
669 * Sets the value of the given variable in the environment. If the variable
670 * already exists, its value is overriden.
673 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
676 unsigned int i, namelen;
680 * Find the slot where the value should be stored. If the variable
681 * already exists, we reuse the slot; otherwise we append a new slot
682 * at the end of the array, expanding if necessary.
685 namelen = strlen(name);
686 for (i = 0; env[i]; i++)
687 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
690 /* Reuse the slot. */
693 /* New variable. Expand if necessary. */
694 if (i >= (*envsizep) - 1) {
696 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
698 /* Need to set the NULL pointer at end of array beyond the new slot. */
702 /* Allocate space and format the variable in the appropriate slot. */
703 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
704 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
708 * Reads environment variables from the given file and adds/overrides them
709 * into the environment. If the file does not exist, this does nothing.
710 * Otherwise, it must consist of empty lines, comments (line starts with '#')
711 * and assignments of the form name=value. No other forms are allowed.
714 read_environment_file(char ***env, unsigned int *envsize,
715 const char *filename)
721 f = fopen(filename, "r");
725 while (fgets(buf, sizeof(buf), f)) {
726 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
728 if (!*cp || *cp == '#' || *cp == '\n')
730 if (strchr(cp, '\n'))
731 *strchr(cp, '\n') = '\0';
732 value = strchr(cp, '=');
734 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
737 /* Replace the equals sign by nul, and advance value to the value string. */
740 child_set_env(env, envsize, cp, value);
747 * Sets any environment variables which have been specified by PAM
749 void do_pam_environment(char ***env, int *envsize)
751 char *equals, var_name[512], var_val[512];
755 if ((pam_env = fetch_pam_environment()) == NULL)
758 for(i = 0; pam_env[i] != NULL; i++) {
759 if ((equals = strstr(pam_env[i], "=")) == NULL)
762 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
763 memset(var_name, '\0', sizeof(var_name));
764 memset(var_val, '\0', sizeof(var_val));
766 strncpy(var_name, pam_env[i], equals - pam_env[i]);
767 strcpy(var_val, equals + 1);
769 debug("PAM environment: %s=%s", var_name, var_val);
771 child_set_env(env, envsize, var_name, var_val);
778 * Performs common processing for the child, such as setting up the
779 * environment, closing extra file descriptors, setting the user and group
780 * ids, and executing the command or shell.
783 do_child(const char *command, struct passwd * pw, const char *term,
784 const char *display, const char *auth_proto,
785 const char *auth_data, const char *ttyname)
787 const char *shell, *cp = NULL;
790 unsigned int envsize, i;
792 extern char **environ;
796 #ifndef USE_PAM /* pam_nologin handles this */
797 f = fopen("/etc/nologin", "r");
799 /* /etc/nologin exists. Print its contents and exit. */
800 while (fgets(buf, sizeof(buf), f))
808 /* Set login name in the kernel. */
809 if (setlogin(pw->pw_name) < 0)
810 error("setlogin failed: %s", strerror(errno));
812 /* Set uid, gid, and groups. */
813 /* Login(1) does this as well, and it needs uid 0 for the "-h"
814 switch, so we let login(1) to this for us. */
815 if (!options.use_login) {
816 if (getuid() == 0 || geteuid() == 0) {
817 if (setgid(pw->pw_gid) < 0) {
821 /* Initialize the group list. */
822 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
823 perror("initgroups");
828 /* Permanently switch to the desired uid. */
829 permanently_set_uid(pw->pw_uid);
831 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
832 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
835 * Get the shell from the password data. An empty shell field is
836 * legal, and means /bin/sh.
838 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
841 /* Try to get AFS tokens for the local cell. */
845 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
852 /* Initialize the environment. */
854 env = xmalloc(envsize * sizeof(char *));
857 if (!options.use_login) {
858 /* Set basic environment. */
859 child_set_env(&env, &envsize, "USER", pw->pw_name);
860 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
861 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
862 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
864 snprintf(buf, sizeof buf, "%.200s/%.50s",
865 _PATH_MAILDIR, pw->pw_name);
866 child_set_env(&env, &envsize, "MAIL", buf);
868 /* Normal systems set SHELL by default. */
869 child_set_env(&env, &envsize, "SHELL", shell);
872 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
874 /* Set custom environment options from RSA authentication. */
875 while (custom_environment) {
876 struct envstring *ce = custom_environment;
879 for (i = 0; s[i] != '=' && s[i]; i++);
882 child_set_env(&env, &envsize, s, s + i + 1);
884 custom_environment = ce->next;
889 snprintf(buf, sizeof buf, "%.50s %d %d",
890 get_remote_ipaddr(), get_remote_port(), get_local_port());
891 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
894 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
896 child_set_env(&env, &envsize, "TERM", term);
898 child_set_env(&env, &envsize, "DISPLAY", display);
902 char *authstate,*krb5cc;
904 if ((authstate = getenv("AUTHSTATE")) != NULL)
905 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
907 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
908 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
917 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
922 /* Pull in any environment variables that may have been set by PAM. */
923 do_pam_environment(&env, &envsize);
926 read_environment_file(&env,&envsize,"/etc/environment");
929 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
930 if (auth_get_socket_name() != NULL)
931 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
932 auth_get_socket_name());
934 /* read $HOME/.ssh/environment. */
935 if (!options.use_login) {
936 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
937 read_environment_file(&env, &envsize, buf);
940 /* dump the environment */
941 fprintf(stderr, "Environment:\n");
942 for (i = 0; env[i]; i++)
943 fprintf(stderr, " %.200s\n", env[i]);
946 * Close the connection descriptors; note that this is the child, and
947 * the server will still have the socket open, and it is important
948 * that we do not shutdown it. Note that the descriptors cannot be
949 * closed before building the environment, as we call
950 * get_remote_ipaddr there.
952 if (packet_get_connection_in() == packet_get_connection_out())
953 close(packet_get_connection_in());
955 close(packet_get_connection_in());
956 close(packet_get_connection_out());
959 * Close all descriptors related to channels. They will still remain
960 * open in the parent.
962 /* XXX better use close-on-exec? -markus */
966 * Close any extra file descriptors. Note that there may still be
967 * descriptors left by system functions. They will be closed later.
972 * Close any extra open file descriptors so that we don\'t have them
973 * hanging around in clients. Note that we want to do this after
974 * initgroups, because at least on Solaris 2.3 it leaves file
977 for (i = 3; i < 64; i++)
980 /* Change current directory to the user\'s home directory. */
981 if (chdir(pw->pw_dir) < 0)
982 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
983 pw->pw_dir, strerror(errno));
986 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
987 * xauth are run in the proper environment.
992 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
995 if (!options.use_login) {
996 if (stat(SSH_USER_RC, &st) >= 0) {
998 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
1000 f = popen("/bin/sh " SSH_USER_RC, "w");
1002 if (auth_proto != NULL && auth_data != NULL)
1003 fprintf(f, "%s %s\n", auth_proto, auth_data);
1006 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1007 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1009 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1011 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1013 if (auth_proto != NULL && auth_data != NULL)
1014 fprintf(f, "%s %s\n", auth_proto, auth_data);
1017 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1021 /* Add authority data to .Xauthority if appropriate. */
1022 if (auth_proto != NULL && auth_data != NULL) {
1024 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
1025 XAUTH_PATH, display, auth_proto, auth_data);
1027 f = popen(XAUTH_PATH " -q -", "w");
1029 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
1032 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
1035 #endif /* XAUTH_PATH */
1037 /* Get the last component of the shell name. */
1038 cp = strrchr(shell, '/');
1045 * If we have no command, execute the shell. In this case, the shell
1046 * name to be passed in argv[0] is preceded by '-' to indicate that
1047 * this is a login shell.
1050 if (!options.use_login) {
1054 * Check for mail if we have a tty and it was enabled
1055 * in server options.
1057 if (ttyname && options.check_mail) {
1059 struct stat mailstat;
1060 mailbox = getenv("MAIL");
1061 if (mailbox != NULL) {
1062 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
1063 printf("No mail.\n");
1064 else if (mailstat.st_mtime < mailstat.st_atime)
1065 printf("You have mail.\n");
1067 printf("You have new mail.\n");
1070 /* Start the shell. Set initial character to '-'. */
1072 strncpy(buf + 1, cp, sizeof(buf) - 1);
1073 buf[sizeof(buf) - 1] = 0;
1075 /* Execute the shell. */
1078 execve(shell, argv, env);
1080 /* Executing the shell failed. */
1085 /* Launch login(1). */
1087 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1088 "-p", "-f", "--", pw->pw_name, NULL);
1090 /* Login couldn't be executed, die. */
1097 * Execute the command using the user's shell. This uses the -c
1098 * option to execute the command.
1100 argv[0] = (char *) cp;
1102 argv[2] = (char *) command;
1104 execve(shell, argv, env);
1113 static int did_init = 0;
1115 debug("session_new: init");
1116 for(i = 0; i < MAX_SESSIONS; i++) {
1117 sessions[i].used = 0;
1118 sessions[i].self = i;
1122 for(i = 0; i < MAX_SESSIONS; i++) {
1123 Session *s = &sessions[i];
1134 s->auth_data = NULL;
1135 s->auth_proto = NULL;
1138 debug("session_new: session %d", i);
1149 for(i = 0; i < MAX_SESSIONS; i++) {
1150 Session *s = &sessions[i];
1151 debug("dump: used %d session %d %p channel %d pid %d",
1161 session_open(int chanid)
1163 Session *s = session_new();
1164 debug("session_open: channel %d", chanid);
1166 error("no more sessions");
1169 s->pw = auth_get_user();
1171 fatal("no user for session %i", s->self);
1172 debug("session_open: session %d: link with channel %d", s->self, chanid);
1178 session_by_channel(int id)
1181 for(i = 0; i < MAX_SESSIONS; i++) {
1182 Session *s = &sessions[i];
1183 if (s->used && s->chanid == id) {
1184 debug("session_by_channel: session %d channel %d", i, id);
1188 debug("session_by_channel: unknown channel %d", id);
1194 session_by_pid(pid_t pid)
1197 debug("session_by_pid: pid %d", pid);
1198 for(i = 0; i < MAX_SESSIONS; i++) {
1199 Session *s = &sessions[i];
1200 if (s->used && s->pid == pid)
1203 error("session_by_pid: unknown pid %d", pid);
1209 session_window_change_req(Session *s)
1211 s->col = packet_get_int();
1212 s->row = packet_get_int();
1213 s->xpixel = packet_get_int();
1214 s->ypixel = packet_get_int();
1216 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1221 session_pty_req(Session *s)
1224 char *term_modes; /* encoded terminal modes */
1228 s->term = packet_get_string(&len);
1229 s->col = packet_get_int();
1230 s->row = packet_get_int();
1231 s->xpixel = packet_get_int();
1232 s->ypixel = packet_get_int();
1233 term_modes = packet_get_string(&len);
1236 if (strcmp(s->term, "") == 0) {
1240 /* Allocate a pty and open it. */
1241 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1246 error("session_pty_req: session %d alloc failed", s->self);
1250 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1252 * Add a cleanup function to clear the utmp entry and record logout
1253 * time in case we call fatal() (e.g., the connection gets closed).
1255 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1256 pty_setowner(s->pw, s->tty);
1257 /* Get window size from the packet. */
1258 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1260 /* XXX parse and set terminal modes */
1266 session_subsystem_req(Session *s)
1270 char *subsys = packet_get_string(&len);
1273 log("subsystem request for %s", subsys);
1280 session_x11_req(Session *s)
1282 if (!options.x11_forwarding) {
1283 debug("X11 forwarding disabled in server configuration file.");
1286 if (xauthfile != NULL) {
1287 debug("X11 fwd already started.");
1291 debug("Received request for X11 forwarding with auth spoofing.");
1292 if (s->display != NULL)
1293 packet_disconnect("Protocol error: X11 display already set.");
1295 s->single_connection = packet_get_char();
1296 s->auth_proto = packet_get_string(NULL);
1297 s->auth_data = packet_get_string(NULL);
1298 s->screen = packet_get_int();
1301 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1302 if (s->display == NULL) {
1303 xfree(s->auth_proto);
1304 xfree(s->auth_data);
1307 xauthfile = xmalloc(MAXPATHLEN);
1308 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1309 temporarily_use_uid(s->pw->pw_uid);
1310 if (mkdtemp(xauthfile) == NULL) {
1312 error("private X11 dir: mkdtemp %s failed: %s",
1313 xauthfile, strerror(errno));
1316 xfree(s->auth_proto);
1317 xfree(s->auth_data);
1318 /* XXXX remove listening channels */
1321 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1322 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1324 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1329 session_input_channel_req(int id, void *arg)
1338 rtype = packet_get_string(&len);
1339 reply = packet_get_char();
1341 s = session_by_channel(id);
1343 fatal("session_input_channel_req: channel %d: no session", id);
1344 c = channel_lookup(id);
1346 fatal("session_input_channel_req: channel %d: bad channel", id);
1348 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1349 s->self, id, rtype, reply);
1352 * a session is in LARVAL state until a shell
1353 * or programm is executed
1355 if (c->type == SSH_CHANNEL_LARVAL) {
1356 if (strcmp(rtype, "shell") == 0) {
1358 do_exec_no_pty(s, NULL, s->pw);
1360 do_exec_pty(s, NULL, s->pw);
1362 } else if (strcmp(rtype, "exec") == 0) {
1363 char *command = packet_get_string(&len);
1368 do_exec_no_pty(s, command, s->pw);
1370 do_exec_pty(s, command, s->pw);
1373 } else if (strcmp(rtype, "pty-req") == 0) {
1374 success = session_pty_req(s);
1375 } else if (strcmp(rtype, "x11-req") == 0) {
1376 success = session_x11_req(s);
1377 } else if (strcmp(rtype, "subsystem") == 0) {
1378 success = session_subsystem_req(s);
1381 if (strcmp(rtype, "window-change") == 0) {
1382 success = session_window_change_req(s);
1386 packet_start(success ?
1387 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1388 packet_put_int(c->remote_id);
1395 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1398 fatal("session_set_fds: called for proto != 2.0");
1400 * now that have a child and a pipe to the child,
1401 * we can activate our channel and register the fd's
1403 if (s->chanid == -1)
1404 fatal("no channel for session %d", s->self);
1405 channel_set_fds(s->chanid,
1407 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1411 session_pty_cleanup(Session *s)
1413 if (s == NULL || s->ttyfd == -1)
1416 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1418 /* Cancel the cleanup function. */
1419 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1421 /* Record that the user has logged out. */
1422 record_logout(s->pid, s->tty);
1424 /* Release the pseudo-tty. */
1425 pty_release(s->tty);
1428 * Close the server side of the socket pairs. We must do this after
1429 * the pty cleanup, so that another process doesn't get this pty
1430 * while we're still cleaning up.
1432 if (close(s->ptymaster) < 0)
1433 error("close(s->ptymaster): %s", strerror(errno));
1437 session_exit_message(Session *s, int status)
1441 fatal("session_close: no session");
1442 c = channel_lookup(s->chanid);
1444 fatal("session_close: session %d: no channel %d",
1445 s->self, s->chanid);
1446 debug("session_exit_message: session %d channel %d pid %d",
1447 s->self, s->chanid, s->pid);
1449 if (WIFEXITED(status)) {
1450 channel_request_start(s->chanid,
1452 packet_put_int(WEXITSTATUS(status));
1454 } else if (WIFSIGNALED(status)) {
1455 channel_request_start(s->chanid,
1457 packet_put_int(WTERMSIG(status));
1458 packet_put_char(WCOREDUMP(status));
1459 packet_put_cstring("");
1460 packet_put_cstring("");
1463 /* Some weird exit cause. Just exit. */
1464 packet_disconnect("wait returned status %04x.", status);
1467 /* disconnect channel */
1468 debug("session_exit_message: release channel %d", s->chanid);
1469 channel_cancel_cleanup(s->chanid);
1471 * emulate a write failure with 'chan_write_failed', nobody will be
1472 * interested in data we write.
1473 * Note that we must not call 'chan_read_failed', since there could
1474 * be some more data waiting in the pipe.
1476 if (c->ostate != CHAN_OUTPUT_CLOSED)
1477 chan_write_failed(c);
1482 session_free(Session *s)
1484 debug("session_free: session %d pid %d", s->self, s->pid);
1490 xfree(s->auth_data);
1492 xfree(s->auth_proto);
1497 session_close(Session *s)
1499 session_pty_cleanup(s);
1504 session_close_by_pid(pid_t pid, int status)
1506 Session *s = session_by_pid(pid);
1508 debug("session_close_by_pid: no session for pid %d", s->pid);
1511 if (s->chanid != -1)
1512 session_exit_message(s, status);
1517 * this is called when a channel dies before
1518 * the session 'child' itself dies
1521 session_close_by_channel(int id, void *arg)
1523 Session *s = session_by_channel(id);
1525 debug("session_close_by_channel: no session for channel %d", id);
1528 /* disconnect channel */
1529 channel_cancel_cleanup(s->chanid);
1532 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1534 /* close session immediately */
1537 /* notify child, delay session cleanup */
1538 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1539 error("session_close_by_channel: kill %d: %s",
1540 s->pid, strerror(errno));
1545 do_authenticated2(void)
1548 * Cancel the alarm we set to limit the time taken for
1554 xauthfile_cleanup_proc(NULL);