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.12 2000/05/03 18:03:07 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 session_proctitle(Session *s);
61 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
62 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
65 do_child(const char *command, struct passwd * pw, const char *term,
66 const char *display, const char *auth_proto,
67 const char *auth_data, const char *ttyname);
70 extern ServerOptions options;
71 #ifdef HAVE___PROGNAME
72 extern char *__progname;
73 #else /* HAVE___PROGNAME */
74 static const char *__progname = "sshd";
75 #endif /* HAVE___PROGNAME */
77 extern int log_stderr;
78 extern int debug_flag;
80 /* Local Xauthority file. */
81 static char *xauthfile;
84 #define MAX_SESSIONS 10
85 Session sessions[MAX_SESSIONS];
86 #ifdef WITH_AIXAUTHENTICATE
87 /* AIX's lastlogin message, set in auth1.c */
89 #endif /* WITH_AIXAUTHENTICATE */
91 /* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
92 int no_port_forwarding_flag = 0;
93 int no_agent_forwarding_flag = 0;
94 int no_x11_forwarding_flag = 0;
97 /* RSA authentication "command=" option. */
98 char *forced_command = NULL;
100 /* RSA authentication "environment=" options. */
101 struct envstring *custom_environment = NULL;
104 * Remove local Xauthority file.
107 xauthfile_cleanup_proc(void *ignore)
109 debug("xauthfile_cleanup_proc called");
111 if (xauthfile != NULL) {
114 p = strrchr(xauthfile, '/');
125 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
126 * dropped connection).
129 pty_cleanup_proc(void *session)
133 fatal("pty_cleanup_proc: no session");
134 debug("pty_cleanup_proc: %s", s->tty);
137 /* Record that the user has logged out. */
138 record_logout(s->pid, s->tty);
141 /* Release the pseudo-tty. */
146 * Prepares for an interactive session. This is called after the user has
147 * been successfully authenticated. During this message exchange, pseudo
148 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
149 * are requested, etc.
152 do_authenticated(struct passwd * pw)
156 int compression_level = 0, enable_compression_after_reply = 0;
161 unsigned int proto_len, data_len, dlen;
164 * Cancel the alarm we set to limit the time taken for
170 * Inform the channel mechanism that we are the server side and that
171 * the client may request to connect to any port at all. (The user
172 * could do it anyway, and we wouldn\'t know what is permitted except
173 * by the client telling us, so we can equally well trust the client
174 * not to request anything bogus.)
176 if (!no_port_forwarding_flag)
177 channel_permit_all_opens();
183 * We stay in this loop until the client requests to execute a shell
189 /* Get a packet from the client. */
190 type = packet_read(&plen);
192 /* Process the packet. */
194 case SSH_CMSG_REQUEST_COMPRESSION:
195 packet_integrity_check(plen, 4, type);
196 compression_level = packet_get_int();
197 if (compression_level < 1 || compression_level > 9) {
198 packet_send_debug("Received illegal compression level %d.",
202 /* Enable compression after we have responded with SUCCESS. */
203 enable_compression_after_reply = 1;
207 case SSH_CMSG_REQUEST_PTY:
209 debug("Allocating a pty not permitted for this authentication.");
213 packet_disconnect("Protocol error: you already have a pty.");
215 debug("Allocating pty.");
217 /* Allocate a pty and open it. */
218 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
220 error("Failed to allocate pty.");
223 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
224 pty_setowner(pw, s->tty);
226 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
227 s->term = packet_get_string(&dlen);
228 packet_integrity_check(dlen, strlen(s->term), type);
229 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
230 /* Remaining bytes */
231 n_bytes = plen - (4 + dlen + 4 * 4);
233 if (strcmp(s->term, "") == 0) {
237 /* Get window size from the packet. */
238 s->row = packet_get_int();
239 s->col = packet_get_int();
240 s->xpixel = packet_get_int();
241 s->ypixel = packet_get_int();
242 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
244 /* Get tty modes from the packet. */
245 tty_parse_modes(s->ttyfd, &n_bytes);
246 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
248 session_proctitle(s);
250 /* Indicate that we now have a pty. */
255 case SSH_CMSG_X11_REQUEST_FORWARDING:
256 if (!options.x11_forwarding) {
257 packet_send_debug("X11 forwarding disabled in server configuration file.");
261 if (no_x11_forwarding_flag) {
262 packet_send_debug("X11 forwarding not permitted for this authentication.");
265 debug("Received request for X11 forwarding with auth spoofing.");
266 if (s->display != NULL)
267 packet_disconnect("Protocol error: X11 display already set.");
269 s->auth_proto = packet_get_string(&proto_len);
270 s->auth_data = packet_get_string(&data_len);
271 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
273 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
274 s->screen = packet_get_int();
277 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
279 if (s->display == NULL)
282 /* Setup to always have a local .Xauthority. */
283 xauthfile = xmalloc(MAXPATHLEN);
284 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
285 temporarily_use_uid(pw->pw_uid);
286 if (mkdtemp(xauthfile) == NULL) {
288 error("private X11 dir: mkdtemp %s failed: %s",
289 xauthfile, strerror(errno));
292 /* XXXX remove listening channels */
295 strlcat(xauthfile, "/cookies", MAXPATHLEN);
296 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
298 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
301 #else /* XAUTH_PATH */
302 packet_send_debug("No xauth program; cannot forward with spoofing.");
304 #endif /* XAUTH_PATH */
306 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
307 if (no_agent_forwarding_flag || compat13) {
308 debug("Authentication agent forwarding not permitted for this authentication.");
311 debug("Received authentication agent forwarding request.");
312 auth_input_request_forwarding(pw);
316 case SSH_CMSG_PORT_FORWARD_REQUEST:
317 if (no_port_forwarding_flag) {
318 debug("Port forwarding not permitted for this authentication.");
321 debug("Received TCP/IP port forwarding request.");
322 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
326 case SSH_CMSG_MAX_PACKET_SIZE:
327 if (packet_set_maxsize(packet_get_int()) > 0)
331 case SSH_CMSG_EXEC_SHELL:
332 case SSH_CMSG_EXEC_CMD:
333 /* Set interactive/non-interactive mode. */
334 packet_set_interactive(have_pty || s->display != NULL,
337 if (type == SSH_CMSG_EXEC_CMD) {
338 command = packet_get_string(&dlen);
339 debug("Exec command '%.500s'", command);
340 packet_integrity_check(plen, 4 + dlen, type);
343 packet_integrity_check(plen, 0, type);
345 if (forced_command != NULL) {
346 command = forced_command;
347 debug("Forced command '%.500s'", forced_command);
350 do_exec_pty(s, command, pw);
352 do_exec_no_pty(s, command, pw);
356 /* Cleanup user's local Xauthority file. */
358 xauthfile_cleanup_proc(NULL);
363 * Any unknown messages in this phase are ignored,
364 * and a failure message is returned.
366 log("Unknown packet type received after authentication: %d", type);
368 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
372 /* Enable compression now that we have replied if appropriate. */
373 if (enable_compression_after_reply) {
374 enable_compression_after_reply = 0;
375 packet_start_compression(compression_level);
381 * This is called to fork and execute a command when we have no tty. This
382 * will call do_child from the child, and server_loop from the parent after
383 * setting up file descriptors and such.
386 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
391 int pin[2], pout[2], perr[2];
392 /* Allocate pipes for communicating with the program. */
393 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
394 packet_disconnect("Could not create pipes: %.100s",
396 #else /* USE_PIPES */
397 int inout[2], err[2];
398 /* Uses socket pairs to communicate with the program. */
399 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
400 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
401 packet_disconnect("Could not create socket pairs: %.100s",
403 #endif /* USE_PIPES */
405 fatal("do_exec_no_pty: no session");
407 session_proctitle(s);
413 /* Fork the child. */
414 if ((pid = fork()) == 0) {
415 /* Child. Reinitialize the log since the pid has changed. */
416 log_init(__progname, options.log_level, options.log_facility, log_stderr);
419 * Create a new session and process group since the 4.4BSD
420 * setlogin() affects the entire process group.
423 error("setsid failed: %.100s", strerror(errno));
427 * Redirect stdin. We close the parent side of the socket
428 * pair, and make the child side the standard input.
431 if (dup2(pin[0], 0) < 0)
432 perror("dup2 stdin");
435 /* Redirect stdout. */
437 if (dup2(pout[1], 1) < 0)
438 perror("dup2 stdout");
441 /* Redirect stderr. */
443 if (dup2(perr[1], 2) < 0)
444 perror("dup2 stderr");
446 #else /* USE_PIPES */
448 * Redirect stdin, stdout, and stderr. Stdin and stdout will
449 * use the same socket, as some programs (particularly rdist)
450 * seem to depend on it.
454 if (dup2(inout[0], 0) < 0) /* stdin */
455 perror("dup2 stdin");
456 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
457 perror("dup2 stdout");
458 if (dup2(err[0], 2) < 0) /* stderr */
459 perror("dup2 stderr");
460 #endif /* USE_PIPES */
462 /* Do processing for the child (exec command etc). */
463 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
467 packet_disconnect("fork failed: %.100s", strerror(errno));
470 /* We are the parent. Close the child sides of the pipes. */
476 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
478 /* Enter the interactive session. */
479 server_loop(pid, pin[1], pout[0], perr[0]);
480 /* server_loop has closed pin[1], pout[1], and perr[1]. */
482 #else /* USE_PIPES */
483 /* We are the parent. Close the child sides of the socket pairs. */
488 * Enter the interactive session. Note: server_loop must be able to
489 * handle the case that fdin and fdout are the same.
492 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
494 server_loop(pid, inout[1], inout[1], err[1]);
495 /* server_loop has closed inout[1] and err[1]. */
497 #endif /* USE_PIPES */
501 * This is called to fork and execute a command when we have a tty. This
502 * will call do_child from the child, and server_loop from the parent after
503 * setting up file descriptors, controlling tty, updating wtmp, utmp,
504 * lastlog, and other such operations.
507 do_exec_pty(Session *s, const char *command, struct passwd * pw)
510 char buf[100], *time_string;
512 const char *hostname;
513 int fdout, ptyfd, ttyfd, ptymaster;
517 struct sockaddr_storage from;
519 time_t last_login_time;
522 fatal("do_exec_pty: no session");
526 /* Get remote host name. */
527 hostname = get_canonical_hostname();
530 * Get the time when the user last logged in. Buf will be set to
531 * contain the hostname the last login was from.
533 if (!options.use_login) {
534 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
539 do_pam_session(pw->pw_name, s->tty);
543 /* Fork the child. */
544 if ((pid = fork()) == 0) {
547 /* Child. Reinitialize the log because the pid has
549 log_init(__progname, options.log_level, options.log_facility, log_stderr);
551 /* Close the master side of the pseudo tty. */
554 /* Make the pseudo tty our controlling tty. */
555 pty_make_controlling_tty(&ttyfd, s->tty);
557 /* Redirect stdin from the pseudo tty. */
558 if (dup2(ttyfd, fileno(stdin)) < 0)
559 error("dup2 stdin failed: %.100s", strerror(errno));
561 /* Redirect stdout to the pseudo tty. */
562 if (dup2(ttyfd, fileno(stdout)) < 0)
563 error("dup2 stdin failed: %.100s", strerror(errno));
565 /* Redirect stderr to the pseudo tty. */
566 if (dup2(ttyfd, fileno(stderr)) < 0)
567 error("dup2 stdin failed: %.100s", strerror(errno));
569 /* Close the extra descriptor for the pseudo tty. */
572 /* XXXX ? move to do_child() ??*/
574 * Get IP address of client. This is needed because we want
575 * to record where the user logged in from. If the
576 * connection is not a socket, let the ip address be 0.0.0.0.
578 memset(&from, 0, sizeof(from));
579 if (packet_connection_is_on_socket()) {
580 fromlen = sizeof(from);
581 if (getpeername(packet_get_connection_in(),
582 (struct sockaddr *) & from, &fromlen) < 0) {
583 debug("getpeername: %.100s", strerror(errno));
587 /* Record that there was a login on that terminal. */
588 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
589 (struct sockaddr *)&from);
591 /* Check if .hushlogin exists. */
592 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
593 quiet_login = stat(line, &st) >= 0;
597 print_pam_messages();
601 * If the user has logged in before, display the time of last
602 * login. However, don't display anything extra if a command
603 * has been specified (so that ssh can be used to execute
604 * commands on a remote machine without users knowing they
605 * are going to another machine). Login(1) will do this for
606 * us as well, so check if login(1) is used
608 if (command == NULL && last_login_time != 0 && !quiet_login &&
609 !options.use_login) {
610 /* Convert the date to a string. */
611 time_string = ctime(&last_login_time);
612 /* Remove the trailing newline. */
613 if (strchr(time_string, '\n'))
614 *strchr(time_string, '\n') = 0;
615 /* Display the last login time. Host if displayed
617 if (strcmp(buf, "") == 0)
618 printf("Last login: %s\r\n", time_string);
620 printf("Last login: %s from %s\r\n", time_string, buf);
623 * Print /etc/motd unless a command was specified or printing
624 * it was disabled in server options or login(1) will be
625 * used. Note that some machines appear to print it in
626 * /etc/profile or similar.
628 if (command == NULL && options.print_motd && !quiet_login &&
629 !options.use_login) {
630 /* Print /etc/motd if it exists. */
631 f = fopen("/etc/motd", "r");
633 while (fgets(line, sizeof(line), f))
638 #if defined(WITH_AIXAUTHENTICATE)
640 * AIX handles the lastlog info differently. Display it here.
642 if (command == NULL && aixloginmsg && *aixloginmsg &&
643 !quiet_login && !options.use_login) {
644 printf("%s\n", aixloginmsg);
647 /* Do common processing for the child, such as execing the command. */
648 do_child(command, pw, s->term, s->display, s->auth_proto, s->auth_data, s->tty);
652 packet_disconnect("fork failed: %.100s", strerror(errno));
655 /* Parent. Close the slave side of the pseudo tty. */
659 * Create another descriptor of the pty master side for use as the
660 * standard input. We could use the original descriptor, but this
661 * simplifies code in server_loop. The descriptor is bidirectional.
665 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
667 /* we keep a reference to the pty master */
668 ptymaster = dup(ptyfd);
670 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
671 s->ptymaster = ptymaster;
673 /* Enter interactive session. */
675 session_set_fds(s, ptyfd, fdout, -1);
677 server_loop(pid, ptyfd, fdout, -1);
678 /* server_loop _has_ closed ptyfd and fdout. */
679 session_pty_cleanup(s);
684 * Sets the value of the given variable in the environment. If the variable
685 * already exists, its value is overriden.
688 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
691 unsigned int i, namelen;
695 * Find the slot where the value should be stored. If the variable
696 * already exists, we reuse the slot; otherwise we append a new slot
697 * at the end of the array, expanding if necessary.
700 namelen = strlen(name);
701 for (i = 0; env[i]; i++)
702 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
705 /* Reuse the slot. */
708 /* New variable. Expand if necessary. */
709 if (i >= (*envsizep) - 1) {
711 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
713 /* Need to set the NULL pointer at end of array beyond the new slot. */
717 /* Allocate space and format the variable in the appropriate slot. */
718 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
719 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
723 * Reads environment variables from the given file and adds/overrides them
724 * into the environment. If the file does not exist, this does nothing.
725 * Otherwise, it must consist of empty lines, comments (line starts with '#')
726 * and assignments of the form name=value. No other forms are allowed.
729 read_environment_file(char ***env, unsigned int *envsize,
730 const char *filename)
736 f = fopen(filename, "r");
740 while (fgets(buf, sizeof(buf), f)) {
741 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
743 if (!*cp || *cp == '#' || *cp == '\n')
745 if (strchr(cp, '\n'))
746 *strchr(cp, '\n') = '\0';
747 value = strchr(cp, '=');
749 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
752 /* Replace the equals sign by nul, and advance value to the value string. */
755 child_set_env(env, envsize, cp, value);
762 * Sets any environment variables which have been specified by PAM
764 void do_pam_environment(char ***env, int *envsize)
766 char *equals, var_name[512], var_val[512];
770 if ((pam_env = fetch_pam_environment()) == NULL)
773 for(i = 0; pam_env[i] != NULL; i++) {
774 if ((equals = strstr(pam_env[i], "=")) == NULL)
777 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
778 memset(var_name, '\0', sizeof(var_name));
779 memset(var_val, '\0', sizeof(var_val));
781 strncpy(var_name, pam_env[i], equals - pam_env[i]);
782 strcpy(var_val, equals + 1);
784 debug("PAM environment: %s=%s", var_name, var_val);
786 child_set_env(env, envsize, var_name, var_val);
793 * Performs common processing for the child, such as setting up the
794 * environment, closing extra file descriptors, setting the user and group
795 * ids, and executing the command or shell.
798 do_child(const char *command, struct passwd * pw, const char *term,
799 const char *display, const char *auth_proto,
800 const char *auth_data, const char *ttyname)
802 const char *shell, *cp = NULL;
805 unsigned int envsize, i;
807 extern char **environ;
811 #ifndef USE_PAM /* pam_nologin handles this */
812 f = fopen("/etc/nologin", "r");
814 /* /etc/nologin exists. Print its contents and exit. */
815 while (fgets(buf, sizeof(buf), f))
823 /* Set login name in the kernel. */
824 if (setlogin(pw->pw_name) < 0)
825 error("setlogin failed: %s", strerror(errno));
827 /* Set uid, gid, and groups. */
828 /* Login(1) does this as well, and it needs uid 0 for the "-h"
829 switch, so we let login(1) to this for us. */
830 if (!options.use_login) {
831 if (getuid() == 0 || geteuid() == 0) {
832 if (setgid(pw->pw_gid) < 0) {
836 /* Initialize the group list. */
837 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
838 perror("initgroups");
843 /* Permanently switch to the desired uid. */
844 permanently_set_uid(pw->pw_uid);
846 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
847 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
850 * Get the shell from the password data. An empty shell field is
851 * legal, and means /bin/sh.
853 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
856 /* Try to get AFS tokens for the local cell. */
860 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
867 /* Initialize the environment. */
869 env = xmalloc(envsize * sizeof(char *));
872 if (!options.use_login) {
873 /* Set basic environment. */
874 child_set_env(&env, &envsize, "USER", pw->pw_name);
875 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
876 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
877 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
879 snprintf(buf, sizeof buf, "%.200s/%.50s",
880 _PATH_MAILDIR, pw->pw_name);
881 child_set_env(&env, &envsize, "MAIL", buf);
883 /* Normal systems set SHELL by default. */
884 child_set_env(&env, &envsize, "SHELL", shell);
887 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
889 /* Set custom environment options from RSA authentication. */
890 while (custom_environment) {
891 struct envstring *ce = custom_environment;
894 for (i = 0; s[i] != '=' && s[i]; i++);
897 child_set_env(&env, &envsize, s, s + i + 1);
899 custom_environment = ce->next;
904 snprintf(buf, sizeof buf, "%.50s %d %d",
905 get_remote_ipaddr(), get_remote_port(), get_local_port());
906 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
909 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
911 child_set_env(&env, &envsize, "TERM", term);
913 child_set_env(&env, &envsize, "DISPLAY", display);
917 char *authstate,*krb5cc;
919 if ((authstate = getenv("AUTHSTATE")) != NULL)
920 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
922 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
923 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
932 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
937 /* Pull in any environment variables that may have been set by PAM. */
938 do_pam_environment(&env, &envsize);
941 read_environment_file(&env,&envsize,"/etc/environment");
944 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
945 if (auth_get_socket_name() != NULL)
946 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
947 auth_get_socket_name());
949 /* read $HOME/.ssh/environment. */
950 if (!options.use_login) {
951 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
952 read_environment_file(&env, &envsize, buf);
955 /* dump the environment */
956 fprintf(stderr, "Environment:\n");
957 for (i = 0; env[i]; i++)
958 fprintf(stderr, " %.200s\n", env[i]);
961 * Close the connection descriptors; note that this is the child, and
962 * the server will still have the socket open, and it is important
963 * that we do not shutdown it. Note that the descriptors cannot be
964 * closed before building the environment, as we call
965 * get_remote_ipaddr there.
967 if (packet_get_connection_in() == packet_get_connection_out())
968 close(packet_get_connection_in());
970 close(packet_get_connection_in());
971 close(packet_get_connection_out());
974 * Close all descriptors related to channels. They will still remain
975 * open in the parent.
977 /* XXX better use close-on-exec? -markus */
981 * Close any extra file descriptors. Note that there may still be
982 * descriptors left by system functions. They will be closed later.
987 * Close any extra open file descriptors so that we don\'t have them
988 * hanging around in clients. Note that we want to do this after
989 * initgroups, because at least on Solaris 2.3 it leaves file
992 for (i = 3; i < 64; i++)
995 /* Change current directory to the user\'s home directory. */
996 if (chdir(pw->pw_dir) < 0)
997 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
998 pw->pw_dir, strerror(errno));
1001 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1002 * xauth are run in the proper environment.
1007 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1010 if (!options.use_login) {
1011 if (stat(SSH_USER_RC, &st) >= 0) {
1013 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
1015 f = popen("/bin/sh " SSH_USER_RC, "w");
1017 if (auth_proto != NULL && auth_data != NULL)
1018 fprintf(f, "%s %s\n", auth_proto, auth_data);
1021 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1022 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1024 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1026 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1028 if (auth_proto != NULL && auth_data != NULL)
1029 fprintf(f, "%s %s\n", auth_proto, auth_data);
1032 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1036 /* Add authority data to .Xauthority if appropriate. */
1037 if (auth_proto != NULL && auth_data != NULL) {
1039 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
1040 XAUTH_PATH, display, auth_proto, auth_data);
1042 f = popen(XAUTH_PATH " -q -", "w");
1044 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
1047 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
1050 #endif /* XAUTH_PATH */
1052 /* Get the last component of the shell name. */
1053 cp = strrchr(shell, '/');
1060 * If we have no command, execute the shell. In this case, the shell
1061 * name to be passed in argv[0] is preceded by '-' to indicate that
1062 * this is a login shell.
1065 if (!options.use_login) {
1069 * Check for mail if we have a tty and it was enabled
1070 * in server options.
1072 if (ttyname && options.check_mail) {
1074 struct stat mailstat;
1075 mailbox = getenv("MAIL");
1076 if (mailbox != NULL) {
1077 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
1078 printf("No mail.\n");
1079 else if (mailstat.st_mtime < mailstat.st_atime)
1080 printf("You have mail.\n");
1082 printf("You have new mail.\n");
1085 /* Start the shell. Set initial character to '-'. */
1087 strncpy(buf + 1, cp, sizeof(buf) - 1);
1088 buf[sizeof(buf) - 1] = 0;
1090 /* Execute the shell. */
1093 execve(shell, argv, env);
1095 /* Executing the shell failed. */
1100 /* Launch login(1). */
1102 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1103 "-p", "-f", "--", pw->pw_name, NULL);
1105 /* Login couldn't be executed, die. */
1112 * Execute the command using the user's shell. This uses the -c
1113 * option to execute the command.
1115 argv[0] = (char *) cp;
1117 argv[2] = (char *) command;
1119 execve(shell, argv, env);
1128 static int did_init = 0;
1130 debug("session_new: init");
1131 for(i = 0; i < MAX_SESSIONS; i++) {
1132 sessions[i].used = 0;
1133 sessions[i].self = i;
1137 for(i = 0; i < MAX_SESSIONS; i++) {
1138 Session *s = &sessions[i];
1149 s->auth_data = NULL;
1150 s->auth_proto = NULL;
1153 debug("session_new: session %d", i);
1164 for(i = 0; i < MAX_SESSIONS; i++) {
1165 Session *s = &sessions[i];
1166 debug("dump: used %d session %d %p channel %d pid %d",
1176 session_open(int chanid)
1178 Session *s = session_new();
1179 debug("session_open: channel %d", chanid);
1181 error("no more sessions");
1184 s->pw = auth_get_user();
1186 fatal("no user for session %i", s->self);
1187 debug("session_open: session %d: link with channel %d", s->self, chanid);
1193 session_by_channel(int id)
1196 for(i = 0; i < MAX_SESSIONS; i++) {
1197 Session *s = &sessions[i];
1198 if (s->used && s->chanid == id) {
1199 debug("session_by_channel: session %d channel %d", i, id);
1203 debug("session_by_channel: unknown channel %d", id);
1209 session_by_pid(pid_t pid)
1212 debug("session_by_pid: pid %d", pid);
1213 for(i = 0; i < MAX_SESSIONS; i++) {
1214 Session *s = &sessions[i];
1215 if (s->used && s->pid == pid)
1218 error("session_by_pid: unknown pid %d", pid);
1224 session_window_change_req(Session *s)
1226 s->col = packet_get_int();
1227 s->row = packet_get_int();
1228 s->xpixel = packet_get_int();
1229 s->ypixel = packet_get_int();
1231 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1236 session_pty_req(Session *s)
1239 char *term_modes; /* encoded terminal modes */
1243 s->term = packet_get_string(&len);
1244 s->col = packet_get_int();
1245 s->row = packet_get_int();
1246 s->xpixel = packet_get_int();
1247 s->ypixel = packet_get_int();
1248 term_modes = packet_get_string(&len);
1251 if (strcmp(s->term, "") == 0) {
1255 /* Allocate a pty and open it. */
1256 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1261 error("session_pty_req: session %d alloc failed", s->self);
1265 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1267 * Add a cleanup function to clear the utmp entry and record logout
1268 * time in case we call fatal() (e.g., the connection gets closed).
1270 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1271 pty_setowner(s->pw, s->tty);
1272 /* Get window size from the packet. */
1273 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1275 session_proctitle(s);
1277 /* XXX parse and set terminal modes */
1283 session_subsystem_req(Session *s)
1287 char *subsys = packet_get_string(&len);
1290 log("subsystem request for %s", subsys);
1297 session_x11_req(Session *s)
1299 if (!options.x11_forwarding) {
1300 debug("X11 forwarding disabled in server configuration file.");
1303 if (xauthfile != NULL) {
1304 debug("X11 fwd already started.");
1308 debug("Received request for X11 forwarding with auth spoofing.");
1309 if (s->display != NULL)
1310 packet_disconnect("Protocol error: X11 display already set.");
1312 s->single_connection = packet_get_char();
1313 s->auth_proto = packet_get_string(NULL);
1314 s->auth_data = packet_get_string(NULL);
1315 s->screen = packet_get_int();
1318 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1319 if (s->display == NULL) {
1320 xfree(s->auth_proto);
1321 xfree(s->auth_data);
1324 xauthfile = xmalloc(MAXPATHLEN);
1325 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1326 temporarily_use_uid(s->pw->pw_uid);
1327 if (mkdtemp(xauthfile) == NULL) {
1329 error("private X11 dir: mkdtemp %s failed: %s",
1330 xauthfile, strerror(errno));
1333 xfree(s->auth_proto);
1334 xfree(s->auth_data);
1335 /* XXXX remove listening channels */
1338 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1339 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1341 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1346 session_input_channel_req(int id, void *arg)
1355 rtype = packet_get_string(&len);
1356 reply = packet_get_char();
1358 s = session_by_channel(id);
1360 fatal("session_input_channel_req: channel %d: no session", id);
1361 c = channel_lookup(id);
1363 fatal("session_input_channel_req: channel %d: bad channel", id);
1365 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1366 s->self, id, rtype, reply);
1369 * a session is in LARVAL state until a shell
1370 * or programm is executed
1372 if (c->type == SSH_CHANNEL_LARVAL) {
1373 if (strcmp(rtype, "shell") == 0) {
1377 do_exec_no_pty(s, NULL, s->pw);
1379 do_exec_pty(s, NULL, s->pw);
1381 } else if (strcmp(rtype, "exec") == 0) {
1382 char *command = packet_get_string(&len);
1386 do_exec_no_pty(s, command, s->pw);
1388 do_exec_pty(s, command, s->pw);
1391 } else if (strcmp(rtype, "pty-req") == 0) {
1392 success = session_pty_req(s);
1393 } else if (strcmp(rtype, "x11-req") == 0) {
1394 success = session_x11_req(s);
1395 } else if (strcmp(rtype, "subsystem") == 0) {
1396 success = session_subsystem_req(s);
1399 if (strcmp(rtype, "window-change") == 0) {
1400 success = session_window_change_req(s);
1404 packet_start(success ?
1405 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1406 packet_put_int(c->remote_id);
1413 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1416 fatal("session_set_fds: called for proto != 2.0");
1418 * now that have a child and a pipe to the child,
1419 * we can activate our channel and register the fd's
1421 if (s->chanid == -1)
1422 fatal("no channel for session %d", s->self);
1423 channel_set_fds(s->chanid,
1425 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1429 session_pty_cleanup(Session *s)
1431 if (s == NULL || s->ttyfd == -1)
1434 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1436 /* Cancel the cleanup function. */
1437 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1439 /* Record that the user has logged out. */
1440 record_logout(s->pid, s->tty);
1442 /* Release the pseudo-tty. */
1443 pty_release(s->tty);
1446 * Close the server side of the socket pairs. We must do this after
1447 * the pty cleanup, so that another process doesn't get this pty
1448 * while we're still cleaning up.
1450 if (close(s->ptymaster) < 0)
1451 error("close(s->ptymaster): %s", strerror(errno));
1455 session_exit_message(Session *s, int status)
1459 fatal("session_close: no session");
1460 c = channel_lookup(s->chanid);
1462 fatal("session_close: session %d: no channel %d",
1463 s->self, s->chanid);
1464 debug("session_exit_message: session %d channel %d pid %d",
1465 s->self, s->chanid, s->pid);
1467 if (WIFEXITED(status)) {
1468 channel_request_start(s->chanid,
1470 packet_put_int(WEXITSTATUS(status));
1472 } else if (WIFSIGNALED(status)) {
1473 channel_request_start(s->chanid,
1475 packet_put_int(WTERMSIG(status));
1477 packet_put_char(WCOREDUMP(status));
1478 #else /* WCOREDUMP */
1480 #endif /* WCOREDUMP */
1481 packet_put_cstring("");
1482 packet_put_cstring("");
1485 /* Some weird exit cause. Just exit. */
1486 packet_disconnect("wait returned status %04x.", status);
1489 /* disconnect channel */
1490 debug("session_exit_message: release channel %d", s->chanid);
1491 channel_cancel_cleanup(s->chanid);
1493 * emulate a write failure with 'chan_write_failed', nobody will be
1494 * interested in data we write.
1495 * Note that we must not call 'chan_read_failed', since there could
1496 * be some more data waiting in the pipe.
1498 if (c->ostate != CHAN_OUTPUT_CLOSED)
1499 chan_write_failed(c);
1504 session_free(Session *s)
1506 debug("session_free: session %d pid %d", s->self, s->pid);
1512 xfree(s->auth_data);
1514 xfree(s->auth_proto);
1519 session_close(Session *s)
1521 session_pty_cleanup(s);
1523 session_proctitle(s);
1527 session_close_by_pid(pid_t pid, int status)
1529 Session *s = session_by_pid(pid);
1531 debug("session_close_by_pid: no session for pid %d", s->pid);
1534 if (s->chanid != -1)
1535 session_exit_message(s, status);
1540 * this is called when a channel dies before
1541 * the session 'child' itself dies
1544 session_close_by_channel(int id, void *arg)
1546 Session *s = session_by_channel(id);
1548 debug("session_close_by_channel: no session for channel %d", id);
1551 /* disconnect channel */
1552 channel_cancel_cleanup(s->chanid);
1555 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1557 /* close session immediately */
1560 /* notify child, delay session cleanup */
1561 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1562 error("session_close_by_channel: kill %d: %s",
1563 s->pid, strerror(errno));
1568 session_tty_list(void)
1570 static char buf[1024];
1573 for(i = 0; i < MAX_SESSIONS; i++) {
1574 Session *s = &sessions[i];
1575 if (s->used && s->ttyfd != -1) {
1577 strlcat(buf, ",", sizeof buf);
1578 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1582 strlcpy(buf, "notty", sizeof buf);
1587 session_proctitle(Session *s)
1590 error("no user for session %d", s->self);
1592 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1596 do_authenticated2(void)
1599 * Cancel the alarm we set to limit the time taken for
1605 xauthfile_cleanup_proc(NULL);