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.2 2000/04/06 08:55:22 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 extern char *__progname;
69 extern int log_stderr;
70 extern int debug_flag;
72 /* Local Xauthority file. */
73 static char *xauthfile;
76 #define MAX_SESSIONS 10
77 Session sessions[MAX_SESSIONS];
79 /* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
80 int no_port_forwarding_flag = 0;
81 int no_agent_forwarding_flag = 0;
82 int no_x11_forwarding_flag = 0;
85 /* RSA authentication "command=" option. */
86 char *forced_command = NULL;
88 /* RSA authentication "environment=" options. */
89 struct envstring *custom_environment = NULL;
92 * Remove local Xauthority file.
95 xauthfile_cleanup_proc(void *ignore)
97 debug("xauthfile_cleanup_proc called");
99 if (xauthfile != NULL) {
102 p = strrchr(xauthfile, '/');
113 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
114 * dropped connection).
117 pty_cleanup_proc(void *session)
121 fatal("pty_cleanup_proc: no session");
122 debug("pty_cleanup_proc: %s", s->tty);
125 /* Record that the user has logged out. */
126 record_logout(s->pid, s->tty);
129 /* Release the pseudo-tty. */
134 * Prepares for an interactive session. This is called after the user has
135 * been successfully authenticated. During this message exchange, pseudo
136 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
137 * are requested, etc.
140 do_authenticated(struct passwd * pw)
144 int compression_level = 0, enable_compression_after_reply = 0;
149 unsigned int proto_len, data_len, dlen;
152 * Cancel the alarm we set to limit the time taken for
158 * Inform the channel mechanism that we are the server side and that
159 * the client may request to connect to any port at all. (The user
160 * could do it anyway, and we wouldn\'t know what is permitted except
161 * by the client telling us, so we can equally well trust the client
162 * not to request anything bogus.)
164 if (!no_port_forwarding_flag)
165 channel_permit_all_opens();
170 * We stay in this loop until the client requests to execute a shell
176 /* Get a packet from the client. */
177 type = packet_read(&plen);
179 /* Process the packet. */
181 case SSH_CMSG_REQUEST_COMPRESSION:
182 packet_integrity_check(plen, 4, type);
183 compression_level = packet_get_int();
184 if (compression_level < 1 || compression_level > 9) {
185 packet_send_debug("Received illegal compression level %d.",
189 /* Enable compression after we have responded with SUCCESS. */
190 enable_compression_after_reply = 1;
194 case SSH_CMSG_REQUEST_PTY:
196 debug("Allocating a pty not permitted for this authentication.");
200 packet_disconnect("Protocol error: you already have a pty.");
202 debug("Allocating pty.");
204 /* Allocate a pty and open it. */
205 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
207 error("Failed to allocate pty.");
210 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
211 pty_setowner(pw, s->tty);
213 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
214 s->term = packet_get_string(&dlen);
215 packet_integrity_check(dlen, strlen(s->term), type);
216 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
217 /* Remaining bytes */
218 n_bytes = plen - (4 + dlen + 4 * 4);
220 if (strcmp(s->term, "") == 0) {
224 /* Get window size from the packet. */
225 s->row = packet_get_int();
226 s->col = packet_get_int();
227 s->xpixel = packet_get_int();
228 s->ypixel = packet_get_int();
229 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
231 /* Get tty modes from the packet. */
232 tty_parse_modes(s->ttyfd, &n_bytes);
233 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
235 /* Indicate that we now have a pty. */
240 case SSH_CMSG_X11_REQUEST_FORWARDING:
241 if (!options.x11_forwarding) {
242 packet_send_debug("X11 forwarding disabled in server configuration file.");
246 if (no_x11_forwarding_flag) {
247 packet_send_debug("X11 forwarding not permitted for this authentication.");
250 debug("Received request for X11 forwarding with auth spoofing.");
251 if (s->display != NULL)
252 packet_disconnect("Protocol error: X11 display already set.");
254 s->auth_proto = packet_get_string(&proto_len);
255 s->auth_data = packet_get_string(&data_len);
256 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
258 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
259 s->screen = packet_get_int();
262 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
264 if (s->display == NULL)
267 /* Setup to always have a local .Xauthority. */
268 xauthfile = xmalloc(MAXPATHLEN);
269 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
270 temporarily_use_uid(pw->pw_uid);
271 if (mkdtemp(xauthfile) == NULL) {
273 error("private X11 dir: mkdtemp %s failed: %s",
274 xauthfile, strerror(errno));
279 strlcat(xauthfile, "/cookies", MAXPATHLEN);
280 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
282 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
285 #else /* XAUTH_PATH */
286 packet_send_debug("No xauth program; cannot forward with spoofing.");
288 #endif /* XAUTH_PATH */
290 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
291 if (no_agent_forwarding_flag || compat13) {
292 debug("Authentication agent forwarding not permitted for this authentication.");
295 debug("Received authentication agent forwarding request.");
296 auth_input_request_forwarding(pw);
300 case SSH_CMSG_PORT_FORWARD_REQUEST:
301 if (no_port_forwarding_flag) {
302 debug("Port forwarding not permitted for this authentication.");
305 debug("Received TCP/IP port forwarding request.");
306 channel_input_port_forward_request(pw->pw_uid == 0);
310 case SSH_CMSG_MAX_PACKET_SIZE:
311 if (packet_set_maxsize(packet_get_int()) > 0)
315 case SSH_CMSG_EXEC_SHELL:
316 case SSH_CMSG_EXEC_CMD:
317 /* Set interactive/non-interactive mode. */
318 packet_set_interactive(have_pty || s->display != NULL,
321 if (type == SSH_CMSG_EXEC_CMD) {
322 command = packet_get_string(&dlen);
323 debug("Exec command '%.500s'", command);
324 packet_integrity_check(plen, 4 + dlen, type);
327 packet_integrity_check(plen, 0, type);
329 if (forced_command != NULL) {
330 command = forced_command;
331 debug("Forced command '%.500s'", forced_command);
334 do_exec_pty(s, command, pw);
336 do_exec_no_pty(s, command, pw);
340 /* Cleanup user's local Xauthority file. */
342 xauthfile_cleanup_proc(NULL);
347 * Any unknown messages in this phase are ignored,
348 * and a failure message is returned.
350 log("Unknown packet type received after authentication: %d", type);
352 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
356 /* Enable compression now that we have replied if appropriate. */
357 if (enable_compression_after_reply) {
358 enable_compression_after_reply = 0;
359 packet_start_compression(compression_level);
365 * This is called to fork and execute a command when we have no tty. This
366 * will call do_child from the child, and server_loop from the parent after
367 * setting up file descriptors and such.
370 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
375 int pin[2], pout[2], perr[2];
376 /* Allocate pipes for communicating with the program. */
377 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
378 packet_disconnect("Could not create pipes: %.100s",
380 #else /* USE_PIPES */
381 int inout[2], err[2];
382 /* Uses socket pairs to communicate with the program. */
383 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
384 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
385 packet_disconnect("Could not create socket pairs: %.100s",
387 #endif /* USE_PIPES */
389 fatal("do_exec_no_pty: no session");
391 setproctitle("%s@notty", pw->pw_name);
397 /* Fork the child. */
398 if ((pid = fork()) == 0) {
399 /* Child. Reinitialize the log since the pid has changed. */
400 log_init(__progname, options.log_level, options.log_facility, log_stderr);
403 * Create a new session and process group since the 4.4BSD
404 * setlogin() affects the entire process group.
407 error("setsid failed: %.100s", strerror(errno));
411 * Redirect stdin. We close the parent side of the socket
412 * pair, and make the child side the standard input.
415 if (dup2(pin[0], 0) < 0)
416 perror("dup2 stdin");
419 /* Redirect stdout. */
421 if (dup2(pout[1], 1) < 0)
422 perror("dup2 stdout");
425 /* Redirect stderr. */
427 if (dup2(perr[1], 2) < 0)
428 perror("dup2 stderr");
430 #else /* USE_PIPES */
432 * Redirect stdin, stdout, and stderr. Stdin and stdout will
433 * use the same socket, as some programs (particularly rdist)
434 * seem to depend on it.
438 if (dup2(inout[0], 0) < 0) /* stdin */
439 perror("dup2 stdin");
440 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
441 perror("dup2 stdout");
442 if (dup2(err[0], 2) < 0) /* stderr */
443 perror("dup2 stderr");
444 #endif /* USE_PIPES */
446 /* Do processing for the child (exec command etc). */
447 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
451 packet_disconnect("fork failed: %.100s", strerror(errno));
454 /* We are the parent. Close the child sides of the pipes. */
460 session_set_fds(s, pin[1], pout[0], perr[0]);
462 /* Enter the interactive session. */
463 server_loop(pid, pin[1], pout[0], perr[0]);
464 /* server_loop has closed pin[1], pout[1], and perr[1]. */
466 #else /* USE_PIPES */
467 /* We are the parent. Close the child sides of the socket pairs. */
472 * Enter the interactive session. Note: server_loop must be able to
473 * handle the case that fdin and fdout are the same.
476 session_set_fds(s, inout[1], inout[1], err[1]);
478 server_loop(pid, inout[1], inout[1], err[1]);
479 /* server_loop has closed inout[1] and err[1]. */
481 #endif /* USE_PIPES */
485 * This is called to fork and execute a command when we have a tty. This
486 * will call do_child from the child, and server_loop from the parent after
487 * setting up file descriptors, controlling tty, updating wtmp, utmp,
488 * lastlog, and other such operations.
491 do_exec_pty(Session *s, const char *command, struct passwd * pw)
494 char buf[100], *time_string;
496 const char *hostname;
497 int fdout, ptyfd, ttyfd, ptymaster;
501 struct sockaddr_storage from;
503 time_t last_login_time;
506 fatal("do_exec_pty: no session");
510 /* Get remote host name. */
511 hostname = get_canonical_hostname();
514 * Get the time when the user last logged in. Buf will be set to
515 * contain the hostname the last login was from.
517 if (!options.use_login) {
518 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
521 setproctitle("%s@%s", pw->pw_name, strrchr(s->tty, '/') + 1);
524 do_pam_session(pw->pw_name, s->tty);
528 /* Fork the child. */
529 if ((pid = fork()) == 0) {
532 /* Child. Reinitialize the log because the pid has
534 log_init(__progname, options.log_level, options.log_facility, log_stderr);
536 /* Close the master side of the pseudo tty. */
539 /* Make the pseudo tty our controlling tty. */
540 pty_make_controlling_tty(&ttyfd, s->tty);
542 /* Redirect stdin from the pseudo tty. */
543 if (dup2(ttyfd, fileno(stdin)) < 0)
544 error("dup2 stdin failed: %.100s", strerror(errno));
546 /* Redirect stdout to the pseudo tty. */
547 if (dup2(ttyfd, fileno(stdout)) < 0)
548 error("dup2 stdin failed: %.100s", strerror(errno));
550 /* Redirect stderr to the pseudo tty. */
551 if (dup2(ttyfd, fileno(stderr)) < 0)
552 error("dup2 stdin failed: %.100s", strerror(errno));
554 /* Close the extra descriptor for the pseudo tty. */
557 ///XXXX ? move to do_child() ??
559 * Get IP address of client. This is needed because we want
560 * to record where the user logged in from. If the
561 * connection is not a socket, let the ip address be 0.0.0.0.
563 memset(&from, 0, sizeof(from));
564 if (packet_connection_is_on_socket()) {
565 fromlen = sizeof(from);
566 if (getpeername(packet_get_connection_in(),
567 (struct sockaddr *) & from, &fromlen) < 0) {
568 debug("getpeername: %.100s", strerror(errno));
572 /* Record that there was a login on that terminal. */
573 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
574 (struct sockaddr *)&from);
576 /* Check if .hushlogin exists. */
577 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
578 quiet_login = stat(line, &st) >= 0;
582 print_pam_messages();
586 * If the user has logged in before, display the time of last
587 * login. However, don't display anything extra if a command
588 * has been specified (so that ssh can be used to execute
589 * commands on a remote machine without users knowing they
590 * are going to another machine). Login(1) will do this for
591 * us as well, so check if login(1) is used
593 if (command == NULL && last_login_time != 0 && !quiet_login &&
594 !options.use_login) {
595 /* Convert the date to a string. */
596 time_string = ctime(&last_login_time);
597 /* Remove the trailing newline. */
598 if (strchr(time_string, '\n'))
599 *strchr(time_string, '\n') = 0;
600 /* Display the last login time. Host if displayed
602 if (strcmp(buf, "") == 0)
603 printf("Last login: %s\r\n", time_string);
605 printf("Last login: %s from %s\r\n", time_string, buf);
608 * Print /etc/motd unless a command was specified or printing
609 * it was disabled in server options or login(1) will be
610 * used. Note that some machines appear to print it in
611 * /etc/profile or similar.
613 if (command == NULL && options.print_motd && !quiet_login &&
614 !options.use_login) {
615 /* Print /etc/motd if it exists. */
616 f = fopen("/etc/motd", "r");
618 while (fgets(line, sizeof(line), f))
623 /* Do common processing for the child, such as execing the command. */
624 do_child(command, pw, s->term, s->display, s->auth_proto, s->auth_data, s->tty);
628 packet_disconnect("fork failed: %.100s", strerror(errno));
631 /* Parent. Close the slave side of the pseudo tty. */
635 * Create another descriptor of the pty master side for use as the
636 * standard input. We could use the original descriptor, but this
637 * simplifies code in server_loop. The descriptor is bidirectional.
641 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
643 /* we keep a reference to the pty master */
644 ptymaster = dup(ptyfd);
646 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
647 s->ptymaster = ptymaster;
649 /* Enter interactive session. */
651 session_set_fds(s, ptyfd, fdout, -1);
653 server_loop(pid, ptyfd, fdout, -1);
654 /* server_loop _has_ closed ptyfd and fdout. */
655 session_pty_cleanup(s);
660 * Sets the value of the given variable in the environment. If the variable
661 * already exists, its value is overriden.
664 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
667 unsigned int i, namelen;
671 * Find the slot where the value should be stored. If the variable
672 * already exists, we reuse the slot; otherwise we append a new slot
673 * at the end of the array, expanding if necessary.
676 namelen = strlen(name);
677 for (i = 0; env[i]; i++)
678 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
681 /* Reuse the slot. */
684 /* New variable. Expand if necessary. */
685 if (i >= (*envsizep) - 1) {
687 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
689 /* Need to set the NULL pointer at end of array beyond the new slot. */
693 /* Allocate space and format the variable in the appropriate slot. */
694 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
695 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
699 * Reads environment variables from the given file and adds/overrides them
700 * into the environment. If the file does not exist, this does nothing.
701 * Otherwise, it must consist of empty lines, comments (line starts with '#')
702 * and assignments of the form name=value. No other forms are allowed.
705 read_environment_file(char ***env, unsigned int *envsize,
706 const char *filename)
712 f = fopen(filename, "r");
716 while (fgets(buf, sizeof(buf), f)) {
717 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
719 if (!*cp || *cp == '#' || *cp == '\n')
721 if (strchr(cp, '\n'))
722 *strchr(cp, '\n') = '\0';
723 value = strchr(cp, '=');
725 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
728 /* Replace the equals sign by nul, and advance value to the value string. */
731 child_set_env(env, envsize, cp, value);
738 * Sets any environment variables which have been specified by PAM
740 void do_pam_environment(char ***env, int *envsize)
742 char *equals, var_name[512], var_val[512];
746 if ((pam_env = fetch_pam_environment()) == NULL)
749 for(i = 0; pam_env[i] != NULL; i++) {
750 if ((equals = strstr(pam_env[i], "=")) == NULL)
753 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
754 memset(var_name, '\0', sizeof(var_name));
755 memset(var_val, '\0', sizeof(var_val));
757 strncpy(var_name, pam_env[i], equals - pam_env[i]);
758 strcpy(var_val, equals + 1);
760 debug("PAM environment: %s=%s", var_name, var_val);
762 child_set_env(env, envsize, var_name, var_val);
769 * Performs common processing for the child, such as setting up the
770 * environment, closing extra file descriptors, setting the user and group
771 * ids, and executing the command or shell.
774 do_child(const char *command, struct passwd * pw, const char *term,
775 const char *display, const char *auth_proto,
776 const char *auth_data, const char *ttyname)
778 const char *shell, *cp = NULL;
781 unsigned int envsize, i;
783 extern char **environ;
787 #ifndef USE_PAM /* pam_nologin handles this */
788 f = fopen("/etc/nologin", "r");
790 /* /etc/nologin exists. Print its contents and exit. */
791 while (fgets(buf, sizeof(buf), f))
799 /* Set login name in the kernel. */
800 if (setlogin(pw->pw_name) < 0)
801 error("setlogin failed: %s", strerror(errno));
803 /* Set uid, gid, and groups. */
804 /* Login(1) does this as well, and it needs uid 0 for the "-h"
805 switch, so we let login(1) to this for us. */
806 if (!options.use_login) {
807 if (getuid() == 0 || geteuid() == 0) {
808 if (setgid(pw->pw_gid) < 0) {
812 /* Initialize the group list. */
813 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
814 perror("initgroups");
819 /* Permanently switch to the desired uid. */
820 permanently_set_uid(pw->pw_uid);
822 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
823 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
826 * Get the shell from the password data. An empty shell field is
827 * legal, and means /bin/sh.
829 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
832 /* Try to get AFS tokens for the local cell. */
836 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
843 /* Initialize the environment. */
845 env = xmalloc(envsize * sizeof(char *));
848 if (!options.use_login) {
849 /* Set basic environment. */
850 child_set_env(&env, &envsize, "USER", pw->pw_name);
851 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
852 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
853 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
855 snprintf(buf, sizeof buf, "%.200s/%.50s",
856 _PATH_MAILDIR, pw->pw_name);
857 child_set_env(&env, &envsize, "MAIL", buf);
859 /* Normal systems set SHELL by default. */
860 child_set_env(&env, &envsize, "SHELL", shell);
863 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
865 /* Set custom environment options from RSA authentication. */
866 while (custom_environment) {
867 struct envstring *ce = custom_environment;
870 for (i = 0; s[i] != '=' && s[i]; i++);
873 child_set_env(&env, &envsize, s, s + i + 1);
875 custom_environment = ce->next;
880 snprintf(buf, sizeof buf, "%.50s %d %d",
881 get_remote_ipaddr(), get_remote_port(), get_local_port());
882 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
885 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
887 child_set_env(&env, &envsize, "TERM", term);
889 child_set_env(&env, &envsize, "DISPLAY", display);
893 char *authstate,*krb5cc;
895 if ((authstate = getenv("AUTHSTATE")) != NULL)
896 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
898 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
899 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
908 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
913 /* Pull in any environment variables that may have been set by PAM. */
914 do_pam_environment(&env, &envsize);
917 read_environment_file(&env,&envsize,"/etc/environment");
920 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
921 if (auth_get_socket_name() != NULL)
922 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
923 auth_get_socket_name());
925 /* read $HOME/.ssh/environment. */
926 if (!options.use_login) {
927 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
928 read_environment_file(&env, &envsize, buf);
931 /* dump the environment */
932 fprintf(stderr, "Environment:\n");
933 for (i = 0; env[i]; i++)
934 fprintf(stderr, " %.200s\n", env[i]);
937 * Close the connection descriptors; note that this is the child, and
938 * the server will still have the socket open, and it is important
939 * that we do not shutdown it. Note that the descriptors cannot be
940 * closed before building the environment, as we call
941 * get_remote_ipaddr there.
943 if (packet_get_connection_in() == packet_get_connection_out())
944 close(packet_get_connection_in());
946 close(packet_get_connection_in());
947 close(packet_get_connection_out());
950 * Close all descriptors related to channels. They will still remain
951 * open in the parent.
953 /* XXX better use close-on-exec? -markus */
957 * Close any extra file descriptors. Note that there may still be
958 * descriptors left by system functions. They will be closed later.
963 * Close any extra open file descriptors so that we don\'t have them
964 * hanging around in clients. Note that we want to do this after
965 * initgroups, because at least on Solaris 2.3 it leaves file
968 for (i = 3; i < 64; i++)
971 /* Change current directory to the user\'s home directory. */
972 if (chdir(pw->pw_dir) < 0)
973 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
974 pw->pw_dir, strerror(errno));
977 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
978 * xauth are run in the proper environment.
983 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
986 if (!options.use_login) {
987 if (stat(SSH_USER_RC, &st) >= 0) {
989 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
991 f = popen("/bin/sh " SSH_USER_RC, "w");
993 if (auth_proto != NULL && auth_data != NULL)
994 fprintf(f, "%s %s\n", auth_proto, auth_data);
997 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
998 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1000 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1002 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1004 if (auth_proto != NULL && auth_data != NULL)
1005 fprintf(f, "%s %s\n", auth_proto, auth_data);
1008 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1012 /* Add authority data to .Xauthority if appropriate. */
1013 if (auth_proto != NULL && auth_data != NULL) {
1015 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
1016 XAUTH_PATH, display, auth_proto, auth_data);
1018 f = popen(XAUTH_PATH " -q -", "w");
1020 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
1023 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
1026 #endif /* XAUTH_PATH */
1028 /* Get the last component of the shell name. */
1029 cp = strrchr(shell, '/');
1036 * If we have no command, execute the shell. In this case, the shell
1037 * name to be passed in argv[0] is preceded by '-' to indicate that
1038 * this is a login shell.
1041 if (!options.use_login) {
1045 * Check for mail if we have a tty and it was enabled
1046 * in server options.
1048 if (ttyname && options.check_mail) {
1050 struct stat mailstat;
1051 mailbox = getenv("MAIL");
1052 if (mailbox != NULL) {
1053 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
1054 printf("No mail.\n");
1055 else if (mailstat.st_mtime < mailstat.st_atime)
1056 printf("You have mail.\n");
1058 printf("You have new mail.\n");
1061 /* Start the shell. Set initial character to '-'. */
1063 strncpy(buf + 1, cp, sizeof(buf) - 1);
1064 buf[sizeof(buf) - 1] = 0;
1066 /* Execute the shell. */
1069 execve(shell, argv, env);
1071 /* Executing the shell failed. */
1076 /* Launch login(1). */
1078 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1079 "-p", "-f", "--", pw->pw_name, NULL);
1081 /* Login couldn't be executed, die. */
1088 * Execute the command using the user's shell. This uses the -c
1089 * option to execute the command.
1091 argv[0] = (char *) cp;
1093 argv[2] = (char *) command;
1095 execve(shell, argv, env);
1104 static int did_init = 0;
1106 debug("session_new: init");
1107 for(i = 0; i < MAX_SESSIONS; i++) {
1108 sessions[i].used = 0;
1109 sessions[i].self = i;
1113 for(i = 0; i < MAX_SESSIONS; i++) {
1114 Session *s = &sessions[i];
1124 s->auth_data = NULL;
1125 s->auth_proto = NULL;
1127 debug("session_new: session %d", i);
1138 for(i = 0; i < MAX_SESSIONS; i++) {
1139 Session *s = &sessions[i];
1140 debug("dump: used %d session %d %p channel %d pid %d",
1150 session_open(int chanid)
1152 Session *s = session_new();
1153 debug("session_open: channel %d", chanid);
1155 error("no more sessions");
1158 debug("session_open: session %d: link with channel %d", s->self, chanid);
1160 s->pw = auth_get_user();
1162 fatal("no user for session %i channel %d",
1163 s->self, s->chanid);
1168 session_by_channel(int id)
1171 for(i = 0; i < MAX_SESSIONS; i++) {
1172 Session *s = &sessions[i];
1173 if (s->used && s->chanid == id) {
1174 debug("session_by_channel: session %d channel %d", i, id);
1178 debug("session_by_channel: unknown channel %d", id);
1184 session_by_pid(pid_t pid)
1187 debug("session_by_pid: pid %d", pid);
1188 for(i = 0; i < MAX_SESSIONS; i++) {
1189 Session *s = &sessions[i];
1190 if (s->used && s->pid == pid)
1193 error("session_by_pid: unknown pid %d", pid);
1199 session_window_change_req(Session *s)
1201 s->col = packet_get_int();
1202 s->row = packet_get_int();
1203 s->xpixel = packet_get_int();
1204 s->ypixel = packet_get_int();
1205 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1210 session_pty_req(Session *s)
1216 s->term = packet_get_string(&len);
1217 s->col = packet_get_int();
1218 s->row = packet_get_int();
1219 s->xpixel = packet_get_int();
1220 s->ypixel = packet_get_int();
1222 if (strcmp(s->term, "") == 0) {
1226 /* Allocate a pty and open it. */
1227 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1232 error("session_pty_req: session %d alloc failed", s->self);
1235 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1237 * Add a cleanup function to clear the utmp entry and record logout
1238 * time in case we call fatal() (e.g., the connection gets closed).
1240 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1241 pty_setowner(s->pw, s->tty);
1242 /* Get window size from the packet. */
1243 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1249 session_input_channel_req(int id, void *arg)
1258 rtype = packet_get_string(&len);
1259 reply = packet_get_char();
1261 s = session_by_channel(id);
1263 fatal("session_input_channel_req: channel %d: no session", id);
1264 c = channel_lookup(id);
1266 fatal("session_input_channel_req: channel %d: bad channel", id);
1268 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1269 s->self, id, rtype, reply);
1272 * a session is in LARVAL state until a shell
1273 * or programm is executed
1275 if (c->type == SSH_CHANNEL_LARVAL) {
1276 if (strcmp(rtype, "shell") == 0) {
1278 do_exec_no_pty(s, NULL, s->pw);
1280 do_exec_pty(s, NULL, s->pw);
1282 } else if (strcmp(rtype, "exec") == 0) {
1283 char *command = packet_get_string(&len);
1285 do_exec_no_pty(s, command, s->pw);
1287 do_exec_pty(s, command, s->pw);
1290 } else if (strcmp(rtype, "pty-req") == 0) {
1291 if (session_pty_req(s) > 0)
1295 if (strcmp(rtype, "window-change") == 0) {
1296 success = session_window_change_req(s);
1300 packet_start(success ?
1301 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1302 packet_put_int(c->remote_id);
1309 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1312 fatal("session_set_fds: called for proto != 2.0");
1314 * now that have a child and a pipe to the child,
1315 * we can activate our channel and register the fd's
1317 if (s->chanid == -1)
1318 fatal("no channel for session %d", s->self);
1319 channel_set_fds(s->chanid,
1321 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1325 session_pty_cleanup(Session *s)
1327 if (s == NULL || s->ttyfd == -1)
1330 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1332 /* Cancel the cleanup function. */
1333 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1335 /* Record that the user has logged out. */
1336 record_logout(s->pid, s->tty);
1338 /* Release the pseudo-tty. */
1339 pty_release(s->tty);
1342 * Close the server side of the socket pairs. We must do this after
1343 * the pty cleanup, so that another process doesn't get this pty
1344 * while we're still cleaning up.
1346 if (close(s->ptymaster) < 0)
1347 error("close(s->ptymaster): %s", strerror(errno));
1351 session_exit_message(Session *s, int status)
1355 fatal("session_close: no session");
1356 c = channel_lookup(s->chanid);
1358 fatal("session_close: session %d: no channel %d",
1359 s->self, s->chanid);
1360 debug("session_exit_message: session %d channel %d pid %d",
1361 s->self, s->chanid, s->pid);
1363 if (WIFEXITED(status)) {
1364 channel_request_start(s->chanid,
1366 packet_put_int(WEXITSTATUS(status));
1368 } else if (WIFSIGNALED(status)) {
1369 channel_request_start(s->chanid,
1371 packet_put_int(WTERMSIG(status));
1372 packet_put_char(WCOREDUMP(status));
1373 packet_put_cstring("");
1374 packet_put_cstring("");
1377 /* Some weird exit cause. Just exit. */
1378 packet_disconnect("wait returned status %04x.", status);
1381 /* disconnect channel */
1382 debug("session_exit_message: release channel %d", s->chanid);
1383 channel_cancel_cleanup(s->chanid);
1384 if (c->istate == CHAN_INPUT_OPEN)
1385 chan_read_failed(c);
1386 chan_write_failed(c);
1391 session_free(Session *s)
1393 debug("session_free: session %d pid %d", s->self, s->pid);
1399 xfree(s->auth_data);
1401 xfree(s->auth_proto);
1406 session_close(Session *s)
1408 session_pty_cleanup(s);
1413 session_close_by_pid(pid_t pid, int status)
1415 Session *s = session_by_pid(pid);
1417 debug("session_close_by_pid: no session for pid %d", s->pid);
1420 if (s->chanid != -1)
1421 session_exit_message(s, status);
1426 * this is called when a channel dies before
1427 * the session 'child' itself dies
1430 session_close_by_channel(int id, void *arg)
1432 Session *s = session_by_channel(id);
1434 debug("session_close_by_channel: no session for channel %d", id);
1437 /* disconnect channel */
1438 channel_cancel_cleanup(s->chanid);
1441 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1443 /* close session immediately */
1446 /* notify child, delay session cleanup */
1447 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1448 error("session_close_by_channel: kill %d: %s",
1449 s->pid, strerror(errno));
1454 do_authenticated2(void)
1457 * Cancel the alarm we set to limit the time taken for
1461 log("do_authenticated2");