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 $");
12 #if defined(HAVE_USERSEC_H)
32 #include "auth-options.h"
34 #ifdef WITH_IRIX_PROJECT
36 #endif /* WITH_IRIX_PROJECT */
46 typedef struct Session Session;
55 int ptyfd, ttyfd, ptymaster;
56 int row, col, xpixel, ypixel;
63 int single_connection;
70 Session *session_new(void);
71 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
72 void session_pty_cleanup(Session *s);
73 void session_proctitle(Session *s);
74 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
75 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
78 do_child(const char *command, struct passwd * pw, const char *term,
79 const char *display, const char *auth_proto,
80 const char *auth_data, const char *ttyname);
83 extern ServerOptions options;
84 #ifdef HAVE___PROGNAME
85 extern char *__progname;
86 #else /* HAVE___PROGNAME */
87 static const char *__progname = "sshd";
88 #endif /* HAVE___PROGNAME */
90 extern int log_stderr;
91 extern int debug_flag;
93 /* Local Xauthority file. */
94 static char *xauthfile;
97 #define MAX_SESSIONS 10
98 Session sessions[MAX_SESSIONS];
99 #ifdef WITH_AIXAUTHENTICATE
100 /* AIX's lastlogin message, set in auth1.c */
102 #endif /* WITH_AIXAUTHENTICATE */
105 * Remove local Xauthority file.
108 xauthfile_cleanup_proc(void *ignore)
110 debug("xauthfile_cleanup_proc called");
112 if (xauthfile != NULL) {
115 p = strrchr(xauthfile, '/');
126 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
127 * dropped connection).
130 pty_cleanup_proc(void *session)
134 fatal("pty_cleanup_proc: no session");
135 debug("pty_cleanup_proc: %s", s->tty);
138 /* Record that the user has logged out. */
139 record_logout(s->pid, s->tty);
142 /* Release the pseudo-tty. */
147 * Prepares for an interactive session. This is called after the user has
148 * been successfully authenticated. During this message exchange, pseudo
149 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
150 * are requested, etc.
153 do_authenticated(struct passwd * pw)
157 int compression_level = 0, enable_compression_after_reply = 0;
162 unsigned int proto_len, data_len, dlen;
165 * Cancel the alarm we set to limit the time taken for
171 * Inform the channel mechanism that we are the server side and that
172 * the client may request to connect to any port at all. (The user
173 * could do it anyway, and we wouldn\'t know what is permitted except
174 * by the client telling us, so we can equally well trust the client
175 * not to request anything bogus.)
177 if (!no_port_forwarding_flag)
178 channel_permit_all_opens();
184 * We stay in this loop until the client requests to execute a shell
190 /* Get a packet from the client. */
191 type = packet_read(&plen);
193 /* Process the packet. */
195 case SSH_CMSG_REQUEST_COMPRESSION:
196 packet_integrity_check(plen, 4, type);
197 compression_level = packet_get_int();
198 if (compression_level < 1 || compression_level > 9) {
199 packet_send_debug("Received illegal compression level %d.",
203 /* Enable compression after we have responded with SUCCESS. */
204 enable_compression_after_reply = 1;
208 case SSH_CMSG_REQUEST_PTY:
210 debug("Allocating a pty not permitted for this authentication.");
214 packet_disconnect("Protocol error: you already have a pty.");
216 debug("Allocating pty.");
218 /* Allocate a pty and open it. */
219 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
221 error("Failed to allocate pty.");
224 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
225 pty_setowner(pw, s->tty);
227 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
228 s->term = packet_get_string(&dlen);
229 packet_integrity_check(dlen, strlen(s->term), type);
230 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
231 /* Remaining bytes */
232 n_bytes = plen - (4 + dlen + 4 * 4);
234 if (strcmp(s->term, "") == 0) {
238 /* Get window size from the packet. */
239 s->row = packet_get_int();
240 s->col = packet_get_int();
241 s->xpixel = packet_get_int();
242 s->ypixel = packet_get_int();
243 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
245 /* Get tty modes from the packet. */
246 tty_parse_modes(s->ttyfd, &n_bytes);
247 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
249 session_proctitle(s);
251 /* Indicate that we now have a pty. */
256 case SSH_CMSG_X11_REQUEST_FORWARDING:
257 if (!options.x11_forwarding) {
258 packet_send_debug("X11 forwarding disabled in server configuration file.");
261 if (!options.xauth_location) {
262 packet_send_debug("No xauth program; cannot forward with spoofing.");
265 if (no_x11_forwarding_flag) {
266 packet_send_debug("X11 forwarding not permitted for this authentication.");
269 debug("Received request for X11 forwarding with auth spoofing.");
270 if (s->display != NULL)
271 packet_disconnect("Protocol error: X11 display already set.");
273 s->auth_proto = packet_get_string(&proto_len);
274 s->auth_data = packet_get_string(&data_len);
275 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
277 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
278 s->screen = packet_get_int();
281 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
283 if (s->display == NULL)
286 /* Setup to always have a local .Xauthority. */
287 xauthfile = xmalloc(MAXPATHLEN);
288 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
289 temporarily_use_uid(pw->pw_uid);
290 if (mkdtemp(xauthfile) == NULL) {
292 error("private X11 dir: mkdtemp %s failed: %s",
293 xauthfile, strerror(errno));
296 /* XXXX remove listening channels */
299 strlcat(xauthfile, "/cookies", MAXPATHLEN);
300 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
302 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
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 success = auth_input_request_forwarding(pw);
315 case SSH_CMSG_PORT_FORWARD_REQUEST:
316 if (no_port_forwarding_flag) {
317 debug("Port forwarding not permitted for this authentication.");
320 debug("Received TCP/IP port forwarding request.");
321 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
325 case SSH_CMSG_MAX_PACKET_SIZE:
326 if (packet_set_maxsize(packet_get_int()) > 0)
330 case SSH_CMSG_EXEC_SHELL:
331 case SSH_CMSG_EXEC_CMD:
332 /* Set interactive/non-interactive mode. */
333 packet_set_interactive(have_pty || s->display != NULL,
336 if (type == SSH_CMSG_EXEC_CMD) {
337 command = packet_get_string(&dlen);
338 debug("Exec command '%.500s'", command);
339 packet_integrity_check(plen, 4 + dlen, type);
342 packet_integrity_check(plen, 0, type);
344 if (forced_command != NULL) {
345 command = forced_command;
346 debug("Forced command '%.500s'", forced_command);
349 do_exec_pty(s, command, pw);
351 do_exec_no_pty(s, command, pw);
355 /* Cleanup user's local Xauthority file. */
357 xauthfile_cleanup_proc(NULL);
362 * Any unknown messages in this phase are ignored,
363 * and a failure message is returned.
365 log("Unknown packet type received after authentication: %d", type);
367 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
371 /* Enable compression now that we have replied if appropriate. */
372 if (enable_compression_after_reply) {
373 enable_compression_after_reply = 0;
374 packet_start_compression(compression_level);
380 * This is called to fork and execute a command when we have no tty. This
381 * will call do_child from the child, and server_loop from the parent after
382 * setting up file descriptors and such.
385 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
390 int pin[2], pout[2], perr[2];
391 /* Allocate pipes for communicating with the program. */
392 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
393 packet_disconnect("Could not create pipes: %.100s",
395 #else /* USE_PIPES */
396 int inout[2], err[2];
397 /* Uses socket pairs to communicate with the program. */
398 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
399 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
400 packet_disconnect("Could not create socket pairs: %.100s",
402 #endif /* USE_PIPES */
404 fatal("do_exec_no_pty: no session");
406 session_proctitle(s);
412 /* Fork the child. */
413 if ((pid = fork()) == 0) {
414 /* Child. Reinitialize the log since the pid has changed. */
415 log_init(__progname, options.log_level, options.log_facility, log_stderr);
418 * Create a new session and process group since the 4.4BSD
419 * setlogin() affects the entire process group.
422 error("setsid failed: %.100s", strerror(errno));
426 * Redirect stdin. We close the parent side of the socket
427 * pair, and make the child side the standard input.
430 if (dup2(pin[0], 0) < 0)
431 perror("dup2 stdin");
434 /* Redirect stdout. */
436 if (dup2(pout[1], 1) < 0)
437 perror("dup2 stdout");
440 /* Redirect stderr. */
442 if (dup2(perr[1], 2) < 0)
443 perror("dup2 stderr");
445 #else /* USE_PIPES */
447 * Redirect stdin, stdout, and stderr. Stdin and stdout will
448 * use the same socket, as some programs (particularly rdist)
449 * seem to depend on it.
453 if (dup2(inout[0], 0) < 0) /* stdin */
454 perror("dup2 stdin");
455 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
456 perror("dup2 stdout");
457 if (dup2(err[0], 2) < 0) /* stderr */
458 perror("dup2 stderr");
459 #endif /* USE_PIPES */
461 /* Do processing for the child (exec command etc). */
462 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
466 packet_disconnect("fork failed: %.100s", strerror(errno));
469 /* We are the parent. Close the child sides of the pipes. */
475 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
477 /* Enter the interactive session. */
478 server_loop(pid, pin[1], pout[0], perr[0]);
479 /* server_loop has closed pin[1], pout[1], and perr[1]. */
481 #else /* USE_PIPES */
482 /* We are the parent. Close the child sides of the socket pairs. */
487 * Enter the interactive session. Note: server_loop must be able to
488 * handle the case that fdin and fdout are the same.
491 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
493 server_loop(pid, inout[1], inout[1], err[1]);
494 /* server_loop has closed inout[1] and err[1]. */
496 #endif /* USE_PIPES */
500 * This is called to fork and execute a command when we have a tty. This
501 * will call do_child from the child, and server_loop from the parent after
502 * setting up file descriptors, controlling tty, updating wtmp, utmp,
503 * lastlog, and other such operations.
506 do_exec_pty(Session *s, const char *command, struct passwd * pw)
509 char buf[100], *time_string;
511 const char *hostname;
512 int fdout, ptyfd, ttyfd, ptymaster;
516 struct sockaddr_storage from;
518 time_t last_login_time;
521 fatal("do_exec_pty: no session");
525 /* Get remote host name. */
526 hostname = get_canonical_hostname();
529 * Get the time when the user last logged in. Buf will be set to
530 * contain the hostname the last login was from.
532 if (!options.use_login) {
533 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
538 do_pam_session(pw->pw_name, s->tty);
542 /* Fork the child. */
543 if ((pid = fork()) == 0) {
546 /* Child. Reinitialize the log because the pid has
548 log_init(__progname, options.log_level, options.log_facility, log_stderr);
550 /* Close the master side of the pseudo tty. */
553 /* Make the pseudo tty our controlling tty. */
554 pty_make_controlling_tty(&ttyfd, s->tty);
556 /* Redirect stdin from the pseudo tty. */
557 if (dup2(ttyfd, fileno(stdin)) < 0)
558 error("dup2 stdin failed: %.100s", strerror(errno));
560 /* Redirect stdout to the pseudo tty. */
561 if (dup2(ttyfd, fileno(stdout)) < 0)
562 error("dup2 stdin failed: %.100s", strerror(errno));
564 /* Redirect stderr to the pseudo tty. */
565 if (dup2(ttyfd, fileno(stderr)) < 0)
566 error("dup2 stdin failed: %.100s", strerror(errno));
568 /* Close the extra descriptor for the pseudo tty. */
571 /* XXXX ? move to do_child() ??*/
573 * Get IP address of client. This is needed because we want
574 * to record where the user logged in from. If the
575 * connection is not a socket, let the ip address be 0.0.0.0.
577 memset(&from, 0, sizeof(from));
578 if (packet_connection_is_on_socket()) {
579 fromlen = sizeof(from);
580 if (getpeername(packet_get_connection_in(),
581 (struct sockaddr *) & from, &fromlen) < 0) {
582 debug("getpeername: %.100s", strerror(errno));
586 /* Record that there was a login on that terminal. */
587 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
588 (struct sockaddr *)&from);
590 /* Check if .hushlogin exists. */
591 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
592 quiet_login = stat(line, &st) >= 0;
596 print_pam_messages();
600 * If the user has logged in before, display the time of last
601 * login. However, don't display anything extra if a command
602 * has been specified (so that ssh can be used to execute
603 * commands on a remote machine without users knowing they
604 * are going to another machine). Login(1) will do this for
605 * us as well, so check if login(1) is used
607 if (command == NULL && last_login_time != 0 && !quiet_login &&
608 !options.use_login) {
609 /* Convert the date to a string. */
610 time_string = ctime(&last_login_time);
611 /* Remove the trailing newline. */
612 if (strchr(time_string, '\n'))
613 *strchr(time_string, '\n') = 0;
614 /* Display the last login time. Host if displayed
616 if (strcmp(buf, "") == 0)
617 printf("Last login: %s\r\n", time_string);
619 printf("Last login: %s from %s\r\n", time_string, buf);
622 * Print /etc/motd unless a command was specified or printing
623 * it was disabled in server options or login(1) will be
624 * used. Note that some machines appear to print it in
625 * /etc/profile or similar.
627 if (command == NULL && options.print_motd && !quiet_login &&
628 !options.use_login) {
629 /* Print /etc/motd if it exists. */
630 f = fopen("/etc/motd", "r");
632 while (fgets(line, sizeof(line), f))
637 #if defined(WITH_AIXAUTHENTICATE)
639 * AIX handles the lastlog info differently. Display it here.
641 if (command == NULL && aixloginmsg && *aixloginmsg &&
642 !quiet_login && !options.use_login) {
643 printf("%s\n", aixloginmsg);
646 /* Do common processing for the child, such as execing the command. */
647 do_child(command, pw, s->term, s->display, s->auth_proto,
648 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);
753 * Replace the equals sign by nul, and advance value to
758 child_set_env(env, envsize, cp, value);
765 * Sets any environment variables which have been specified by PAM
767 void do_pam_environment(char ***env, int *envsize)
769 char *equals, var_name[512], var_val[512];
773 if ((pam_env = fetch_pam_environment()) == NULL)
776 for(i = 0; pam_env[i] != NULL; i++) {
777 if ((equals = strstr(pam_env[i], "=")) == NULL)
780 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
781 memset(var_name, '\0', sizeof(var_name));
782 memset(var_val, '\0', sizeof(var_val));
784 strncpy(var_name, pam_env[i], equals - pam_env[i]);
785 strcpy(var_val, equals + 1);
787 debug("PAM environment: %s=%s", var_name, var_val);
789 child_set_env(env, envsize, var_name, var_val);
795 #if defined(HAVE_GETUSERATTR)
797 * AIX-specific login initialisation
799 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
804 getrlimit(resource, &rlim);
807 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
809 rlim.rlim_cur = RLIM_INFINITY;
810 } else if (slim != 0) {
811 /* See the wackiness below */
812 if (rlim.rlim_cur == slim * mult)
815 rlim.rlim_cur = slim * mult;
820 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
822 rlim.rlim_max = RLIM_INFINITY;
823 } else if (hlim != 0) {
824 rlim.rlim_max = hlim * mult;
829 * XXX For cpu and fsize the soft limit is set to the hard limit
830 * if the hard limit is left at its default value and the soft limit
831 * is changed from its default value, either by requesting it
832 * (slim == 0) or by setting it to the current default. At least
833 * that's how rlogind does it. If you're confused you're not alone.
834 * Bug or feature? AIX 4.3.1.2
836 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
837 && hlim == 0 && slim != 0)
838 rlim.rlim_max = rlim.rlim_cur;
839 /* A specified hard limit limits the soft limit */
840 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
841 rlim.rlim_cur = rlim.rlim_max;
842 /* A soft limit can increase a hard limit */
843 else if (rlim.rlim_cur > rlim.rlim_max)
844 rlim.rlim_max = rlim.rlim_cur;
846 if (setrlimit(resource, &rlim) != 0)
847 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
850 void set_limits_from_userattr(char *user)
855 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
856 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
857 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
858 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
859 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
860 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
861 #if defined(S_UNOFILE)
862 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
865 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
866 /* Convert decimal to octal */
867 (void) snprintf(buf, sizeof(buf), "%d", mask);
868 if (sscanf(buf, "%o", &mask) == 1)
872 #endif /* defined(HAVE_GETUSERATTR) */
875 * Performs common processing for the child, such as setting up the
876 * environment, closing extra file descriptors, setting the user and group
877 * ids, and executing the command or shell.
880 do_child(const char *command, struct passwd * pw, const char *term,
881 const char *display, const char *auth_proto,
882 const char *auth_data, const char *ttyname)
884 const char *shell, *cp = NULL;
888 unsigned int envsize, i;
890 extern char **environ;
893 #ifdef WITH_IRIX_PROJECT
895 #endif /* WITH_IRIX_PROJECT */
897 /* login(1) is only called if we execute the login shell */
898 if (options.use_login && command != NULL)
899 options.use_login = 0;
901 #ifndef USE_PAM /* pam_nologin handles this */
902 f = fopen("/etc/nologin", "r");
904 /* /etc/nologin exists. Print its contents and exit. */
905 while (fgets(buf, sizeof(buf), f))
914 /* Set login name in the kernel. */
915 if (setlogin(pw->pw_name) < 0)
916 error("setlogin failed: %s", strerror(errno));
919 /* Set uid, gid, and groups. */
920 /* Login(1) does this as well, and it needs uid 0 for the "-h"
921 switch, so we let login(1) to this for us. */
922 if (!options.use_login) {
924 extern char **saved_argv;
925 extern int saved_argc;
926 char *host = get_canonical_hostname ();
928 if (sia_become_user(NULL, saved_argc, saved_argv, host,
929 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
931 perror("sia_become_user");
934 if (setreuid(geteuid(), geteuid()) < 0) {
938 #else /* HAVE_OSF_SIA */
939 if (getuid() == 0 || geteuid() == 0) {
940 #if defined(HAVE_GETUSERATTR)
941 set_limits_from_userattr(pw->pw_name);
942 #endif /* defined(HAVE_GETUSERATTR) */
944 if (setgid(pw->pw_gid) < 0) {
948 /* Initialize the group list. */
949 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
950 perror("initgroups");
955 #ifdef WITH_IRIX_ARRAY
956 /* initialize array session */
957 if (newarraysess() != 0)
958 fatal("Failed to set up new array session: %.100s",
960 #endif /* WITH_IRIX_ARRAY */
962 #ifdef WITH_IRIX_PROJECT
963 /* initialize irix project info */
964 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
965 debug("Failed to get project id, using projid 0");
970 fatal("Failed to initialize project %d for %s: %.100s",
971 (int)projid, pw->pw_name, strerror(errno));
972 #endif /* WITH_IRIX_PROJECT */
974 /* Permanently switch to the desired uid. */
975 permanently_set_uid(pw->pw_uid);
977 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
978 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
979 #endif /* HAVE_OSF_SIA */
982 * Get the shell from the password data. An empty shell field is
983 * legal, and means /bin/sh.
985 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
988 /* Try to get AFS tokens for the local cell. */
992 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
999 /* Initialize the environment. */
1001 env = xmalloc(envsize * sizeof(char *));
1004 if (!options.use_login) {
1005 /* Set basic environment. */
1006 child_set_env(&env, &envsize, "USER", pw->pw_name);
1007 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1008 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1009 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1011 snprintf(buf, sizeof buf, "%.200s/%.50s",
1012 _PATH_MAILDIR, pw->pw_name);
1013 child_set_env(&env, &envsize, "MAIL", buf);
1015 /* Normal systems set SHELL by default. */
1016 child_set_env(&env, &envsize, "SHELL", shell);
1019 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1021 /* Set custom environment options from RSA authentication. */
1022 while (custom_environment) {
1023 struct envstring *ce = custom_environment;
1026 for (i = 0; s[i] != '=' && s[i]; i++);
1029 child_set_env(&env, &envsize, s, s + i + 1);
1031 custom_environment = ce->next;
1036 snprintf(buf, sizeof buf, "%.50s %d %d",
1037 get_remote_ipaddr(), get_remote_port(), get_local_port());
1038 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1041 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1043 child_set_env(&env, &envsize, "TERM", term);
1045 child_set_env(&env, &envsize, "DISPLAY", display);
1049 char *authstate,*krb5cc;
1051 if ((authstate = getenv("AUTHSTATE")) != NULL)
1052 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1054 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1055 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1061 extern char *ticket;
1064 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1069 /* Pull in any environment variables that may have been set by PAM. */
1070 do_pam_environment(&env, &envsize);
1071 #endif /* USE_PAM */
1073 read_environment_file(&env,&envsize,"/etc/environment");
1076 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1077 if (auth_get_socket_name() != NULL)
1078 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1079 auth_get_socket_name());
1081 /* read $HOME/.ssh/environment. */
1082 if (!options.use_login) {
1083 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1085 read_environment_file(&env, &envsize, buf);
1088 /* dump the environment */
1089 fprintf(stderr, "Environment:\n");
1090 for (i = 0; env[i]; i++)
1091 fprintf(stderr, " %.200s\n", env[i]);
1094 * Close the connection descriptors; note that this is the child, and
1095 * the server will still have the socket open, and it is important
1096 * that we do not shutdown it. Note that the descriptors cannot be
1097 * closed before building the environment, as we call
1098 * get_remote_ipaddr there.
1100 if (packet_get_connection_in() == packet_get_connection_out())
1101 close(packet_get_connection_in());
1103 close(packet_get_connection_in());
1104 close(packet_get_connection_out());
1107 * Close all descriptors related to channels. They will still remain
1108 * open in the parent.
1110 /* XXX better use close-on-exec? -markus */
1111 channel_close_all();
1114 * Close any extra file descriptors. Note that there may still be
1115 * descriptors left by system functions. They will be closed later.
1120 * Close any extra open file descriptors so that we don\'t have them
1121 * hanging around in clients. Note that we want to do this after
1122 * initgroups, because at least on Solaris 2.3 it leaves file
1125 for (i = 3; i < 64; i++)
1128 /* Change current directory to the user\'s home directory. */
1129 if (chdir(pw->pw_dir) < 0)
1130 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1131 pw->pw_dir, strerror(errno));
1134 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1135 * xauth are run in the proper environment.
1140 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1143 if (!options.use_login) {
1144 if (stat(SSH_USER_RC, &st) >= 0) {
1146 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1148 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1150 if (auth_proto != NULL && auth_data != NULL)
1151 fprintf(f, "%s %s\n", auth_proto, auth_data);
1154 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1155 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1157 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1159 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1161 if (auth_proto != NULL && auth_data != NULL)
1162 fprintf(f, "%s %s\n", auth_proto, auth_data);
1165 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1166 } else if (options.xauth_location != NULL) {
1167 /* Add authority data to .Xauthority if appropriate. */
1168 if (auth_proto != NULL && auth_data != NULL) {
1169 char *screen = strchr(display, ':');
1172 "Running %.100s add %.100s %.100s %.100s\n",
1173 options.xauth_location, display,
1174 auth_proto, auth_data);
1177 "Adding %.*s/unix%s %s %s\n",
1178 screen-display, display,
1179 screen, auth_proto, auth_data);
1181 snprintf(cmd, sizeof cmd, "%s -q -",
1182 options.xauth_location);
1183 f = popen(cmd, "w");
1185 fprintf(f, "add %s %s %s\n", display,
1186 auth_proto, auth_data);
1188 fprintf(f, "add %.*s/unix%s %s %s\n",
1189 screen-display, display,
1190 screen, auth_proto, auth_data);
1193 fprintf(stderr, "Could not run %s\n",
1198 /* Get the last component of the shell name. */
1199 cp = strrchr(shell, '/');
1206 * If we have no command, execute the shell. In this case, the shell
1207 * name to be passed in argv[0] is preceded by '-' to indicate that
1208 * this is a login shell.
1211 if (!options.use_login) {
1215 * Check for mail if we have a tty and it was enabled
1216 * in server options.
1218 if (ttyname && options.check_mail) {
1220 struct stat mailstat;
1221 mailbox = getenv("MAIL");
1222 if (mailbox != NULL) {
1223 if (stat(mailbox, &mailstat) != 0 ||
1224 mailstat.st_size == 0)
1225 printf("No mail.\n");
1226 else if (mailstat.st_mtime < mailstat.st_atime)
1227 printf("You have mail.\n");
1229 printf("You have new mail.\n");
1232 /* Start the shell. Set initial character to '-'. */
1234 strncpy(buf + 1, cp, sizeof(buf) - 1);
1235 buf[sizeof(buf) - 1] = 0;
1237 /* Execute the shell. */
1240 execve(shell, argv, env);
1242 /* Executing the shell failed. */
1247 /* Launch login(1). */
1249 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
1250 "-p", "-f", "--", pw->pw_name, NULL);
1252 /* Login couldn't be executed, die. */
1259 * Execute the command using the user's shell. This uses the -c
1260 * option to execute the command.
1262 argv[0] = (char *) cp;
1264 argv[2] = (char *) command;
1266 execve(shell, argv, env);
1275 static int did_init = 0;
1277 debug("session_new: init");
1278 for(i = 0; i < MAX_SESSIONS; i++) {
1279 sessions[i].used = 0;
1280 sessions[i].self = i;
1284 for(i = 0; i < MAX_SESSIONS; i++) {
1285 Session *s = &sessions[i];
1296 s->auth_data = NULL;
1297 s->auth_proto = NULL;
1300 debug("session_new: session %d", i);
1311 for(i = 0; i < MAX_SESSIONS; i++) {
1312 Session *s = &sessions[i];
1313 debug("dump: used %d session %d %p channel %d pid %d",
1323 session_open(int chanid)
1325 Session *s = session_new();
1326 debug("session_open: channel %d", chanid);
1328 error("no more sessions");
1331 s->pw = auth_get_user();
1333 fatal("no user for session %i", s->self);
1334 debug("session_open: session %d: link with channel %d", s->self, chanid);
1340 session_by_channel(int id)
1343 for(i = 0; i < MAX_SESSIONS; i++) {
1344 Session *s = &sessions[i];
1345 if (s->used && s->chanid == id) {
1346 debug("session_by_channel: session %d channel %d", i, id);
1350 debug("session_by_channel: unknown channel %d", id);
1356 session_by_pid(pid_t pid)
1359 debug("session_by_pid: pid %d", pid);
1360 for(i = 0; i < MAX_SESSIONS; i++) {
1361 Session *s = &sessions[i];
1362 if (s->used && s->pid == pid)
1365 error("session_by_pid: unknown pid %d", pid);
1371 session_window_change_req(Session *s)
1373 s->col = packet_get_int();
1374 s->row = packet_get_int();
1375 s->xpixel = packet_get_int();
1376 s->ypixel = packet_get_int();
1378 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1383 session_pty_req(Session *s)
1386 char *term_modes; /* encoded terminal modes */
1392 s->term = packet_get_string(&len);
1393 s->col = packet_get_int();
1394 s->row = packet_get_int();
1395 s->xpixel = packet_get_int();
1396 s->ypixel = packet_get_int();
1397 term_modes = packet_get_string(&len);
1400 if (strcmp(s->term, "") == 0) {
1404 /* Allocate a pty and open it. */
1405 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1410 error("session_pty_req: session %d alloc failed", s->self);
1414 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1416 * Add a cleanup function to clear the utmp entry and record logout
1417 * time in case we call fatal() (e.g., the connection gets closed).
1419 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1420 pty_setowner(s->pw, s->tty);
1421 /* Get window size from the packet. */
1422 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1424 session_proctitle(s);
1426 /* XXX parse and set terminal modes */
1432 session_subsystem_req(Session *s)
1436 char *subsys = packet_get_string(&len);
1440 log("subsystem request for %s", subsys);
1442 for (i = 0; i < options.num_subsystems; i++) {
1443 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1444 debug("subsystem: exec() %s", options.subsystem_command[i]);
1445 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1451 log("subsystem request for %s failed, subsystem not found", subsys);
1458 session_x11_req(Session *s)
1460 if (!no_port_forwarding_flag) {
1461 debug("X11 forwarding disabled in user configuration file.");
1464 if (!options.x11_forwarding) {
1465 debug("X11 forwarding disabled in server configuration file.");
1468 if (xauthfile != NULL) {
1469 debug("X11 fwd already started.");
1473 debug("Received request for X11 forwarding with auth spoofing.");
1474 if (s->display != NULL)
1475 packet_disconnect("Protocol error: X11 display already set.");
1477 s->single_connection = packet_get_char();
1478 s->auth_proto = packet_get_string(NULL);
1479 s->auth_data = packet_get_string(NULL);
1480 s->screen = packet_get_int();
1483 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1484 if (s->display == NULL) {
1485 xfree(s->auth_proto);
1486 xfree(s->auth_data);
1489 xauthfile = xmalloc(MAXPATHLEN);
1490 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1491 temporarily_use_uid(s->pw->pw_uid);
1492 if (mkdtemp(xauthfile) == NULL) {
1494 error("private X11 dir: mkdtemp %s failed: %s",
1495 xauthfile, strerror(errno));
1498 xfree(s->auth_proto);
1499 xfree(s->auth_data);
1500 /* XXXX remove listening channels */
1503 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1504 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1506 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1511 session_shell_req(Session *s)
1513 /* if forced_command == NULL, the shell is execed */
1514 char *shell = forced_command;
1518 do_exec_no_pty(s, shell, s->pw);
1520 do_exec_pty(s, shell, s->pw);
1525 session_exec_req(Session *s)
1528 char *command = packet_get_string(&len);
1530 if (forced_command) {
1532 command = forced_command;
1533 debug("Forced command '%.500s'", forced_command);
1537 do_exec_no_pty(s, command, s->pw);
1539 do_exec_pty(s, command, s->pw);
1540 if (forced_command == NULL)
1546 session_input_channel_req(int id, void *arg)
1555 rtype = packet_get_string(&len);
1556 reply = packet_get_char();
1558 s = session_by_channel(id);
1560 fatal("session_input_channel_req: channel %d: no session", id);
1561 c = channel_lookup(id);
1563 fatal("session_input_channel_req: channel %d: bad channel", id);
1565 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1566 s->self, id, rtype, reply);
1569 * a session is in LARVAL state until a shell
1570 * or programm is executed
1572 if (c->type == SSH_CHANNEL_LARVAL) {
1573 if (strcmp(rtype, "shell") == 0) {
1574 success = session_shell_req(s);
1575 } else if (strcmp(rtype, "exec") == 0) {
1576 success = session_exec_req(s);
1577 } else if (strcmp(rtype, "pty-req") == 0) {
1578 success = session_pty_req(s);
1579 } else if (strcmp(rtype, "x11-req") == 0) {
1580 success = session_x11_req(s);
1581 } else if (strcmp(rtype, "subsystem") == 0) {
1582 success = session_subsystem_req(s);
1585 if (strcmp(rtype, "window-change") == 0) {
1586 success = session_window_change_req(s);
1590 packet_start(success ?
1591 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1592 packet_put_int(c->remote_id);
1599 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1602 fatal("session_set_fds: called for proto != 2.0");
1604 * now that have a child and a pipe to the child,
1605 * we can activate our channel and register the fd's
1607 if (s->chanid == -1)
1608 fatal("no channel for session %d", s->self);
1609 channel_set_fds(s->chanid,
1611 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1615 session_pty_cleanup(Session *s)
1617 if (s == NULL || s->ttyfd == -1)
1620 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1622 /* Cancel the cleanup function. */
1623 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1625 /* Record that the user has logged out. */
1626 record_logout(s->pid, s->tty);
1628 /* Release the pseudo-tty. */
1629 pty_release(s->tty);
1632 * Close the server side of the socket pairs. We must do this after
1633 * the pty cleanup, so that another process doesn't get this pty
1634 * while we're still cleaning up.
1636 if (close(s->ptymaster) < 0)
1637 error("close(s->ptymaster): %s", strerror(errno));
1641 session_exit_message(Session *s, int status)
1645 fatal("session_close: no session");
1646 c = channel_lookup(s->chanid);
1648 fatal("session_close: session %d: no channel %d",
1649 s->self, s->chanid);
1650 debug("session_exit_message: session %d channel %d pid %d",
1651 s->self, s->chanid, s->pid);
1653 if (WIFEXITED(status)) {
1654 channel_request_start(s->chanid,
1656 packet_put_int(WEXITSTATUS(status));
1658 } else if (WIFSIGNALED(status)) {
1659 channel_request_start(s->chanid,
1661 packet_put_int(WTERMSIG(status));
1663 packet_put_char(WCOREDUMP(status));
1664 #else /* WCOREDUMP */
1666 #endif /* WCOREDUMP */
1667 packet_put_cstring("");
1668 packet_put_cstring("");
1671 /* Some weird exit cause. Just exit. */
1672 packet_disconnect("wait returned status %04x.", status);
1675 /* disconnect channel */
1676 debug("session_exit_message: release channel %d", s->chanid);
1677 channel_cancel_cleanup(s->chanid);
1679 * emulate a write failure with 'chan_write_failed', nobody will be
1680 * interested in data we write.
1681 * Note that we must not call 'chan_read_failed', since there could
1682 * be some more data waiting in the pipe.
1684 if (c->ostate != CHAN_OUTPUT_CLOSED)
1685 chan_write_failed(c);
1690 session_free(Session *s)
1692 debug("session_free: session %d pid %d", s->self, s->pid);
1698 xfree(s->auth_data);
1700 xfree(s->auth_proto);
1705 session_close(Session *s)
1707 session_pty_cleanup(s);
1709 session_proctitle(s);
1713 session_close_by_pid(pid_t pid, int status)
1715 Session *s = session_by_pid(pid);
1717 debug("session_close_by_pid: no session for pid %d", s->pid);
1720 if (s->chanid != -1)
1721 session_exit_message(s, status);
1726 * this is called when a channel dies before
1727 * the session 'child' itself dies
1730 session_close_by_channel(int id, void *arg)
1732 Session *s = session_by_channel(id);
1734 debug("session_close_by_channel: no session for channel %d", id);
1737 /* disconnect channel */
1738 channel_cancel_cleanup(s->chanid);
1741 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1743 /* close session immediately */
1746 /* notify child, delay session cleanup */
1748 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1749 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1750 error("session_close_by_channel: kill %d: %s",
1751 s->pid, strerror(errno));
1756 session_tty_list(void)
1758 static char buf[1024];
1761 for(i = 0; i < MAX_SESSIONS; i++) {
1762 Session *s = &sessions[i];
1763 if (s->used && s->ttyfd != -1) {
1765 strlcat(buf, ",", sizeof buf);
1766 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1770 strlcpy(buf, "notty", sizeof buf);
1775 session_proctitle(Session *s)
1778 error("no user for session %d", s->self);
1780 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1784 do_authenticated2(void)
1787 * Cancel the alarm we set to limit the time taken for
1793 xauthfile_cleanup_proc(NULL);