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"
31 #ifdef WITH_IRIX_PROJECT
33 #endif /* WITH_IRIX_PROJECT */
43 typedef struct Session Session;
52 int ptyfd, ttyfd, ptymaster;
53 int row, col, xpixel, ypixel;
60 int single_connection;
67 Session *session_new(void);
68 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
69 void session_pty_cleanup(Session *s);
70 void session_proctitle(Session *s);
71 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
72 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
75 do_child(const char *command, struct passwd * pw, const char *term,
76 const char *display, const char *auth_proto,
77 const char *auth_data, const char *ttyname);
80 extern ServerOptions options;
81 #ifdef HAVE___PROGNAME
82 extern char *__progname;
83 #else /* HAVE___PROGNAME */
84 static const char *__progname = "sshd";
85 #endif /* HAVE___PROGNAME */
87 extern int log_stderr;
88 extern int debug_flag;
90 /* Local Xauthority file. */
91 static char *xauthfile;
94 #define MAX_SESSIONS 10
95 Session sessions[MAX_SESSIONS];
96 #ifdef WITH_AIXAUTHENTICATE
97 /* AIX's lastlogin message, set in auth1.c */
99 #endif /* WITH_AIXAUTHENTICATE */
102 * Remove local Xauthority file.
105 xauthfile_cleanup_proc(void *ignore)
107 debug("xauthfile_cleanup_proc called");
109 if (xauthfile != NULL) {
112 p = strrchr(xauthfile, '/');
123 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
124 * dropped connection).
127 pty_cleanup_proc(void *session)
131 fatal("pty_cleanup_proc: no session");
132 debug("pty_cleanup_proc: %s", s->tty);
135 /* Record that the user has logged out. */
136 record_logout(s->pid, s->tty);
139 /* Release the pseudo-tty. */
144 * Prepares for an interactive session. This is called after the user has
145 * been successfully authenticated. During this message exchange, pseudo
146 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
147 * are requested, etc.
150 do_authenticated(struct passwd * pw)
154 int compression_level = 0, enable_compression_after_reply = 0;
159 unsigned int proto_len, data_len, dlen;
162 * Cancel the alarm we set to limit the time taken for
168 * Inform the channel mechanism that we are the server side and that
169 * the client may request to connect to any port at all. (The user
170 * could do it anyway, and we wouldn\'t know what is permitted except
171 * by the client telling us, so we can equally well trust the client
172 * not to request anything bogus.)
174 if (!no_port_forwarding_flag)
175 channel_permit_all_opens();
181 * We stay in this loop until the client requests to execute a shell
187 /* Get a packet from the client. */
188 type = packet_read(&plen);
190 /* Process the packet. */
192 case SSH_CMSG_REQUEST_COMPRESSION:
193 packet_integrity_check(plen, 4, type);
194 compression_level = packet_get_int();
195 if (compression_level < 1 || compression_level > 9) {
196 packet_send_debug("Received illegal compression level %d.",
200 /* Enable compression after we have responded with SUCCESS. */
201 enable_compression_after_reply = 1;
205 case SSH_CMSG_REQUEST_PTY:
207 debug("Allocating a pty not permitted for this authentication.");
211 packet_disconnect("Protocol error: you already have a pty.");
213 debug("Allocating pty.");
215 /* Allocate a pty and open it. */
216 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
218 error("Failed to allocate pty.");
221 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
222 pty_setowner(pw, s->tty);
224 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
225 s->term = packet_get_string(&dlen);
226 packet_integrity_check(dlen, strlen(s->term), type);
227 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
228 /* Remaining bytes */
229 n_bytes = plen - (4 + dlen + 4 * 4);
231 if (strcmp(s->term, "") == 0) {
235 /* Get window size from the packet. */
236 s->row = packet_get_int();
237 s->col = packet_get_int();
238 s->xpixel = packet_get_int();
239 s->ypixel = packet_get_int();
240 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
242 /* Get tty modes from the packet. */
243 tty_parse_modes(s->ttyfd, &n_bytes);
244 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
246 session_proctitle(s);
248 /* Indicate that we now have a pty. */
253 case SSH_CMSG_X11_REQUEST_FORWARDING:
254 if (!options.x11_forwarding) {
255 packet_send_debug("X11 forwarding disabled in server configuration file.");
258 if (!options.xauth_location) {
259 packet_send_debug("No xauth program; cannot forward with spoofing.");
262 if (no_x11_forwarding_flag) {
263 packet_send_debug("X11 forwarding not permitted for this authentication.");
266 debug("Received request for X11 forwarding with auth spoofing.");
267 if (s->display != NULL)
268 packet_disconnect("Protocol error: X11 display already set.");
270 s->auth_proto = packet_get_string(&proto_len);
271 s->auth_data = packet_get_string(&data_len);
272 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
274 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
275 s->screen = packet_get_int();
278 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
280 if (s->display == NULL)
283 /* Setup to always have a local .Xauthority. */
284 xauthfile = xmalloc(MAXPATHLEN);
285 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
286 temporarily_use_uid(pw->pw_uid);
287 if (mkdtemp(xauthfile) == NULL) {
289 error("private X11 dir: mkdtemp %s failed: %s",
290 xauthfile, strerror(errno));
293 /* XXXX remove listening channels */
296 strlcat(xauthfile, "/cookies", MAXPATHLEN);
297 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
299 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
303 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
304 if (no_agent_forwarding_flag || compat13) {
305 debug("Authentication agent forwarding not permitted for this authentication.");
308 debug("Received authentication agent forwarding request.");
309 success = auth_input_request_forwarding(pw);
312 case SSH_CMSG_PORT_FORWARD_REQUEST:
313 if (no_port_forwarding_flag) {
314 debug("Port forwarding not permitted for this authentication.");
317 debug("Received TCP/IP port forwarding request.");
318 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
322 case SSH_CMSG_MAX_PACKET_SIZE:
323 if (packet_set_maxsize(packet_get_int()) > 0)
327 case SSH_CMSG_EXEC_SHELL:
328 case SSH_CMSG_EXEC_CMD:
329 /* Set interactive/non-interactive mode. */
330 packet_set_interactive(have_pty || s->display != NULL,
333 if (type == SSH_CMSG_EXEC_CMD) {
334 command = packet_get_string(&dlen);
335 debug("Exec command '%.500s'", command);
336 packet_integrity_check(plen, 4 + dlen, type);
339 packet_integrity_check(plen, 0, type);
341 if (forced_command != NULL) {
342 command = forced_command;
343 debug("Forced command '%.500s'", forced_command);
346 do_exec_pty(s, command, pw);
348 do_exec_no_pty(s, command, pw);
352 /* Cleanup user's local Xauthority file. */
354 xauthfile_cleanup_proc(NULL);
359 * Any unknown messages in this phase are ignored,
360 * and a failure message is returned.
362 log("Unknown packet type received after authentication: %d", type);
364 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
368 /* Enable compression now that we have replied if appropriate. */
369 if (enable_compression_after_reply) {
370 enable_compression_after_reply = 0;
371 packet_start_compression(compression_level);
377 * This is called to fork and execute a command when we have no tty. This
378 * will call do_child from the child, and server_loop from the parent after
379 * setting up file descriptors and such.
382 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
387 int pin[2], pout[2], perr[2];
388 /* Allocate pipes for communicating with the program. */
389 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
390 packet_disconnect("Could not create pipes: %.100s",
392 #else /* USE_PIPES */
393 int inout[2], err[2];
394 /* Uses socket pairs to communicate with the program. */
395 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
396 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
397 packet_disconnect("Could not create socket pairs: %.100s",
399 #endif /* USE_PIPES */
401 fatal("do_exec_no_pty: no session");
403 session_proctitle(s);
409 /* Fork the child. */
410 if ((pid = fork()) == 0) {
411 /* Child. Reinitialize the log since the pid has changed. */
412 log_init(__progname, options.log_level, options.log_facility, log_stderr);
415 * Create a new session and process group since the 4.4BSD
416 * setlogin() affects the entire process group.
419 error("setsid failed: %.100s", strerror(errno));
423 * Redirect stdin. We close the parent side of the socket
424 * pair, and make the child side the standard input.
427 if (dup2(pin[0], 0) < 0)
428 perror("dup2 stdin");
431 /* Redirect stdout. */
433 if (dup2(pout[1], 1) < 0)
434 perror("dup2 stdout");
437 /* Redirect stderr. */
439 if (dup2(perr[1], 2) < 0)
440 perror("dup2 stderr");
442 #else /* USE_PIPES */
444 * Redirect stdin, stdout, and stderr. Stdin and stdout will
445 * use the same socket, as some programs (particularly rdist)
446 * seem to depend on it.
450 if (dup2(inout[0], 0) < 0) /* stdin */
451 perror("dup2 stdin");
452 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
453 perror("dup2 stdout");
454 if (dup2(err[0], 2) < 0) /* stderr */
455 perror("dup2 stderr");
456 #endif /* USE_PIPES */
458 /* Do processing for the child (exec command etc). */
459 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
463 packet_disconnect("fork failed: %.100s", strerror(errno));
466 /* We are the parent. Close the child sides of the pipes. */
472 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
474 /* Enter the interactive session. */
475 server_loop(pid, pin[1], pout[0], perr[0]);
476 /* server_loop has closed pin[1], pout[1], and perr[1]. */
478 #else /* USE_PIPES */
479 /* We are the parent. Close the child sides of the socket pairs. */
484 * Enter the interactive session. Note: server_loop must be able to
485 * handle the case that fdin and fdout are the same.
488 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
490 server_loop(pid, inout[1], inout[1], err[1]);
491 /* server_loop has closed inout[1] and err[1]. */
493 #endif /* USE_PIPES */
497 * This is called to fork and execute a command when we have a tty. This
498 * will call do_child from the child, and server_loop from the parent after
499 * setting up file descriptors, controlling tty, updating wtmp, utmp,
500 * lastlog, and other such operations.
503 do_exec_pty(Session *s, const char *command, struct passwd * pw)
506 char buf[100], *time_string;
508 const char *hostname;
509 int fdout, ptyfd, ttyfd, ptymaster;
513 struct sockaddr_storage from;
515 time_t last_login_time;
518 fatal("do_exec_pty: no session");
522 /* Get remote host name. */
523 hostname = get_canonical_hostname();
526 * Get the time when the user last logged in. Buf will be set to
527 * contain the hostname the last login was from.
529 if (!options.use_login) {
530 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
535 do_pam_session(pw->pw_name, s->tty);
539 /* Fork the child. */
540 if ((pid = fork()) == 0) {
543 /* Child. Reinitialize the log because the pid has
545 log_init(__progname, options.log_level, options.log_facility, log_stderr);
547 /* Close the master side of the pseudo tty. */
550 /* Make the pseudo tty our controlling tty. */
551 pty_make_controlling_tty(&ttyfd, s->tty);
553 /* Redirect stdin from the pseudo tty. */
554 if (dup2(ttyfd, fileno(stdin)) < 0)
555 error("dup2 stdin failed: %.100s", strerror(errno));
557 /* Redirect stdout to the pseudo tty. */
558 if (dup2(ttyfd, fileno(stdout)) < 0)
559 error("dup2 stdin failed: %.100s", strerror(errno));
561 /* Redirect stderr to the pseudo tty. */
562 if (dup2(ttyfd, fileno(stderr)) < 0)
563 error("dup2 stdin failed: %.100s", strerror(errno));
565 /* Close the extra descriptor for the pseudo tty. */
568 /* XXXX ? move to do_child() ??*/
570 * Get IP address of client. This is needed because we want
571 * to record where the user logged in from. If the
572 * connection is not a socket, let the ip address be 0.0.0.0.
574 memset(&from, 0, sizeof(from));
575 if (packet_connection_is_on_socket()) {
576 fromlen = sizeof(from);
577 if (getpeername(packet_get_connection_in(),
578 (struct sockaddr *) & from, &fromlen) < 0) {
579 debug("getpeername: %.100s", strerror(errno));
583 /* Record that there was a login on that terminal. */
584 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
585 (struct sockaddr *)&from);
587 /* Check if .hushlogin exists. */
588 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
589 quiet_login = stat(line, &st) >= 0;
593 print_pam_messages();
597 * If the user has logged in before, display the time of last
598 * login. However, don't display anything extra if a command
599 * has been specified (so that ssh can be used to execute
600 * commands on a remote machine without users knowing they
601 * are going to another machine). Login(1) will do this for
602 * us as well, so check if login(1) is used
604 if (command == NULL && last_login_time != 0 && !quiet_login &&
605 !options.use_login) {
606 /* Convert the date to a string. */
607 time_string = ctime(&last_login_time);
608 /* Remove the trailing newline. */
609 if (strchr(time_string, '\n'))
610 *strchr(time_string, '\n') = 0;
611 /* Display the last login time. Host if displayed
613 if (strcmp(buf, "") == 0)
614 printf("Last login: %s\r\n", time_string);
616 printf("Last login: %s from %s\r\n", time_string, buf);
619 * Print /etc/motd unless a command was specified or printing
620 * it was disabled in server options or login(1) will be
621 * used. Note that some machines appear to print it in
622 * /etc/profile or similar.
624 if (command == NULL && options.print_motd && !quiet_login &&
625 !options.use_login) {
626 /* Print /etc/motd if it exists. */
627 f = fopen("/etc/motd", "r");
629 while (fgets(line, sizeof(line), f))
634 #if defined(WITH_AIXAUTHENTICATE)
636 * AIX handles the lastlog info differently. Display it here.
638 if (command == NULL && aixloginmsg && *aixloginmsg &&
639 !quiet_login && !options.use_login) {
640 printf("%s\n", aixloginmsg);
643 /* Do common processing for the child, such as execing the command. */
644 do_child(command, pw, s->term, s->display, s->auth_proto,
645 s->auth_data, s->tty);
649 packet_disconnect("fork failed: %.100s", strerror(errno));
652 /* Parent. Close the slave side of the pseudo tty. */
656 * Create another descriptor of the pty master side for use as the
657 * standard input. We could use the original descriptor, but this
658 * simplifies code in server_loop. The descriptor is bidirectional.
662 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
664 /* we keep a reference to the pty master */
665 ptymaster = dup(ptyfd);
667 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
668 s->ptymaster = ptymaster;
670 /* Enter interactive session. */
672 session_set_fds(s, ptyfd, fdout, -1);
674 server_loop(pid, ptyfd, fdout, -1);
675 /* server_loop _has_ closed ptyfd and fdout. */
676 session_pty_cleanup(s);
681 * Sets the value of the given variable in the environment. If the variable
682 * already exists, its value is overriden.
685 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
688 unsigned int i, namelen;
692 * Find the slot where the value should be stored. If the variable
693 * already exists, we reuse the slot; otherwise we append a new slot
694 * at the end of the array, expanding if necessary.
697 namelen = strlen(name);
698 for (i = 0; env[i]; i++)
699 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
702 /* Reuse the slot. */
705 /* New variable. Expand if necessary. */
706 if (i >= (*envsizep) - 1) {
708 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
710 /* Need to set the NULL pointer at end of array beyond the new slot. */
714 /* Allocate space and format the variable in the appropriate slot. */
715 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
716 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
720 * Reads environment variables from the given file and adds/overrides them
721 * into the environment. If the file does not exist, this does nothing.
722 * Otherwise, it must consist of empty lines, comments (line starts with '#')
723 * and assignments of the form name=value. No other forms are allowed.
726 read_environment_file(char ***env, unsigned int *envsize,
727 const char *filename)
733 f = fopen(filename, "r");
737 while (fgets(buf, sizeof(buf), f)) {
738 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
740 if (!*cp || *cp == '#' || *cp == '\n')
742 if (strchr(cp, '\n'))
743 *strchr(cp, '\n') = '\0';
744 value = strchr(cp, '=');
746 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
750 * Replace the equals sign by nul, and advance value to
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;
806 unsigned int envsize, i;
808 extern char **environ;
811 #ifdef WITH_IRIX_PROJECT
813 #endif /* WITH_IRIX_PROJECT */
815 /* login(1) is only called if we execute the login shell */
816 if (options.use_login && command != NULL)
817 options.use_login = 0;
819 #ifndef USE_PAM /* pam_nologin handles this */
820 f = fopen("/etc/nologin", "r");
822 /* /etc/nologin exists. Print its contents and exit. */
823 while (fgets(buf, sizeof(buf), f))
832 /* Set login name in the kernel. */
833 if (setlogin(pw->pw_name) < 0)
834 error("setlogin failed: %s", strerror(errno));
837 /* Set uid, gid, and groups. */
838 /* Login(1) does this as well, and it needs uid 0 for the "-h"
839 switch, so we let login(1) to this for us. */
840 if (!options.use_login) {
842 extern char **saved_argv;
843 extern int saved_argc;
844 char *host = get_canonical_hostname ();
846 if (sia_become_user(NULL, saved_argc, saved_argv, host,
847 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
849 perror("sia_become_user");
852 if (setreuid(geteuid(), geteuid()) < 0) {
856 #else /* HAVE_OSF_SIA */
857 if (getuid() == 0 || geteuid() == 0) {
858 if (setgid(pw->pw_gid) < 0) {
862 /* Initialize the group list. */
863 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
864 perror("initgroups");
869 #ifdef WITH_IRIX_ARRAY
870 /* initialize array session */
871 if (newarraysess() != 0)
872 fatal("Failed to set up new array session: %.100s",
874 #endif /* WITH_IRIX_ARRAY */
876 #ifdef WITH_IRIX_PROJECT
877 /* initialize irix project info */
878 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
879 debug("Failed to get project id, using projid 0");
884 fatal("Failed to initialize project %d for %s: %.100s",
885 (int)projid, pw->pw_name, strerror(errno));
886 #endif /* WITH_IRIX_PROJECT */
888 /* Permanently switch to the desired uid. */
889 permanently_set_uid(pw->pw_uid);
891 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
892 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
893 #endif /* HAVE_OSF_SIA */
896 * Get the shell from the password data. An empty shell field is
897 * legal, and means /bin/sh.
899 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
902 /* Try to get AFS tokens for the local cell. */
906 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
913 /* Initialize the environment. */
915 env = xmalloc(envsize * sizeof(char *));
918 if (!options.use_login) {
919 /* Set basic environment. */
920 child_set_env(&env, &envsize, "USER", pw->pw_name);
921 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
922 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
923 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
925 snprintf(buf, sizeof buf, "%.200s/%.50s",
926 _PATH_MAILDIR, pw->pw_name);
927 child_set_env(&env, &envsize, "MAIL", buf);
929 /* Normal systems set SHELL by default. */
930 child_set_env(&env, &envsize, "SHELL", shell);
933 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
935 /* Set custom environment options from RSA authentication. */
936 while (custom_environment) {
937 struct envstring *ce = custom_environment;
940 for (i = 0; s[i] != '=' && s[i]; i++);
943 child_set_env(&env, &envsize, s, s + i + 1);
945 custom_environment = ce->next;
950 snprintf(buf, sizeof buf, "%.50s %d %d",
951 get_remote_ipaddr(), get_remote_port(), get_local_port());
952 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
955 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
957 child_set_env(&env, &envsize, "TERM", term);
959 child_set_env(&env, &envsize, "DISPLAY", display);
963 char *authstate,*krb5cc;
965 if ((authstate = getenv("AUTHSTATE")) != NULL)
966 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
968 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
969 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
978 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
983 /* Pull in any environment variables that may have been set by PAM. */
984 do_pam_environment(&env, &envsize);
987 read_environment_file(&env,&envsize,"/etc/environment");
990 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
991 if (auth_get_socket_name() != NULL)
992 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
993 auth_get_socket_name());
995 /* read $HOME/.ssh/environment. */
996 if (!options.use_login) {
997 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
999 read_environment_file(&env, &envsize, buf);
1002 /* dump the environment */
1003 fprintf(stderr, "Environment:\n");
1004 for (i = 0; env[i]; i++)
1005 fprintf(stderr, " %.200s\n", env[i]);
1008 * Close the connection descriptors; note that this is the child, and
1009 * the server will still have the socket open, and it is important
1010 * that we do not shutdown it. Note that the descriptors cannot be
1011 * closed before building the environment, as we call
1012 * get_remote_ipaddr there.
1014 if (packet_get_connection_in() == packet_get_connection_out())
1015 close(packet_get_connection_in());
1017 close(packet_get_connection_in());
1018 close(packet_get_connection_out());
1021 * Close all descriptors related to channels. They will still remain
1022 * open in the parent.
1024 /* XXX better use close-on-exec? -markus */
1025 channel_close_all();
1028 * Close any extra file descriptors. Note that there may still be
1029 * descriptors left by system functions. They will be closed later.
1034 * Close any extra open file descriptors so that we don\'t have them
1035 * hanging around in clients. Note that we want to do this after
1036 * initgroups, because at least on Solaris 2.3 it leaves file
1039 for (i = 3; i < 64; i++)
1042 /* Change current directory to the user\'s home directory. */
1043 if (chdir(pw->pw_dir) < 0)
1044 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1045 pw->pw_dir, strerror(errno));
1048 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1049 * xauth are run in the proper environment.
1054 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1057 if (!options.use_login) {
1058 if (stat(SSH_USER_RC, &st) >= 0) {
1060 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1062 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1064 if (auth_proto != NULL && auth_data != NULL)
1065 fprintf(f, "%s %s\n", auth_proto, auth_data);
1068 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1069 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1071 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1073 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1075 if (auth_proto != NULL && auth_data != NULL)
1076 fprintf(f, "%s %s\n", auth_proto, auth_data);
1079 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1080 } else if (options.xauth_location != NULL) {
1081 /* Add authority data to .Xauthority if appropriate. */
1082 if (auth_proto != NULL && auth_data != NULL) {
1083 char *screen = strchr(display, ':');
1086 "Running %.100s add %.100s %.100s %.100s\n",
1087 options.xauth_location, display,
1088 auth_proto, auth_data);
1091 "Adding %.*s/unix%s %s %s\n",
1092 screen-display, display,
1093 screen, auth_proto, auth_data);
1095 snprintf(cmd, sizeof cmd, "%s -q -",
1096 options.xauth_location);
1097 f = popen(cmd, "w");
1099 fprintf(f, "add %s %s %s\n", display,
1100 auth_proto, auth_data);
1102 fprintf(f, "add %.*s/unix%s %s %s\n",
1103 screen-display, display,
1104 screen, auth_proto, auth_data);
1107 fprintf(stderr, "Could not run %s\n",
1112 /* Get the last component of the shell name. */
1113 cp = strrchr(shell, '/');
1120 * If we have no command, execute the shell. In this case, the shell
1121 * name to be passed in argv[0] is preceded by '-' to indicate that
1122 * this is a login shell.
1125 if (!options.use_login) {
1129 * Check for mail if we have a tty and it was enabled
1130 * in server options.
1132 if (ttyname && options.check_mail) {
1134 struct stat mailstat;
1135 mailbox = getenv("MAIL");
1136 if (mailbox != NULL) {
1137 if (stat(mailbox, &mailstat) != 0 ||
1138 mailstat.st_size == 0)
1139 printf("No mail.\n");
1140 else if (mailstat.st_mtime < mailstat.st_atime)
1141 printf("You have mail.\n");
1143 printf("You have new mail.\n");
1146 /* Start the shell. Set initial character to '-'. */
1148 strncpy(buf + 1, cp, sizeof(buf) - 1);
1149 buf[sizeof(buf) - 1] = 0;
1151 /* Execute the shell. */
1154 execve(shell, argv, env);
1156 /* Executing the shell failed. */
1161 /* Launch login(1). */
1163 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
1164 "-p", "-f", "--", pw->pw_name, NULL);
1166 /* Login couldn't be executed, die. */
1173 * Execute the command using the user's shell. This uses the -c
1174 * option to execute the command.
1176 argv[0] = (char *) cp;
1178 argv[2] = (char *) command;
1180 execve(shell, argv, env);
1189 static int did_init = 0;
1191 debug("session_new: init");
1192 for(i = 0; i < MAX_SESSIONS; i++) {
1193 sessions[i].used = 0;
1194 sessions[i].self = i;
1198 for(i = 0; i < MAX_SESSIONS; i++) {
1199 Session *s = &sessions[i];
1210 s->auth_data = NULL;
1211 s->auth_proto = NULL;
1214 debug("session_new: session %d", i);
1225 for(i = 0; i < MAX_SESSIONS; i++) {
1226 Session *s = &sessions[i];
1227 debug("dump: used %d session %d %p channel %d pid %d",
1237 session_open(int chanid)
1239 Session *s = session_new();
1240 debug("session_open: channel %d", chanid);
1242 error("no more sessions");
1245 s->pw = auth_get_user();
1247 fatal("no user for session %i", s->self);
1248 debug("session_open: session %d: link with channel %d", s->self, chanid);
1254 session_by_channel(int id)
1257 for(i = 0; i < MAX_SESSIONS; i++) {
1258 Session *s = &sessions[i];
1259 if (s->used && s->chanid == id) {
1260 debug("session_by_channel: session %d channel %d", i, id);
1264 debug("session_by_channel: unknown channel %d", id);
1270 session_by_pid(pid_t pid)
1273 debug("session_by_pid: pid %d", pid);
1274 for(i = 0; i < MAX_SESSIONS; i++) {
1275 Session *s = &sessions[i];
1276 if (s->used && s->pid == pid)
1279 error("session_by_pid: unknown pid %d", pid);
1285 session_window_change_req(Session *s)
1287 s->col = packet_get_int();
1288 s->row = packet_get_int();
1289 s->xpixel = packet_get_int();
1290 s->ypixel = packet_get_int();
1292 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1297 session_pty_req(Session *s)
1300 char *term_modes; /* encoded terminal modes */
1306 s->term = packet_get_string(&len);
1307 s->col = packet_get_int();
1308 s->row = packet_get_int();
1309 s->xpixel = packet_get_int();
1310 s->ypixel = packet_get_int();
1311 term_modes = packet_get_string(&len);
1314 if (strcmp(s->term, "") == 0) {
1318 /* Allocate a pty and open it. */
1319 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1324 error("session_pty_req: session %d alloc failed", s->self);
1328 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1330 * Add a cleanup function to clear the utmp entry and record logout
1331 * time in case we call fatal() (e.g., the connection gets closed).
1333 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1334 pty_setowner(s->pw, s->tty);
1335 /* Get window size from the packet. */
1336 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1338 session_proctitle(s);
1340 /* XXX parse and set terminal modes */
1346 session_subsystem_req(Session *s)
1350 char *subsys = packet_get_string(&len);
1354 log("subsystem request for %s", subsys);
1356 for (i = 0; i < options.num_subsystems; i++) {
1357 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1358 debug("subsystem: exec() %s", options.subsystem_command[i]);
1359 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1365 log("subsystem request for %s failed, subsystem not found", subsys);
1372 session_x11_req(Session *s)
1374 if (!no_port_forwarding_flag) {
1375 debug("X11 forwarding disabled in user configuration file.");
1378 if (!options.x11_forwarding) {
1379 debug("X11 forwarding disabled in server configuration file.");
1382 if (xauthfile != NULL) {
1383 debug("X11 fwd already started.");
1387 debug("Received request for X11 forwarding with auth spoofing.");
1388 if (s->display != NULL)
1389 packet_disconnect("Protocol error: X11 display already set.");
1391 s->single_connection = packet_get_char();
1392 s->auth_proto = packet_get_string(NULL);
1393 s->auth_data = packet_get_string(NULL);
1394 s->screen = packet_get_int();
1397 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1398 if (s->display == NULL) {
1399 xfree(s->auth_proto);
1400 xfree(s->auth_data);
1403 xauthfile = xmalloc(MAXPATHLEN);
1404 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1405 temporarily_use_uid(s->pw->pw_uid);
1406 if (mkdtemp(xauthfile) == NULL) {
1408 error("private X11 dir: mkdtemp %s failed: %s",
1409 xauthfile, strerror(errno));
1412 xfree(s->auth_proto);
1413 xfree(s->auth_data);
1414 /* XXXX remove listening channels */
1417 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1418 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1420 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1425 session_shell_req(Session *s)
1427 /* if forced_command == NULL, the shell is execed */
1428 char *shell = forced_command;
1432 do_exec_no_pty(s, shell, s->pw);
1434 do_exec_pty(s, shell, s->pw);
1439 session_exec_req(Session *s)
1442 char *command = packet_get_string(&len);
1444 if (forced_command) {
1446 command = forced_command;
1447 debug("Forced command '%.500s'", forced_command);
1451 do_exec_no_pty(s, command, s->pw);
1453 do_exec_pty(s, command, s->pw);
1454 if (forced_command == NULL)
1460 session_input_channel_req(int id, void *arg)
1469 rtype = packet_get_string(&len);
1470 reply = packet_get_char();
1472 s = session_by_channel(id);
1474 fatal("session_input_channel_req: channel %d: no session", id);
1475 c = channel_lookup(id);
1477 fatal("session_input_channel_req: channel %d: bad channel", id);
1479 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1480 s->self, id, rtype, reply);
1483 * a session is in LARVAL state until a shell
1484 * or programm is executed
1486 if (c->type == SSH_CHANNEL_LARVAL) {
1487 if (strcmp(rtype, "shell") == 0) {
1488 success = session_shell_req(s);
1489 } else if (strcmp(rtype, "exec") == 0) {
1490 success = session_exec_req(s);
1491 } else if (strcmp(rtype, "pty-req") == 0) {
1492 success = session_pty_req(s);
1493 } else if (strcmp(rtype, "x11-req") == 0) {
1494 success = session_x11_req(s);
1495 } else if (strcmp(rtype, "subsystem") == 0) {
1496 success = session_subsystem_req(s);
1499 if (strcmp(rtype, "window-change") == 0) {
1500 success = session_window_change_req(s);
1504 packet_start(success ?
1505 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1506 packet_put_int(c->remote_id);
1513 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1516 fatal("session_set_fds: called for proto != 2.0");
1518 * now that have a child and a pipe to the child,
1519 * we can activate our channel and register the fd's
1521 if (s->chanid == -1)
1522 fatal("no channel for session %d", s->self);
1523 channel_set_fds(s->chanid,
1525 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1529 session_pty_cleanup(Session *s)
1531 if (s == NULL || s->ttyfd == -1)
1534 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1536 /* Cancel the cleanup function. */
1537 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1539 /* Record that the user has logged out. */
1540 record_logout(s->pid, s->tty);
1542 /* Release the pseudo-tty. */
1543 pty_release(s->tty);
1546 * Close the server side of the socket pairs. We must do this after
1547 * the pty cleanup, so that another process doesn't get this pty
1548 * while we're still cleaning up.
1550 if (close(s->ptymaster) < 0)
1551 error("close(s->ptymaster): %s", strerror(errno));
1555 session_exit_message(Session *s, int status)
1559 fatal("session_close: no session");
1560 c = channel_lookup(s->chanid);
1562 fatal("session_close: session %d: no channel %d",
1563 s->self, s->chanid);
1564 debug("session_exit_message: session %d channel %d pid %d",
1565 s->self, s->chanid, s->pid);
1567 if (WIFEXITED(status)) {
1568 channel_request_start(s->chanid,
1570 packet_put_int(WEXITSTATUS(status));
1572 } else if (WIFSIGNALED(status)) {
1573 channel_request_start(s->chanid,
1575 packet_put_int(WTERMSIG(status));
1577 packet_put_char(WCOREDUMP(status));
1578 #else /* WCOREDUMP */
1580 #endif /* WCOREDUMP */
1581 packet_put_cstring("");
1582 packet_put_cstring("");
1585 /* Some weird exit cause. Just exit. */
1586 packet_disconnect("wait returned status %04x.", status);
1589 /* disconnect channel */
1590 debug("session_exit_message: release channel %d", s->chanid);
1591 channel_cancel_cleanup(s->chanid);
1593 * emulate a write failure with 'chan_write_failed', nobody will be
1594 * interested in data we write.
1595 * Note that we must not call 'chan_read_failed', since there could
1596 * be some more data waiting in the pipe.
1598 if (c->ostate != CHAN_OUTPUT_CLOSED)
1599 chan_write_failed(c);
1604 session_free(Session *s)
1606 debug("session_free: session %d pid %d", s->self, s->pid);
1612 xfree(s->auth_data);
1614 xfree(s->auth_proto);
1619 session_close(Session *s)
1621 session_pty_cleanup(s);
1623 session_proctitle(s);
1627 session_close_by_pid(pid_t pid, int status)
1629 Session *s = session_by_pid(pid);
1631 debug("session_close_by_pid: no session for pid %d", s->pid);
1634 if (s->chanid != -1)
1635 session_exit_message(s, status);
1640 * this is called when a channel dies before
1641 * the session 'child' itself dies
1644 session_close_by_channel(int id, void *arg)
1646 Session *s = session_by_channel(id);
1648 debug("session_close_by_channel: no session for channel %d", id);
1651 /* disconnect channel */
1652 channel_cancel_cleanup(s->chanid);
1655 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1657 /* close session immediately */
1660 /* notify child, delay session cleanup */
1662 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1663 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1664 error("session_close_by_channel: kill %d: %s",
1665 s->pid, strerror(errno));
1670 session_tty_list(void)
1672 static char buf[1024];
1675 for(i = 0; i < MAX_SESSIONS; i++) {
1676 Session *s = &sessions[i];
1677 if (s->used && s->ttyfd != -1) {
1679 strlcat(buf, ",", sizeof buf);
1680 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1684 strlcpy(buf, "notty", sizeof buf);
1689 session_proctitle(Session *s)
1692 error("no user for session %d", s->self);
1694 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1698 do_authenticated2(void)
1701 * Cancel the alarm we set to limit the time taken for
1707 xauthfile_cleanup_proc(NULL);