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.35 2000/09/04 19:07:21 markus Exp $");
29 #include "auth-options.h"
31 #ifdef WITH_IRIX_PROJECT
33 #endif /* WITH_IRIX_PROJECT */
35 #if defined(HAVE_USERSEC_H)
45 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
46 # define S_UFSIZE_HARD S_UFSIZE "_hard"
47 # define S_UCPU_HARD S_UCPU "_hard"
48 # define S_UDATA_HARD S_UDATA "_hard"
49 # define S_USTACK_HARD S_USTACK "_hard"
50 # define S_URSS_HARD S_URSS "_hard"
51 # define S_UCORE_HARD S_UCORE "_hard"
52 # define S_UNOFILE_HARD S_UNOFILE "_hard"
56 #include <login_cap.h>
62 typedef struct Session Session;
71 int ptyfd, ttyfd, ptymaster;
72 int row, col, xpixel, ypixel;
79 int single_connection;
86 Session *session_new(void);
87 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
88 void session_pty_cleanup(Session *s);
89 void session_proctitle(Session *s);
90 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
91 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
92 void do_login(Session *s);
95 do_child(const char *command, struct passwd * pw, const char *term,
96 const char *display, const char *auth_proto,
97 const char *auth_data, const char *ttyname);
100 extern ServerOptions options;
101 #ifdef HAVE___PROGNAME
102 extern char *__progname;
103 #else /* HAVE___PROGNAME */
104 static const char *__progname = "sshd";
105 #endif /* HAVE___PROGNAME */
107 extern int log_stderr;
108 extern int debug_flag;
109 extern unsigned int utmp_len;
111 extern int startup_pipe;
113 /* Local Xauthority file. */
114 static char *xauthfile;
116 /* original command from peer. */
117 char *original_command = NULL;
120 #define MAX_SESSIONS 10
121 Session sessions[MAX_SESSIONS];
122 #ifdef WITH_AIXAUTHENTICATE
123 /* AIX's lastlogin message, set in auth1.c */
125 #endif /* WITH_AIXAUTHENTICATE */
127 #ifdef HAVE_LOGIN_CAP
128 static login_cap_t *lc;
132 * Remove local Xauthority file.
135 xauthfile_cleanup_proc(void *ignore)
137 debug("xauthfile_cleanup_proc called");
139 if (xauthfile != NULL) {
142 p = strrchr(xauthfile, '/');
153 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
154 * dropped connection).
157 pty_cleanup_proc(void *session)
161 fatal("pty_cleanup_proc: no session");
162 debug("pty_cleanup_proc: %s", s->tty);
165 /* Record that the user has logged out. */
166 record_logout(s->pid, s->tty);
169 /* Release the pseudo-tty. */
174 * Prepares for an interactive session. This is called after the user has
175 * been successfully authenticated. During this message exchange, pseudo
176 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
177 * are requested, etc.
180 do_authenticated(struct passwd * pw)
184 int compression_level = 0, enable_compression_after_reply = 0;
189 unsigned int proto_len, data_len, dlen;
192 * Cancel the alarm we set to limit the time taken for
196 if (startup_pipe != -1) {
202 * Inform the channel mechanism that we are the server side and that
203 * the client may request to connect to any port at all. (The user
204 * could do it anyway, and we wouldn\'t know what is permitted except
205 * by the client telling us, so we can equally well trust the client
206 * not to request anything bogus.)
208 if (!no_port_forwarding_flag)
209 channel_permit_all_opens();
214 #ifdef HAVE_LOGIN_CAP
215 if ((lc = login_getclass(pw->pw_class)) == NULL) {
216 error("unable to get login class");
222 * We stay in this loop until the client requests to execute a shell
228 /* Get a packet from the client. */
229 type = packet_read(&plen);
231 /* Process the packet. */
233 case SSH_CMSG_REQUEST_COMPRESSION:
234 packet_integrity_check(plen, 4, type);
235 compression_level = packet_get_int();
236 if (compression_level < 1 || compression_level > 9) {
237 packet_send_debug("Received illegal compression level %d.",
241 /* Enable compression after we have responded with SUCCESS. */
242 enable_compression_after_reply = 1;
246 case SSH_CMSG_REQUEST_PTY:
248 debug("Allocating a pty not permitted for this authentication.");
252 packet_disconnect("Protocol error: you already have a pty.");
254 debug("Allocating pty.");
256 /* Allocate a pty and open it. */
257 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
259 error("Failed to allocate pty.");
262 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
263 pty_setowner(pw, s->tty);
265 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
266 s->term = packet_get_string(&dlen);
267 packet_integrity_check(dlen, strlen(s->term), type);
268 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
269 /* Remaining bytes */
270 n_bytes = plen - (4 + dlen + 4 * 4);
272 if (strcmp(s->term, "") == 0) {
276 /* Get window size from the packet. */
277 s->row = packet_get_int();
278 s->col = packet_get_int();
279 s->xpixel = packet_get_int();
280 s->ypixel = packet_get_int();
281 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
283 /* Get tty modes from the packet. */
284 tty_parse_modes(s->ttyfd, &n_bytes);
285 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
287 session_proctitle(s);
289 /* Indicate that we now have a pty. */
294 case SSH_CMSG_X11_REQUEST_FORWARDING:
295 if (!options.x11_forwarding) {
296 packet_send_debug("X11 forwarding disabled in server configuration file.");
299 if (!options.xauth_location) {
300 packet_send_debug("No xauth program; cannot forward with spoofing.");
303 if (no_x11_forwarding_flag) {
304 packet_send_debug("X11 forwarding not permitted for this authentication.");
307 debug("Received request for X11 forwarding with auth spoofing.");
308 if (s->display != NULL)
309 packet_disconnect("Protocol error: X11 display already set.");
311 s->auth_proto = packet_get_string(&proto_len);
312 s->auth_data = packet_get_string(&data_len);
313 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
315 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
316 s->screen = packet_get_int();
319 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
321 if (s->display == NULL)
324 /* Setup to always have a local .Xauthority. */
325 xauthfile = xmalloc(MAXPATHLEN);
326 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
327 temporarily_use_uid(pw->pw_uid);
328 if (mkdtemp(xauthfile) == NULL) {
330 error("private X11 dir: mkdtemp %s failed: %s",
331 xauthfile, strerror(errno));
334 /* XXXX remove listening channels */
337 strlcat(xauthfile, "/cookies", MAXPATHLEN);
338 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
342 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
346 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
347 if (no_agent_forwarding_flag || compat13) {
348 debug("Authentication agent forwarding not permitted for this authentication.");
351 debug("Received authentication agent forwarding request.");
352 success = auth_input_request_forwarding(pw);
355 case SSH_CMSG_PORT_FORWARD_REQUEST:
356 if (no_port_forwarding_flag) {
357 debug("Port forwarding not permitted for this authentication.");
360 debug("Received TCP/IP port forwarding request.");
361 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
365 case SSH_CMSG_MAX_PACKET_SIZE:
366 if (packet_set_maxsize(packet_get_int()) > 0)
370 case SSH_CMSG_EXEC_SHELL:
371 case SSH_CMSG_EXEC_CMD:
372 /* Set interactive/non-interactive mode. */
373 packet_set_interactive(have_pty || s->display != NULL,
376 if (type == SSH_CMSG_EXEC_CMD) {
377 command = packet_get_string(&dlen);
378 debug("Exec command '%.500s'", command);
379 packet_integrity_check(plen, 4 + dlen, type);
382 packet_integrity_check(plen, 0, type);
384 if (forced_command != NULL) {
385 original_command = command;
386 command = forced_command;
387 debug("Forced command '%.500s'", forced_command);
390 do_exec_pty(s, command, pw);
392 do_exec_no_pty(s, command, pw);
396 /* Cleanup user's local Xauthority file. */
398 xauthfile_cleanup_proc(NULL);
403 * Any unknown messages in this phase are ignored,
404 * and a failure message is returned.
406 log("Unknown packet type received after authentication: %d", type);
408 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
412 /* Enable compression now that we have replied if appropriate. */
413 if (enable_compression_after_reply) {
414 enable_compression_after_reply = 0;
415 packet_start_compression(compression_level);
421 * This is called to fork and execute a command when we have no tty. This
422 * will call do_child from the child, and server_loop from the parent after
423 * setting up file descriptors and such.
426 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
431 int pin[2], pout[2], perr[2];
432 /* Allocate pipes for communicating with the program. */
433 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
434 packet_disconnect("Could not create pipes: %.100s",
436 #else /* USE_PIPES */
437 int inout[2], err[2];
438 /* Uses socket pairs to communicate with the program. */
439 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
440 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
441 packet_disconnect("Could not create socket pairs: %.100s",
443 #endif /* USE_PIPES */
445 fatal("do_exec_no_pty: no session");
447 session_proctitle(s);
453 /* Fork the child. */
454 if ((pid = fork()) == 0) {
455 /* Child. Reinitialize the log since the pid has changed. */
456 log_init(__progname, options.log_level, options.log_facility, log_stderr);
459 * Create a new session and process group since the 4.4BSD
460 * setlogin() affects the entire process group.
463 error("setsid failed: %.100s", strerror(errno));
467 * Redirect stdin. We close the parent side of the socket
468 * pair, and make the child side the standard input.
471 if (dup2(pin[0], 0) < 0)
472 perror("dup2 stdin");
475 /* Redirect stdout. */
477 if (dup2(pout[1], 1) < 0)
478 perror("dup2 stdout");
481 /* Redirect stderr. */
483 if (dup2(perr[1], 2) < 0)
484 perror("dup2 stderr");
486 #else /* USE_PIPES */
488 * Redirect stdin, stdout, and stderr. Stdin and stdout will
489 * use the same socket, as some programs (particularly rdist)
490 * seem to depend on it.
494 if (dup2(inout[0], 0) < 0) /* stdin */
495 perror("dup2 stdin");
496 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
497 perror("dup2 stdout");
498 if (dup2(err[0], 2) < 0) /* stderr */
499 perror("dup2 stderr");
500 #endif /* USE_PIPES */
502 /* Do processing for the child (exec command etc). */
503 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
507 packet_disconnect("fork failed: %.100s", strerror(errno));
510 /* We are the parent. Close the child sides of the pipes. */
516 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
518 /* Enter the interactive session. */
519 server_loop(pid, pin[1], pout[0], perr[0]);
520 /* server_loop has closed pin[1], pout[1], and perr[1]. */
522 #else /* USE_PIPES */
523 /* We are the parent. Close the child sides of the socket pairs. */
528 * Enter the interactive session. Note: server_loop must be able to
529 * handle the case that fdin and fdout are the same.
532 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
534 server_loop(pid, inout[1], inout[1], err[1]);
535 /* server_loop has closed inout[1] and err[1]. */
537 #endif /* USE_PIPES */
541 * This is called to fork and execute a command when we have a tty. This
542 * will call do_child from the child, and server_loop from the parent after
543 * setting up file descriptors, controlling tty, updating wtmp, utmp,
544 * lastlog, and other such operations.
547 do_exec_pty(Session *s, const char *command, struct passwd * pw)
549 int fdout, ptyfd, ttyfd, ptymaster;
553 fatal("do_exec_pty: no session");
558 do_pam_session(pw->pw_name, s->tty);
562 /* Fork the child. */
563 if ((pid = fork()) == 0) {
564 /* Child. Reinitialize the log because the pid has changed. */
565 log_init(__progname, options.log_level, options.log_facility, log_stderr);
567 /* Close the master side of the pseudo tty. */
570 /* Make the pseudo tty our controlling tty. */
571 pty_make_controlling_tty(&ttyfd, s->tty);
573 /* Redirect stdin from the pseudo tty. */
574 if (dup2(ttyfd, fileno(stdin)) < 0)
575 error("dup2 stdin failed: %.100s", strerror(errno));
577 /* Redirect stdout to the pseudo tty. */
578 if (dup2(ttyfd, fileno(stdout)) < 0)
579 error("dup2 stdin failed: %.100s", strerror(errno));
581 /* Redirect stderr to the pseudo tty. */
582 if (dup2(ttyfd, fileno(stderr)) < 0)
583 error("dup2 stdin failed: %.100s", strerror(errno));
585 /* Close the extra descriptor for the pseudo tty. */
588 /* record login, etc. similar to login(1) */
589 if (command == NULL && !options.use_login)
592 /* Do common processing for the child, such as execing the command. */
593 do_child(command, pw, s->term, s->display, s->auth_proto,
594 s->auth_data, s->tty);
598 packet_disconnect("fork failed: %.100s", strerror(errno));
601 /* Parent. Close the slave side of the pseudo tty. */
605 * Create another descriptor of the pty master side for use as the
606 * standard input. We could use the original descriptor, but this
607 * simplifies code in server_loop. The descriptor is bidirectional.
611 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
613 /* we keep a reference to the pty master */
614 ptymaster = dup(ptyfd);
616 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
617 s->ptymaster = ptymaster;
619 /* Enter interactive session. */
621 session_set_fds(s, ptyfd, fdout, -1);
623 server_loop(pid, ptyfd, fdout, -1);
624 /* server_loop _has_ closed ptyfd and fdout. */
625 session_pty_cleanup(s);
630 get_remote_name_or_ip(void)
632 static const char *remote = "";
634 remote = get_canonical_hostname();
635 if (utmp_len == 0 || strlen(remote) > utmp_len)
636 remote = get_remote_ipaddr();
640 /* administrative, login(1)-like work */
647 char hostname[MAXHOSTNAMELEN];
649 struct sockaddr_storage from;
651 time_t last_login_time;
652 struct passwd * pw = s->pw;
653 pid_t pid = getpid();
656 * Get IP address of client. If the connection is not a socket, let
657 * the address be 0.0.0.0.
659 memset(&from, 0, sizeof(from));
660 if (packet_connection_is_on_socket()) {
661 fromlen = sizeof(from);
662 if (getpeername(packet_get_connection_in(),
663 (struct sockaddr *) & from, &fromlen) < 0) {
664 debug("getpeername: %.100s", strerror(errno));
669 /* Get the time and hostname when the user last logged in. */
670 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
671 hostname, sizeof(hostname));
673 /* Record that there was a login on that tty from the remote host. */
674 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
675 get_remote_name_or_ip(), (struct sockaddr *)&from);
677 /* Done if .hushlogin exists. */
678 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
679 #ifdef HAVE_LOGIN_CAP
680 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
682 if (stat(buf, &st) >= 0)
687 print_pam_messages();
689 #ifdef WITH_AIXAUTHENTICATE
690 if (aixloginmsg && *aixloginmsg)
691 printf("%s\n", aixloginmsg);
692 #endif /* WITH_AIXAUTHENTICATE */
694 if (last_login_time != 0) {
695 time_string = ctime(&last_login_time);
696 if (strchr(time_string, '\n'))
697 *strchr(time_string, '\n') = 0;
698 if (strcmp(buf, "") == 0)
699 printf("Last login: %s\r\n", time_string);
701 printf("Last login: %s from %s\r\n", time_string, buf);
703 if (options.print_motd) {
704 #ifdef HAVE_LOGIN_CAP
705 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
708 f = fopen("/etc/motd", "r");
711 while (fgets(buf, sizeof(buf), f))
719 * Sets the value of the given variable in the environment. If the variable
720 * already exists, its value is overriden.
723 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
726 unsigned int i, namelen;
730 * Find the slot where the value should be stored. If the variable
731 * already exists, we reuse the slot; otherwise we append a new slot
732 * at the end of the array, expanding if necessary.
735 namelen = strlen(name);
736 for (i = 0; env[i]; i++)
737 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
740 /* Reuse the slot. */
743 /* New variable. Expand if necessary. */
744 if (i >= (*envsizep) - 1) {
746 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
748 /* Need to set the NULL pointer at end of array beyond the new slot. */
752 /* Allocate space and format the variable in the appropriate slot. */
753 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
754 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
758 * Reads environment variables from the given file and adds/overrides them
759 * into the environment. If the file does not exist, this does nothing.
760 * Otherwise, it must consist of empty lines, comments (line starts with '#')
761 * and assignments of the form name=value. No other forms are allowed.
764 read_environment_file(char ***env, unsigned int *envsize,
765 const char *filename)
771 f = fopen(filename, "r");
775 while (fgets(buf, sizeof(buf), f)) {
776 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
778 if (!*cp || *cp == '#' || *cp == '\n')
780 if (strchr(cp, '\n'))
781 *strchr(cp, '\n') = '\0';
782 value = strchr(cp, '=');
784 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
788 * Replace the equals sign by nul, and advance value to
793 child_set_env(env, envsize, cp, value);
800 * Sets any environment variables which have been specified by PAM
802 void do_pam_environment(char ***env, int *envsize)
804 char *equals, var_name[512], var_val[512];
808 if ((pam_env = fetch_pam_environment()) == NULL)
811 for(i = 0; pam_env[i] != NULL; i++) {
812 if ((equals = strstr(pam_env[i], "=")) == NULL)
815 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
816 memset(var_name, '\0', sizeof(var_name));
817 memset(var_val, '\0', sizeof(var_val));
819 strncpy(var_name, pam_env[i], equals - pam_env[i]);
820 strcpy(var_val, equals + 1);
822 debug("PAM environment: %s=%s", var_name, var_val);
824 child_set_env(env, envsize, var_name, var_val);
830 #if defined(HAVE_GETUSERATTR)
832 * AIX-specific login initialisation
834 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
839 getrlimit(resource, &rlim);
842 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
844 rlim.rlim_cur = RLIM_INFINITY;
845 } else if (slim != 0) {
846 /* See the wackiness below */
847 if (rlim.rlim_cur == slim * mult)
850 rlim.rlim_cur = slim * mult;
855 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
857 rlim.rlim_max = RLIM_INFINITY;
858 } else if (hlim != 0) {
859 rlim.rlim_max = hlim * mult;
864 * XXX For cpu and fsize the soft limit is set to the hard limit
865 * if the hard limit is left at its default value and the soft limit
866 * is changed from its default value, either by requesting it
867 * (slim == 0) or by setting it to the current default. At least
868 * that's how rlogind does it. If you're confused you're not alone.
869 * Bug or feature? AIX 4.3.1.2
871 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
872 && hlim == 0 && slim != 0)
873 rlim.rlim_max = rlim.rlim_cur;
874 /* A specified hard limit limits the soft limit */
875 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
876 rlim.rlim_cur = rlim.rlim_max;
877 /* A soft limit can increase a hard limit */
878 else if (rlim.rlim_cur > rlim.rlim_max)
879 rlim.rlim_max = rlim.rlim_cur;
881 if (setrlimit(resource, &rlim) != 0)
882 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
885 void set_limits_from_userattr(char *user)
890 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
891 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
892 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
893 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
894 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
895 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
896 #if defined(S_UNOFILE)
897 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
900 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
901 /* Convert decimal to octal */
902 (void) snprintf(buf, sizeof(buf), "%d", mask);
903 if (sscanf(buf, "%o", &mask) == 1)
907 #endif /* defined(HAVE_GETUSERATTR) */
910 * Performs common processing for the child, such as setting up the
911 * environment, closing extra file descriptors, setting the user and group
912 * ids, and executing the command or shell.
915 do_child(const char *command, struct passwd * pw, const char *term,
916 const char *display, const char *auth_proto,
917 const char *auth_data, const char *ttyname)
919 const char *shell, *hostname = NULL, *cp = NULL;
923 unsigned int envsize, i;
925 extern char **environ;
928 #ifdef WITH_IRIX_PROJECT
930 #endif /* WITH_IRIX_PROJECT */
932 /* login(1) is only called if we execute the login shell */
933 if (options.use_login && command != NULL)
934 options.use_login = 0;
936 #ifndef USE_PAM /* pam_nologin handles this */
937 if (!options.use_login) {
938 # ifdef HAVE_LOGIN_CAP
939 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
940 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
941 _PATH_NOLOGIN), "r");
942 # else /* HAVE_LOGIN_CAP */
944 f = fopen(_PATH_NOLOGIN, "r");
945 # endif /* HAVE_LOGIN_CAP */
947 /* /etc/nologin exists. Print its contents and exit. */
948 while (fgets(buf, sizeof(buf), f))
956 /* Set login name, uid, gid, and groups. */
957 /* Login(1) does this as well, and it needs uid 0 for the "-h"
958 switch, so we let login(1) to this for us. */
959 if (!options.use_login) {
961 extern char **saved_argv;
962 extern int saved_argc;
963 char *host = get_canonical_hostname ();
965 if (sia_become_user(NULL, saved_argc, saved_argv, host,
966 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
968 perror("sia_become_user");
971 if (setreuid(geteuid(), geteuid()) < 0) {
975 #else /* HAVE_OSF_SIA */
976 if (getuid() == 0 || geteuid() == 0) {
977 # ifdef HAVE_GETUSERATTR
978 set_limits_from_userattr(pw->pw_name);
979 # endif /* HAVE_GETUSERATTR */
980 # ifdef HAVE_LOGIN_CAP
981 if (setusercontext(lc, pw, pw->pw_uid,
982 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
983 perror("unable to set user context");
986 # else /* HAVE_LOGIN_CAP */
987 if (setlogin(pw->pw_name) < 0)
988 error("setlogin failed: %s", strerror(errno));
989 if (setgid(pw->pw_gid) < 0) {
993 /* Initialize the group list. */
994 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
995 perror("initgroups");
999 # ifdef WITH_IRIX_ARRAY
1000 /* initialize array session */
1001 if (newarraysess() != 0)
1002 fatal("Failed to set up new array session: %.100s",
1004 # endif /* WITH_IRIX_ARRAY */
1005 # ifdef WITH_IRIX_PROJECT
1006 /* initialize irix project info */
1007 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1008 debug("Failed to get project id, using projid 0");
1011 if (setprid(projid))
1012 fatal("Failed to initialize project %d for %s: %.100s",
1013 (int)projid, pw->pw_name, strerror(errno));
1014 # endif /* WITH_IRIX_PROJECT */
1015 /* Permanently switch to the desired uid. */
1016 permanently_set_uid(pw->pw_uid);
1017 # endif /* HAVE_LOGIN_CAP */
1019 #endif /* HAVE_OSF_SIA */
1021 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1022 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1025 * Get the shell from the password data. An empty shell field is
1026 * legal, and means /bin/sh.
1028 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1029 #ifdef HAVE_LOGIN_CAP
1030 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1034 /* Try to get AFS tokens for the local cell. */
1038 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1039 krb_afslog(cell, 0);
1045 /* Initialize the environment. */
1047 env = xmalloc(envsize * sizeof(char *));
1050 if (!options.use_login) {
1051 /* Set basic environment. */
1052 child_set_env(&env, &envsize, "USER", pw->pw_name);
1053 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1054 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1055 #ifdef HAVE_LOGIN_CAP
1056 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1057 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1059 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1062 snprintf(buf, sizeof buf, "%.200s/%.50s",
1063 _PATH_MAILDIR, pw->pw_name);
1064 child_set_env(&env, &envsize, "MAIL", buf);
1066 /* Normal systems set SHELL by default. */
1067 child_set_env(&env, &envsize, "SHELL", shell);
1070 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1072 /* Set custom environment options from RSA authentication. */
1073 while (custom_environment) {
1074 struct envstring *ce = custom_environment;
1077 for (i = 0; s[i] != '=' && s[i]; i++);
1080 child_set_env(&env, &envsize, s, s + i + 1);
1082 custom_environment = ce->next;
1087 snprintf(buf, sizeof buf, "%.50s %d %d",
1088 get_remote_ipaddr(), get_remote_port(), get_local_port());
1089 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1092 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1094 child_set_env(&env, &envsize, "TERM", term);
1096 child_set_env(&env, &envsize, "DISPLAY", display);
1097 if (original_command)
1098 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1103 char *authstate,*krb5cc;
1105 if ((authstate = getenv("AUTHSTATE")) != NULL)
1106 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1108 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1109 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1115 extern char *ticket;
1118 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1123 /* Pull in any environment variables that may have been set by PAM. */
1124 do_pam_environment(&env, &envsize);
1125 #endif /* USE_PAM */
1127 read_environment_file(&env,&envsize,"/etc/environment");
1130 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1131 if (auth_get_socket_name() != NULL)
1132 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1133 auth_get_socket_name());
1135 /* read $HOME/.ssh/environment. */
1136 if (!options.use_login) {
1137 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1139 read_environment_file(&env, &envsize, buf);
1142 /* dump the environment */
1143 fprintf(stderr, "Environment:\n");
1144 for (i = 0; env[i]; i++)
1145 fprintf(stderr, " %.200s\n", env[i]);
1147 /* we have to stash the hostname before we close our socket. */
1148 if (options.use_login)
1149 hostname = get_remote_name_or_ip();
1151 * Close the connection descriptors; note that this is the child, and
1152 * the server will still have the socket open, and it is important
1153 * that we do not shutdown it. Note that the descriptors cannot be
1154 * closed before building the environment, as we call
1155 * get_remote_ipaddr there.
1157 if (packet_get_connection_in() == packet_get_connection_out())
1158 close(packet_get_connection_in());
1160 close(packet_get_connection_in());
1161 close(packet_get_connection_out());
1164 * Close all descriptors related to channels. They will still remain
1165 * open in the parent.
1167 /* XXX better use close-on-exec? -markus */
1168 channel_close_all();
1171 * Close any extra file descriptors. Note that there may still be
1172 * descriptors left by system functions. They will be closed later.
1177 * Close any extra open file descriptors so that we don\'t have them
1178 * hanging around in clients. Note that we want to do this after
1179 * initgroups, because at least on Solaris 2.3 it leaves file
1182 for (i = 3; i < 64; i++)
1185 /* Change current directory to the user\'s home directory. */
1186 if (chdir(pw->pw_dir) < 0) {
1187 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1188 pw->pw_dir, strerror(errno));
1189 #ifdef HAVE_LOGIN_CAP
1190 if (login_getcapbool(lc, "requirehome", 0))
1196 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1197 * xauth are run in the proper environment.
1202 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1205 if (!options.use_login) {
1206 if (stat(SSH_USER_RC, &st) >= 0) {
1208 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1210 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1212 if (auth_proto != NULL && auth_data != NULL)
1213 fprintf(f, "%s %s\n", auth_proto, auth_data);
1216 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1217 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1219 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1221 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1223 if (auth_proto != NULL && auth_data != NULL)
1224 fprintf(f, "%s %s\n", auth_proto, auth_data);
1227 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1228 } else if (options.xauth_location != NULL) {
1229 /* Add authority data to .Xauthority if appropriate. */
1230 if (auth_proto != NULL && auth_data != NULL) {
1231 char *screen = strchr(display, ':');
1234 "Running %.100s add %.100s %.100s %.100s\n",
1235 options.xauth_location, display,
1236 auth_proto, auth_data);
1239 "Adding %.*s/unix%s %s %s\n",
1240 (int)(screen-display), display,
1241 screen, auth_proto, auth_data);
1243 snprintf(cmd, sizeof cmd, "%s -q -",
1244 options.xauth_location);
1245 f = popen(cmd, "w");
1247 fprintf(f, "add %s %s %s\n", display,
1248 auth_proto, auth_data);
1250 fprintf(f, "add %.*s/unix%s %s %s\n",
1251 (int)(screen-display), display,
1252 screen, auth_proto, auth_data);
1255 fprintf(stderr, "Could not run %s\n",
1260 /* Get the last component of the shell name. */
1261 cp = strrchr(shell, '/');
1268 * If we have no command, execute the shell. In this case, the shell
1269 * name to be passed in argv[0] is preceded by '-' to indicate that
1270 * this is a login shell.
1273 if (!options.use_login) {
1277 * Check for mail if we have a tty and it was enabled
1278 * in server options.
1280 if (ttyname && options.check_mail) {
1282 struct stat mailstat;
1283 mailbox = getenv("MAIL");
1284 if (mailbox != NULL) {
1285 if (stat(mailbox, &mailstat) != 0 ||
1286 mailstat.st_size == 0)
1287 printf("No mail.\n");
1288 else if (mailstat.st_mtime < mailstat.st_atime)
1289 printf("You have mail.\n");
1291 printf("You have new mail.\n");
1294 /* Start the shell. Set initial character to '-'. */
1296 strncpy(buf + 1, cp, sizeof(buf) - 1);
1297 buf[sizeof(buf) - 1] = 0;
1299 /* Execute the shell. */
1302 execve(shell, argv, env);
1304 /* Executing the shell failed. */
1309 /* Launch login(1). */
1311 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1312 "-p", "-f", "--", pw->pw_name, NULL);
1314 /* Login couldn't be executed, die. */
1321 * Execute the command using the user's shell. This uses the -c
1322 * option to execute the command.
1324 argv[0] = (char *) cp;
1326 argv[2] = (char *) command;
1328 execve(shell, argv, env);
1337 static int did_init = 0;
1339 debug("session_new: init");
1340 for(i = 0; i < MAX_SESSIONS; i++) {
1341 sessions[i].used = 0;
1342 sessions[i].self = i;
1346 for(i = 0; i < MAX_SESSIONS; i++) {
1347 Session *s = &sessions[i];
1358 s->auth_data = NULL;
1359 s->auth_proto = NULL;
1362 debug("session_new: session %d", i);
1373 for(i = 0; i < MAX_SESSIONS; i++) {
1374 Session *s = &sessions[i];
1375 debug("dump: used %d session %d %p channel %d pid %d",
1385 session_open(int chanid)
1387 Session *s = session_new();
1388 debug("session_open: channel %d", chanid);
1390 error("no more sessions");
1393 s->pw = auth_get_user();
1395 fatal("no user for session %i", s->self);
1396 debug("session_open: session %d: link with channel %d", s->self, chanid);
1402 session_by_channel(int id)
1405 for(i = 0; i < MAX_SESSIONS; i++) {
1406 Session *s = &sessions[i];
1407 if (s->used && s->chanid == id) {
1408 debug("session_by_channel: session %d channel %d", i, id);
1412 debug("session_by_channel: unknown channel %d", id);
1418 session_by_pid(pid_t pid)
1421 debug("session_by_pid: pid %d", pid);
1422 for(i = 0; i < MAX_SESSIONS; i++) {
1423 Session *s = &sessions[i];
1424 if (s->used && s->pid == pid)
1427 error("session_by_pid: unknown pid %d", pid);
1433 session_window_change_req(Session *s)
1435 s->col = packet_get_int();
1436 s->row = packet_get_int();
1437 s->xpixel = packet_get_int();
1438 s->ypixel = packet_get_int();
1440 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1445 session_pty_req(Session *s)
1448 char *term_modes; /* encoded terminal modes */
1454 s->term = packet_get_string(&len);
1455 s->col = packet_get_int();
1456 s->row = packet_get_int();
1457 s->xpixel = packet_get_int();
1458 s->ypixel = packet_get_int();
1459 term_modes = packet_get_string(&len);
1462 if (strcmp(s->term, "") == 0) {
1466 /* Allocate a pty and open it. */
1467 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1472 error("session_pty_req: session %d alloc failed", s->self);
1476 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1478 * Add a cleanup function to clear the utmp entry and record logout
1479 * time in case we call fatal() (e.g., the connection gets closed).
1481 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1482 pty_setowner(s->pw, s->tty);
1483 /* Get window size from the packet. */
1484 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1486 session_proctitle(s);
1488 /* XXX parse and set terminal modes */
1494 session_subsystem_req(Session *s)
1498 char *subsys = packet_get_string(&len);
1502 log("subsystem request for %s", subsys);
1504 for (i = 0; i < options.num_subsystems; i++) {
1505 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1506 debug("subsystem: exec() %s", options.subsystem_command[i]);
1507 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1513 log("subsystem request for %s failed, subsystem not found", subsys);
1520 session_x11_req(Session *s)
1523 if (no_x11_forwarding_flag) {
1524 debug("X11 forwarding disabled in user configuration file.");
1527 if (!options.x11_forwarding) {
1528 debug("X11 forwarding disabled in server configuration file.");
1531 if (xauthfile != NULL) {
1532 debug("X11 fwd already started.");
1536 debug("Received request for X11 forwarding with auth spoofing.");
1537 if (s->display != NULL)
1538 packet_disconnect("Protocol error: X11 display already set.");
1540 s->single_connection = packet_get_char();
1541 s->auth_proto = packet_get_string(NULL);
1542 s->auth_data = packet_get_string(NULL);
1543 s->screen = packet_get_int();
1546 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1547 if (s->display == NULL) {
1548 xfree(s->auth_proto);
1549 xfree(s->auth_data);
1552 xauthfile = xmalloc(MAXPATHLEN);
1553 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1554 temporarily_use_uid(s->pw->pw_uid);
1555 if (mkdtemp(xauthfile) == NULL) {
1557 error("private X11 dir: mkdtemp %s failed: %s",
1558 xauthfile, strerror(errno));
1561 xfree(s->auth_proto);
1562 xfree(s->auth_data);
1563 /* XXXX remove listening channels */
1566 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1567 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1571 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1576 session_shell_req(Session *s)
1578 /* if forced_command == NULL, the shell is execed */
1579 char *shell = forced_command;
1583 do_exec_no_pty(s, shell, s->pw);
1585 do_exec_pty(s, shell, s->pw);
1590 session_exec_req(Session *s)
1593 char *command = packet_get_string(&len);
1595 if (forced_command) {
1596 original_command = command;
1597 command = forced_command;
1598 debug("Forced command '%.500s'", forced_command);
1602 do_exec_no_pty(s, command, s->pw);
1604 do_exec_pty(s, command, s->pw);
1605 if (forced_command == NULL)
1611 session_input_channel_req(int id, void *arg)
1620 rtype = packet_get_string(&len);
1621 reply = packet_get_char();
1623 s = session_by_channel(id);
1625 fatal("session_input_channel_req: channel %d: no session", id);
1626 c = channel_lookup(id);
1628 fatal("session_input_channel_req: channel %d: bad channel", id);
1630 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1631 s->self, id, rtype, reply);
1634 * a session is in LARVAL state until a shell
1635 * or programm is executed
1637 if (c->type == SSH_CHANNEL_LARVAL) {
1638 if (strcmp(rtype, "shell") == 0) {
1639 success = session_shell_req(s);
1640 } else if (strcmp(rtype, "exec") == 0) {
1641 success = session_exec_req(s);
1642 } else if (strcmp(rtype, "pty-req") == 0) {
1643 success = session_pty_req(s);
1644 } else if (strcmp(rtype, "x11-req") == 0) {
1645 success = session_x11_req(s);
1646 } else if (strcmp(rtype, "subsystem") == 0) {
1647 success = session_subsystem_req(s);
1650 if (strcmp(rtype, "window-change") == 0) {
1651 success = session_window_change_req(s);
1655 packet_start(success ?
1656 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1657 packet_put_int(c->remote_id);
1664 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1667 fatal("session_set_fds: called for proto != 2.0");
1669 * now that have a child and a pipe to the child,
1670 * we can activate our channel and register the fd's
1672 if (s->chanid == -1)
1673 fatal("no channel for session %d", s->self);
1674 channel_set_fds(s->chanid,
1676 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1680 session_pty_cleanup(Session *s)
1682 if (s == NULL || s->ttyfd == -1)
1685 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1687 /* Cancel the cleanup function. */
1688 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1690 /* Record that the user has logged out. */
1691 record_logout(s->pid, s->tty);
1693 /* Release the pseudo-tty. */
1694 pty_release(s->tty);
1697 * Close the server side of the socket pairs. We must do this after
1698 * the pty cleanup, so that another process doesn't get this pty
1699 * while we're still cleaning up.
1701 if (close(s->ptymaster) < 0)
1702 error("close(s->ptymaster): %s", strerror(errno));
1706 session_exit_message(Session *s, int status)
1710 fatal("session_close: no session");
1711 c = channel_lookup(s->chanid);
1713 fatal("session_close: session %d: no channel %d",
1714 s->self, s->chanid);
1715 debug("session_exit_message: session %d channel %d pid %d",
1716 s->self, s->chanid, s->pid);
1718 if (WIFEXITED(status)) {
1719 channel_request_start(s->chanid,
1721 packet_put_int(WEXITSTATUS(status));
1723 } else if (WIFSIGNALED(status)) {
1724 channel_request_start(s->chanid,
1726 packet_put_int(WTERMSIG(status));
1728 packet_put_char(WCOREDUMP(status));
1729 #else /* WCOREDUMP */
1731 #endif /* WCOREDUMP */
1732 packet_put_cstring("");
1733 packet_put_cstring("");
1736 /* Some weird exit cause. Just exit. */
1737 packet_disconnect("wait returned status %04x.", status);
1740 /* disconnect channel */
1741 debug("session_exit_message: release channel %d", s->chanid);
1742 channel_cancel_cleanup(s->chanid);
1744 * emulate a write failure with 'chan_write_failed', nobody will be
1745 * interested in data we write.
1746 * Note that we must not call 'chan_read_failed', since there could
1747 * be some more data waiting in the pipe.
1749 if (c->ostate != CHAN_OUTPUT_CLOSED)
1750 chan_write_failed(c);
1755 session_free(Session *s)
1757 debug("session_free: session %d pid %d", s->self, s->pid);
1763 xfree(s->auth_data);
1765 xfree(s->auth_proto);
1770 session_close(Session *s)
1772 session_pty_cleanup(s);
1774 session_proctitle(s);
1778 session_close_by_pid(pid_t pid, int status)
1780 Session *s = session_by_pid(pid);
1782 debug("session_close_by_pid: no session for pid %d", s->pid);
1785 if (s->chanid != -1)
1786 session_exit_message(s, status);
1791 * this is called when a channel dies before
1792 * the session 'child' itself dies
1795 session_close_by_channel(int id, void *arg)
1797 Session *s = session_by_channel(id);
1799 debug("session_close_by_channel: no session for channel %d", id);
1802 /* disconnect channel */
1803 channel_cancel_cleanup(s->chanid);
1806 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1808 /* close session immediately */
1811 /* notify child, delay session cleanup */
1813 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1814 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1815 error("session_close_by_channel: kill %d: %s",
1816 s->pid, strerror(errno));
1821 session_tty_list(void)
1823 static char buf[1024];
1826 for(i = 0; i < MAX_SESSIONS; i++) {
1827 Session *s = &sessions[i];
1828 if (s->used && s->ttyfd != -1) {
1830 strlcat(buf, ",", sizeof buf);
1831 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1835 strlcpy(buf, "notty", sizeof buf);
1840 session_proctitle(Session *s)
1843 error("no user for session %d", s->self);
1845 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1849 do_authenticated2(void)
1851 #ifdef HAVE_LOGIN_CAP
1856 * Cancel the alarm we set to limit the time taken for
1860 if (startup_pipe != -1) {
1861 close(startup_pipe);
1864 #ifdef HAVE_LOGIN_CAP
1865 pw = auth_get_user();
1866 if ((lc = login_getclass(pw->pw_class)) == NULL) {
1867 error("unable to get login class");
1873 xauthfile_cleanup_proc(NULL);