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.20 2000/06/18 04:42:54 markus Exp $");
29 #include "auth-options.h"
34 typedef struct Session Session;
43 int ptyfd, ttyfd, ptymaster;
44 int row, col, xpixel, ypixel;
51 int single_connection;
58 Session *session_new(void);
59 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
60 void session_pty_cleanup(Session *s);
61 void session_proctitle(Session *s);
62 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
63 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
66 do_child(const char *command, struct passwd * pw, const char *term,
67 const char *display, const char *auth_proto,
68 const char *auth_data, const char *ttyname);
71 extern ServerOptions options;
72 #ifdef HAVE___PROGNAME
73 extern char *__progname;
74 #else /* HAVE___PROGNAME */
75 static const char *__progname = "sshd";
76 #endif /* HAVE___PROGNAME */
78 extern int log_stderr;
79 extern int debug_flag;
81 /* Local Xauthority file. */
82 static char *xauthfile;
85 #define MAX_SESSIONS 10
86 Session sessions[MAX_SESSIONS];
87 #ifdef WITH_AIXAUTHENTICATE
88 /* AIX's lastlogin message, set in auth1.c */
90 #endif /* WITH_AIXAUTHENTICATE */
93 * Remove local Xauthority file.
96 xauthfile_cleanup_proc(void *ignore)
98 debug("xauthfile_cleanup_proc called");
100 if (xauthfile != NULL) {
103 p = strrchr(xauthfile, '/');
114 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
115 * dropped connection).
118 pty_cleanup_proc(void *session)
122 fatal("pty_cleanup_proc: no session");
123 debug("pty_cleanup_proc: %s", s->tty);
126 /* Record that the user has logged out. */
127 record_logout(s->pid, s->tty);
130 /* Release the pseudo-tty. */
135 * Prepares for an interactive session. This is called after the user has
136 * been successfully authenticated. During this message exchange, pseudo
137 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
138 * are requested, etc.
141 do_authenticated(struct passwd * pw)
145 int compression_level = 0, enable_compression_after_reply = 0;
150 unsigned int proto_len, data_len, dlen;
153 * Cancel the alarm we set to limit the time taken for
159 * Inform the channel mechanism that we are the server side and that
160 * the client may request to connect to any port at all. (The user
161 * could do it anyway, and we wouldn\'t know what is permitted except
162 * by the client telling us, so we can equally well trust the client
163 * not to request anything bogus.)
165 if (!no_port_forwarding_flag)
166 channel_permit_all_opens();
172 * We stay in this loop until the client requests to execute a shell
178 /* Get a packet from the client. */
179 type = packet_read(&plen);
181 /* Process the packet. */
183 case SSH_CMSG_REQUEST_COMPRESSION:
184 packet_integrity_check(plen, 4, type);
185 compression_level = packet_get_int();
186 if (compression_level < 1 || compression_level > 9) {
187 packet_send_debug("Received illegal compression level %d.",
191 /* Enable compression after we have responded with SUCCESS. */
192 enable_compression_after_reply = 1;
196 case SSH_CMSG_REQUEST_PTY:
198 debug("Allocating a pty not permitted for this authentication.");
202 packet_disconnect("Protocol error: you already have a pty.");
204 debug("Allocating pty.");
206 /* Allocate a pty and open it. */
207 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
209 error("Failed to allocate pty.");
212 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
213 pty_setowner(pw, s->tty);
215 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
216 s->term = packet_get_string(&dlen);
217 packet_integrity_check(dlen, strlen(s->term), type);
218 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
219 /* Remaining bytes */
220 n_bytes = plen - (4 + dlen + 4 * 4);
222 if (strcmp(s->term, "") == 0) {
226 /* Get window size from the packet. */
227 s->row = packet_get_int();
228 s->col = packet_get_int();
229 s->xpixel = packet_get_int();
230 s->ypixel = packet_get_int();
231 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
233 /* Get tty modes from the packet. */
234 tty_parse_modes(s->ttyfd, &n_bytes);
235 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
237 session_proctitle(s);
239 /* Indicate that we now have a pty. */
244 case SSH_CMSG_X11_REQUEST_FORWARDING:
245 if (!options.x11_forwarding) {
246 packet_send_debug("X11 forwarding disabled in server configuration file.");
249 if (!options.xauth_location) {
250 packet_send_debug("No xauth program; cannot forward with spoofing.");
253 if (no_x11_forwarding_flag) {
254 packet_send_debug("X11 forwarding not permitted for this authentication.");
257 debug("Received request for X11 forwarding with auth spoofing.");
258 if (s->display != NULL)
259 packet_disconnect("Protocol error: X11 display already set.");
261 s->auth_proto = packet_get_string(&proto_len);
262 s->auth_data = packet_get_string(&data_len);
263 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
265 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
266 s->screen = packet_get_int();
269 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
271 if (s->display == NULL)
274 /* Setup to always have a local .Xauthority. */
275 xauthfile = xmalloc(MAXPATHLEN);
276 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
277 temporarily_use_uid(pw->pw_uid);
278 if (mkdtemp(xauthfile) == NULL) {
280 error("private X11 dir: mkdtemp %s failed: %s",
281 xauthfile, strerror(errno));
284 /* XXXX remove listening channels */
287 strlcat(xauthfile, "/cookies", MAXPATHLEN);
288 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
290 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
294 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
295 if (no_agent_forwarding_flag || compat13) {
296 debug("Authentication agent forwarding not permitted for this authentication.");
299 debug("Received authentication agent forwarding request.");
300 success = auth_input_request_forwarding(pw);
303 case SSH_CMSG_PORT_FORWARD_REQUEST:
304 if (no_port_forwarding_flag) {
305 debug("Port forwarding not permitted for this authentication.");
308 debug("Received TCP/IP port forwarding request.");
309 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
313 case SSH_CMSG_MAX_PACKET_SIZE:
314 if (packet_set_maxsize(packet_get_int()) > 0)
318 case SSH_CMSG_EXEC_SHELL:
319 case SSH_CMSG_EXEC_CMD:
320 /* Set interactive/non-interactive mode. */
321 packet_set_interactive(have_pty || s->display != NULL,
324 if (type == SSH_CMSG_EXEC_CMD) {
325 command = packet_get_string(&dlen);
326 debug("Exec command '%.500s'", command);
327 packet_integrity_check(plen, 4 + dlen, type);
330 packet_integrity_check(plen, 0, type);
332 if (forced_command != NULL) {
333 command = forced_command;
334 debug("Forced command '%.500s'", forced_command);
337 do_exec_pty(s, command, pw);
339 do_exec_no_pty(s, command, pw);
343 /* Cleanup user's local Xauthority file. */
345 xauthfile_cleanup_proc(NULL);
350 * Any unknown messages in this phase are ignored,
351 * and a failure message is returned.
353 log("Unknown packet type received after authentication: %d", type);
355 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
359 /* Enable compression now that we have replied if appropriate. */
360 if (enable_compression_after_reply) {
361 enable_compression_after_reply = 0;
362 packet_start_compression(compression_level);
368 * This is called to fork and execute a command when we have no tty. This
369 * will call do_child from the child, and server_loop from the parent after
370 * setting up file descriptors and such.
373 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
378 int pin[2], pout[2], perr[2];
379 /* Allocate pipes for communicating with the program. */
380 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
381 packet_disconnect("Could not create pipes: %.100s",
383 #else /* USE_PIPES */
384 int inout[2], err[2];
385 /* Uses socket pairs to communicate with the program. */
386 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
387 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
388 packet_disconnect("Could not create socket pairs: %.100s",
390 #endif /* USE_PIPES */
392 fatal("do_exec_no_pty: no session");
394 session_proctitle(s);
400 /* Fork the child. */
401 if ((pid = fork()) == 0) {
402 /* Child. Reinitialize the log since the pid has changed. */
403 log_init(__progname, options.log_level, options.log_facility, log_stderr);
406 * Create a new session and process group since the 4.4BSD
407 * setlogin() affects the entire process group.
410 error("setsid failed: %.100s", strerror(errno));
414 * Redirect stdin. We close the parent side of the socket
415 * pair, and make the child side the standard input.
418 if (dup2(pin[0], 0) < 0)
419 perror("dup2 stdin");
422 /* Redirect stdout. */
424 if (dup2(pout[1], 1) < 0)
425 perror("dup2 stdout");
428 /* Redirect stderr. */
430 if (dup2(perr[1], 2) < 0)
431 perror("dup2 stderr");
433 #else /* USE_PIPES */
435 * Redirect stdin, stdout, and stderr. Stdin and stdout will
436 * use the same socket, as some programs (particularly rdist)
437 * seem to depend on it.
441 if (dup2(inout[0], 0) < 0) /* stdin */
442 perror("dup2 stdin");
443 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
444 perror("dup2 stdout");
445 if (dup2(err[0], 2) < 0) /* stderr */
446 perror("dup2 stderr");
447 #endif /* USE_PIPES */
449 /* Do processing for the child (exec command etc). */
450 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
454 packet_disconnect("fork failed: %.100s", strerror(errno));
457 /* We are the parent. Close the child sides of the pipes. */
463 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
465 /* Enter the interactive session. */
466 server_loop(pid, pin[1], pout[0], perr[0]);
467 /* server_loop has closed pin[1], pout[1], and perr[1]. */
469 #else /* USE_PIPES */
470 /* We are the parent. Close the child sides of the socket pairs. */
475 * Enter the interactive session. Note: server_loop must be able to
476 * handle the case that fdin and fdout are the same.
479 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
481 server_loop(pid, inout[1], inout[1], err[1]);
482 /* server_loop has closed inout[1] and err[1]. */
484 #endif /* USE_PIPES */
488 * This is called to fork and execute a command when we have a tty. This
489 * will call do_child from the child, and server_loop from the parent after
490 * setting up file descriptors, controlling tty, updating wtmp, utmp,
491 * lastlog, and other such operations.
494 do_exec_pty(Session *s, const char *command, struct passwd * pw)
497 char buf[100], *time_string;
499 const char *hostname;
500 int fdout, ptyfd, ttyfd, ptymaster;
504 struct sockaddr_storage from;
506 time_t last_login_time;
509 fatal("do_exec_pty: no session");
513 /* Get remote host name. */
514 hostname = get_canonical_hostname();
517 * Get the time when the user last logged in. Buf will be set to
518 * contain the hostname the last login was from.
520 if (!options.use_login) {
521 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
526 do_pam_session(pw->pw_name, s->tty);
530 /* Fork the child. */
531 if ((pid = fork()) == 0) {
534 /* Child. Reinitialize the log because the pid has
536 log_init(__progname, options.log_level, options.log_facility, log_stderr);
538 /* Close the master side of the pseudo tty. */
541 /* Make the pseudo tty our controlling tty. */
542 pty_make_controlling_tty(&ttyfd, s->tty);
544 /* Redirect stdin from the pseudo tty. */
545 if (dup2(ttyfd, fileno(stdin)) < 0)
546 error("dup2 stdin failed: %.100s", strerror(errno));
548 /* Redirect stdout to the pseudo tty. */
549 if (dup2(ttyfd, fileno(stdout)) < 0)
550 error("dup2 stdin failed: %.100s", strerror(errno));
552 /* Redirect stderr to the pseudo tty. */
553 if (dup2(ttyfd, fileno(stderr)) < 0)
554 error("dup2 stdin failed: %.100s", strerror(errno));
556 /* Close the extra descriptor for the pseudo tty. */
559 /* XXXX ? move to do_child() ??*/
561 * Get IP address of client. This is needed because we want
562 * to record where the user logged in from. If the
563 * connection is not a socket, let the ip address be 0.0.0.0.
565 memset(&from, 0, sizeof(from));
566 if (packet_connection_is_on_socket()) {
567 fromlen = sizeof(from);
568 if (getpeername(packet_get_connection_in(),
569 (struct sockaddr *) & from, &fromlen) < 0) {
570 debug("getpeername: %.100s", strerror(errno));
574 /* Record that there was a login on that terminal. */
575 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
576 (struct sockaddr *)&from);
578 /* Check if .hushlogin exists. */
579 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
580 quiet_login = stat(line, &st) >= 0;
584 print_pam_messages();
588 * If the user has logged in before, display the time of last
589 * login. However, don't display anything extra if a command
590 * has been specified (so that ssh can be used to execute
591 * commands on a remote machine without users knowing they
592 * are going to another machine). Login(1) will do this for
593 * us as well, so check if login(1) is used
595 if (command == NULL && last_login_time != 0 && !quiet_login &&
596 !options.use_login) {
597 /* Convert the date to a string. */
598 time_string = ctime(&last_login_time);
599 /* Remove the trailing newline. */
600 if (strchr(time_string, '\n'))
601 *strchr(time_string, '\n') = 0;
602 /* Display the last login time. Host if displayed
604 if (strcmp(buf, "") == 0)
605 printf("Last login: %s\r\n", time_string);
607 printf("Last login: %s from %s\r\n", time_string, buf);
610 * Print /etc/motd unless a command was specified or printing
611 * it was disabled in server options or login(1) will be
612 * used. Note that some machines appear to print it in
613 * /etc/profile or similar.
615 if (command == NULL && options.print_motd && !quiet_login &&
616 !options.use_login) {
617 /* Print /etc/motd if it exists. */
618 f = fopen("/etc/motd", "r");
620 while (fgets(line, sizeof(line), f))
625 #if defined(WITH_AIXAUTHENTICATE)
627 * AIX handles the lastlog info differently. Display it here.
629 if (command == NULL && aixloginmsg && *aixloginmsg &&
630 !quiet_login && !options.use_login) {
631 printf("%s\n", aixloginmsg);
634 /* Do common processing for the child, such as execing the command. */
635 do_child(command, pw, s->term, s->display, s->auth_proto,
636 s->auth_data, s->tty);
640 packet_disconnect("fork failed: %.100s", strerror(errno));
643 /* Parent. Close the slave side of the pseudo tty. */
647 * Create another descriptor of the pty master side for use as the
648 * standard input. We could use the original descriptor, but this
649 * simplifies code in server_loop. The descriptor is bidirectional.
653 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
655 /* we keep a reference to the pty master */
656 ptymaster = dup(ptyfd);
658 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
659 s->ptymaster = ptymaster;
661 /* Enter interactive session. */
663 session_set_fds(s, ptyfd, fdout, -1);
665 server_loop(pid, ptyfd, fdout, -1);
666 /* server_loop _has_ closed ptyfd and fdout. */
667 session_pty_cleanup(s);
672 * Sets the value of the given variable in the environment. If the variable
673 * already exists, its value is overriden.
676 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
679 unsigned int i, namelen;
683 * Find the slot where the value should be stored. If the variable
684 * already exists, we reuse the slot; otherwise we append a new slot
685 * at the end of the array, expanding if necessary.
688 namelen = strlen(name);
689 for (i = 0; env[i]; i++)
690 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
693 /* Reuse the slot. */
696 /* New variable. Expand if necessary. */
697 if (i >= (*envsizep) - 1) {
699 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
701 /* Need to set the NULL pointer at end of array beyond the new slot. */
705 /* Allocate space and format the variable in the appropriate slot. */
706 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
707 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
711 * Reads environment variables from the given file and adds/overrides them
712 * into the environment. If the file does not exist, this does nothing.
713 * Otherwise, it must consist of empty lines, comments (line starts with '#')
714 * and assignments of the form name=value. No other forms are allowed.
717 read_environment_file(char ***env, unsigned int *envsize,
718 const char *filename)
724 f = fopen(filename, "r");
728 while (fgets(buf, sizeof(buf), f)) {
729 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
731 if (!*cp || *cp == '#' || *cp == '\n')
733 if (strchr(cp, '\n'))
734 *strchr(cp, '\n') = '\0';
735 value = strchr(cp, '=');
737 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
741 * Replace the equals sign by nul, and advance value to
746 child_set_env(env, envsize, cp, value);
753 * Sets any environment variables which have been specified by PAM
755 void do_pam_environment(char ***env, int *envsize)
757 char *equals, var_name[512], var_val[512];
761 if ((pam_env = fetch_pam_environment()) == NULL)
764 for(i = 0; pam_env[i] != NULL; i++) {
765 if ((equals = strstr(pam_env[i], "=")) == NULL)
768 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
769 memset(var_name, '\0', sizeof(var_name));
770 memset(var_val, '\0', sizeof(var_val));
772 strncpy(var_name, pam_env[i], equals - pam_env[i]);
773 strcpy(var_val, equals + 1);
775 debug("PAM environment: %s=%s", var_name, var_val);
777 child_set_env(env, envsize, var_name, var_val);
784 * Performs common processing for the child, such as setting up the
785 * environment, closing extra file descriptors, setting the user and group
786 * ids, and executing the command or shell.
789 do_child(const char *command, struct passwd * pw, const char *term,
790 const char *display, const char *auth_proto,
791 const char *auth_data, const char *ttyname)
793 const char *shell, *cp = NULL;
797 unsigned int envsize, i;
799 extern char **environ;
803 /* login(1) is only called if we execute the login shell */
804 if (options.use_login && command != NULL)
805 options.use_login = 0;
807 #ifndef USE_PAM /* pam_nologin handles this */
808 f = fopen("/etc/nologin", "r");
810 /* /etc/nologin exists. Print its contents and exit. */
811 while (fgets(buf, sizeof(buf), f))
819 /* Set login name in the kernel. */
820 if (setlogin(pw->pw_name) < 0)
821 error("setlogin failed: %s", strerror(errno));
823 /* Set uid, gid, and groups. */
824 /* Login(1) does this as well, and it needs uid 0 for the "-h"
825 switch, so we let login(1) to this for us. */
826 if (!options.use_login) {
827 if (getuid() == 0 || geteuid() == 0) {
828 if (setgid(pw->pw_gid) < 0) {
832 /* Initialize the group list. */
833 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
834 perror("initgroups");
839 /* Permanently switch to the desired uid. */
840 permanently_set_uid(pw->pw_uid);
842 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
843 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
846 * Get the shell from the password data. An empty shell field is
847 * legal, and means /bin/sh.
849 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
852 /* Try to get AFS tokens for the local cell. */
856 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
863 /* Initialize the environment. */
865 env = xmalloc(envsize * sizeof(char *));
868 if (!options.use_login) {
869 /* Set basic environment. */
870 child_set_env(&env, &envsize, "USER", pw->pw_name);
871 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
872 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
873 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
875 snprintf(buf, sizeof buf, "%.200s/%.50s",
876 _PATH_MAILDIR, pw->pw_name);
877 child_set_env(&env, &envsize, "MAIL", buf);
879 /* Normal systems set SHELL by default. */
880 child_set_env(&env, &envsize, "SHELL", shell);
883 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
885 /* Set custom environment options from RSA authentication. */
886 while (custom_environment) {
887 struct envstring *ce = custom_environment;
890 for (i = 0; s[i] != '=' && s[i]; i++);
893 child_set_env(&env, &envsize, s, s + i + 1);
895 custom_environment = ce->next;
900 snprintf(buf, sizeof buf, "%.50s %d %d",
901 get_remote_ipaddr(), get_remote_port(), get_local_port());
902 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
905 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
907 child_set_env(&env, &envsize, "TERM", term);
909 child_set_env(&env, &envsize, "DISPLAY", display);
913 char *authstate,*krb5cc;
915 if ((authstate = getenv("AUTHSTATE")) != NULL)
916 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
918 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
919 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
928 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
933 /* Pull in any environment variables that may have been set by PAM. */
934 do_pam_environment(&env, &envsize);
937 read_environment_file(&env,&envsize,"/etc/environment");
940 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
941 if (auth_get_socket_name() != NULL)
942 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
943 auth_get_socket_name());
945 /* read $HOME/.ssh/environment. */
946 if (!options.use_login) {
947 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
949 read_environment_file(&env, &envsize, buf);
952 /* dump the environment */
953 fprintf(stderr, "Environment:\n");
954 for (i = 0; env[i]; i++)
955 fprintf(stderr, " %.200s\n", env[i]);
958 * Close the connection descriptors; note that this is the child, and
959 * the server will still have the socket open, and it is important
960 * that we do not shutdown it. Note that the descriptors cannot be
961 * closed before building the environment, as we call
962 * get_remote_ipaddr there.
964 if (packet_get_connection_in() == packet_get_connection_out())
965 close(packet_get_connection_in());
967 close(packet_get_connection_in());
968 close(packet_get_connection_out());
971 * Close all descriptors related to channels. They will still remain
972 * open in the parent.
974 /* XXX better use close-on-exec? -markus */
978 * Close any extra file descriptors. Note that there may still be
979 * descriptors left by system functions. They will be closed later.
984 * Close any extra open file descriptors so that we don\'t have them
985 * hanging around in clients. Note that we want to do this after
986 * initgroups, because at least on Solaris 2.3 it leaves file
989 for (i = 3; i < 64; i++)
992 /* Change current directory to the user\'s home directory. */
993 if (chdir(pw->pw_dir) < 0)
994 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
995 pw->pw_dir, strerror(errno));
998 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
999 * xauth are run in the proper environment.
1004 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1007 if (!options.use_login) {
1008 if (stat(SSH_USER_RC, &st) >= 0) {
1010 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
1012 f = popen("/bin/sh " SSH_USER_RC, "w");
1014 if (auth_proto != NULL && auth_data != NULL)
1015 fprintf(f, "%s %s\n", auth_proto, auth_data);
1018 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1019 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1021 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1023 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1025 if (auth_proto != NULL && auth_data != NULL)
1026 fprintf(f, "%s %s\n", auth_proto, auth_data);
1029 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1030 } else if (options.xauth_location != NULL) {
1031 /* Add authority data to .Xauthority if appropriate. */
1032 if (auth_proto != NULL && auth_data != NULL) {
1033 char *screen = strchr(display, ':');
1036 "Running %.100s add %.100s %.100s %.100s\n",
1037 options.xauth_location, display,
1038 auth_proto, auth_data);
1041 "Adding %.*s/unix%s %s %s\n",
1042 screen-display, display,
1043 screen, auth_proto, auth_data);
1045 snprintf(cmd, sizeof cmd, "%s -q -",
1046 options.xauth_location);
1047 f = popen(cmd, "w");
1049 fprintf(f, "add %s %s %s\n", display,
1050 auth_proto, auth_data);
1052 fprintf(f, "add %.*s/unix%s %s %s\n",
1053 screen-display, display,
1054 screen, auth_proto, auth_data);
1057 fprintf(stderr, "Could not run %s\n",
1062 /* Get the last component of the shell name. */
1063 cp = strrchr(shell, '/');
1070 * If we have no command, execute the shell. In this case, the shell
1071 * name to be passed in argv[0] is preceded by '-' to indicate that
1072 * this is a login shell.
1075 if (!options.use_login) {
1079 * Check for mail if we have a tty and it was enabled
1080 * in server options.
1082 if (ttyname && options.check_mail) {
1084 struct stat mailstat;
1085 mailbox = getenv("MAIL");
1086 if (mailbox != NULL) {
1087 if (stat(mailbox, &mailstat) != 0 ||
1088 mailstat.st_size == 0)
1089 printf("No mail.\n");
1090 else if (mailstat.st_mtime < mailstat.st_atime)
1091 printf("You have mail.\n");
1093 printf("You have new mail.\n");
1096 /* Start the shell. Set initial character to '-'. */
1098 strncpy(buf + 1, cp, sizeof(buf) - 1);
1099 buf[sizeof(buf) - 1] = 0;
1101 /* Execute the shell. */
1104 execve(shell, argv, env);
1106 /* Executing the shell failed. */
1111 /* Launch login(1). */
1113 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1114 "-p", "-f", "--", pw->pw_name, NULL);
1116 /* Login couldn't be executed, die. */
1123 * Execute the command using the user's shell. This uses the -c
1124 * option to execute the command.
1126 argv[0] = (char *) cp;
1128 argv[2] = (char *) command;
1130 execve(shell, argv, env);
1139 static int did_init = 0;
1141 debug("session_new: init");
1142 for(i = 0; i < MAX_SESSIONS; i++) {
1143 sessions[i].used = 0;
1144 sessions[i].self = i;
1148 for(i = 0; i < MAX_SESSIONS; i++) {
1149 Session *s = &sessions[i];
1160 s->auth_data = NULL;
1161 s->auth_proto = NULL;
1164 debug("session_new: session %d", i);
1175 for(i = 0; i < MAX_SESSIONS; i++) {
1176 Session *s = &sessions[i];
1177 debug("dump: used %d session %d %p channel %d pid %d",
1187 session_open(int chanid)
1189 Session *s = session_new();
1190 debug("session_open: channel %d", chanid);
1192 error("no more sessions");
1195 s->pw = auth_get_user();
1197 fatal("no user for session %i", s->self);
1198 debug("session_open: session %d: link with channel %d", s->self, chanid);
1204 session_by_channel(int id)
1207 for(i = 0; i < MAX_SESSIONS; i++) {
1208 Session *s = &sessions[i];
1209 if (s->used && s->chanid == id) {
1210 debug("session_by_channel: session %d channel %d", i, id);
1214 debug("session_by_channel: unknown channel %d", id);
1220 session_by_pid(pid_t pid)
1223 debug("session_by_pid: pid %d", pid);
1224 for(i = 0; i < MAX_SESSIONS; i++) {
1225 Session *s = &sessions[i];
1226 if (s->used && s->pid == pid)
1229 error("session_by_pid: unknown pid %d", pid);
1235 session_window_change_req(Session *s)
1237 s->col = packet_get_int();
1238 s->row = packet_get_int();
1239 s->xpixel = packet_get_int();
1240 s->ypixel = packet_get_int();
1242 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1247 session_pty_req(Session *s)
1250 char *term_modes; /* encoded terminal modes */
1256 s->term = packet_get_string(&len);
1257 s->col = packet_get_int();
1258 s->row = packet_get_int();
1259 s->xpixel = packet_get_int();
1260 s->ypixel = packet_get_int();
1261 term_modes = packet_get_string(&len);
1264 if (strcmp(s->term, "") == 0) {
1268 /* Allocate a pty and open it. */
1269 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1274 error("session_pty_req: session %d alloc failed", s->self);
1278 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1280 * Add a cleanup function to clear the utmp entry and record logout
1281 * time in case we call fatal() (e.g., the connection gets closed).
1283 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1284 pty_setowner(s->pw, s->tty);
1285 /* Get window size from the packet. */
1286 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1288 session_proctitle(s);
1290 /* XXX parse and set terminal modes */
1296 session_subsystem_req(Session *s)
1300 char *subsys = packet_get_string(&len);
1304 log("subsystem request for %s", subsys);
1306 for (i = 0; i < options.num_subsystems; i++) {
1307 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1308 debug("subsystem: exec() %s", options.subsystem_command[i]);
1309 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1315 log("subsystem request for %s failed, subsystem not found", subsys);
1322 session_x11_req(Session *s)
1324 if (!no_port_forwarding_flag) {
1325 debug("X11 forwarding disabled in user configuration file.");
1328 if (!options.x11_forwarding) {
1329 debug("X11 forwarding disabled in server configuration file.");
1332 if (xauthfile != NULL) {
1333 debug("X11 fwd already started.");
1337 debug("Received request for X11 forwarding with auth spoofing.");
1338 if (s->display != NULL)
1339 packet_disconnect("Protocol error: X11 display already set.");
1341 s->single_connection = packet_get_char();
1342 s->auth_proto = packet_get_string(NULL);
1343 s->auth_data = packet_get_string(NULL);
1344 s->screen = packet_get_int();
1347 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1348 if (s->display == NULL) {
1349 xfree(s->auth_proto);
1350 xfree(s->auth_data);
1353 xauthfile = xmalloc(MAXPATHLEN);
1354 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1355 temporarily_use_uid(s->pw->pw_uid);
1356 if (mkdtemp(xauthfile) == NULL) {
1358 error("private X11 dir: mkdtemp %s failed: %s",
1359 xauthfile, strerror(errno));
1362 xfree(s->auth_proto);
1363 xfree(s->auth_data);
1364 /* XXXX remove listening channels */
1367 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1368 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1370 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1375 session_shell_req(Session *s)
1377 /* if forced_command == NULL, the shell is execed */
1378 char *shell = forced_command;
1382 do_exec_no_pty(s, shell, s->pw);
1384 do_exec_pty(s, shell, s->pw);
1389 session_exec_req(Session *s)
1392 char *command = packet_get_string(&len);
1394 if (forced_command) {
1396 command = forced_command;
1397 debug("Forced command '%.500s'", forced_command);
1401 do_exec_no_pty(s, command, s->pw);
1403 do_exec_pty(s, command, s->pw);
1404 if (forced_command == NULL)
1410 session_input_channel_req(int id, void *arg)
1419 rtype = packet_get_string(&len);
1420 reply = packet_get_char();
1422 s = session_by_channel(id);
1424 fatal("session_input_channel_req: channel %d: no session", id);
1425 c = channel_lookup(id);
1427 fatal("session_input_channel_req: channel %d: bad channel", id);
1429 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1430 s->self, id, rtype, reply);
1433 * a session is in LARVAL state until a shell
1434 * or programm is executed
1436 if (c->type == SSH_CHANNEL_LARVAL) {
1437 if (strcmp(rtype, "shell") == 0) {
1438 success = session_shell_req(s);
1439 } else if (strcmp(rtype, "exec") == 0) {
1440 success = session_exec_req(s);
1441 } else if (strcmp(rtype, "pty-req") == 0) {
1442 success = session_pty_req(s);
1443 } else if (strcmp(rtype, "x11-req") == 0) {
1444 success = session_x11_req(s);
1445 } else if (strcmp(rtype, "subsystem") == 0) {
1446 success = session_subsystem_req(s);
1449 if (strcmp(rtype, "window-change") == 0) {
1450 success = session_window_change_req(s);
1454 packet_start(success ?
1455 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1456 packet_put_int(c->remote_id);
1463 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1466 fatal("session_set_fds: called for proto != 2.0");
1468 * now that have a child and a pipe to the child,
1469 * we can activate our channel and register the fd's
1471 if (s->chanid == -1)
1472 fatal("no channel for session %d", s->self);
1473 channel_set_fds(s->chanid,
1475 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1479 session_pty_cleanup(Session *s)
1481 if (s == NULL || s->ttyfd == -1)
1484 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1486 /* Cancel the cleanup function. */
1487 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1489 /* Record that the user has logged out. */
1490 record_logout(s->pid, s->tty);
1492 /* Release the pseudo-tty. */
1493 pty_release(s->tty);
1496 * Close the server side of the socket pairs. We must do this after
1497 * the pty cleanup, so that another process doesn't get this pty
1498 * while we're still cleaning up.
1500 if (close(s->ptymaster) < 0)
1501 error("close(s->ptymaster): %s", strerror(errno));
1505 session_exit_message(Session *s, int status)
1509 fatal("session_close: no session");
1510 c = channel_lookup(s->chanid);
1512 fatal("session_close: session %d: no channel %d",
1513 s->self, s->chanid);
1514 debug("session_exit_message: session %d channel %d pid %d",
1515 s->self, s->chanid, s->pid);
1517 if (WIFEXITED(status)) {
1518 channel_request_start(s->chanid,
1520 packet_put_int(WEXITSTATUS(status));
1522 } else if (WIFSIGNALED(status)) {
1523 channel_request_start(s->chanid,
1525 packet_put_int(WTERMSIG(status));
1527 packet_put_char(WCOREDUMP(status));
1528 #else /* WCOREDUMP */
1530 #endif /* WCOREDUMP */
1531 packet_put_cstring("");
1532 packet_put_cstring("");
1535 /* Some weird exit cause. Just exit. */
1536 packet_disconnect("wait returned status %04x.", status);
1539 /* disconnect channel */
1540 debug("session_exit_message: release channel %d", s->chanid);
1541 channel_cancel_cleanup(s->chanid);
1543 * emulate a write failure with 'chan_write_failed', nobody will be
1544 * interested in data we write.
1545 * Note that we must not call 'chan_read_failed', since there could
1546 * be some more data waiting in the pipe.
1548 if (c->ostate != CHAN_OUTPUT_CLOSED)
1549 chan_write_failed(c);
1554 session_free(Session *s)
1556 debug("session_free: session %d pid %d", s->self, s->pid);
1562 xfree(s->auth_data);
1564 xfree(s->auth_proto);
1569 session_close(Session *s)
1571 session_pty_cleanup(s);
1573 session_proctitle(s);
1577 session_close_by_pid(pid_t pid, int status)
1579 Session *s = session_by_pid(pid);
1581 debug("session_close_by_pid: no session for pid %d", s->pid);
1584 if (s->chanid != -1)
1585 session_exit_message(s, status);
1590 * this is called when a channel dies before
1591 * the session 'child' itself dies
1594 session_close_by_channel(int id, void *arg)
1596 Session *s = session_by_channel(id);
1598 debug("session_close_by_channel: no session for channel %d", id);
1601 /* disconnect channel */
1602 channel_cancel_cleanup(s->chanid);
1605 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1607 /* close session immediately */
1610 /* notify child, delay session cleanup */
1611 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1612 error("session_close_by_channel: kill %d: %s",
1613 s->pid, strerror(errno));
1618 session_tty_list(void)
1620 static char buf[1024];
1623 for(i = 0; i < MAX_SESSIONS; i++) {
1624 Session *s = &sessions[i];
1625 if (s->used && s->ttyfd != -1) {
1627 strlcat(buf, ",", sizeof buf);
1628 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1632 strlcpy(buf, "notty", sizeof buf);
1637 session_proctitle(Session *s)
1640 error("no user for session %d", s->self);
1642 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1646 do_authenticated2(void)
1649 * Cancel the alarm we set to limit the time taken for
1655 xauthfile_cleanup_proc(NULL);