Debian Codegraph @

src/programs/pkexec.c

raw
1 /*
2 * Copyright (C) 2008 Red Hat, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General
15 * Public License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
17 * Boston, MA 02111-1307, USA.
18 *
19 * Author: David Zeuthen <[email protected]>
20 */
21
22 #include <string.h>
23 #include <stdlib.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <grp.h>
29 #include <pwd.h>
30 #include <errno.h>
31
32 #ifdef __linux__
33 #include <sys/prctl.h>
34 #endif
35
36 #ifdef __FreeBSD__
37 #include <signal.h>
38 #include <sys/procctl.h>
39 #endif
40
41 #include <glib/gi18n.h>
42 #include <glib-unix.h>
43
44 #ifdef POLKIT_AUTHFW_PAM
45 #include <security/pam_appl.h>
46 #endif /* POLKIT_AUTHFW_PAM */
47
48 #include <syslog.h>
49 #include <stdarg.h>
50
51 #include <polkit/polkit.h>
52 #define POLKIT_AGENT_I_KNOW_API_IS_SUBJECT_TO_CHANGE
53 #include <polkitagent/polkitagent.h>
54
55 static gchar *original_user_name = NULL;
56 static gchar *original_cwd;
57 static gchar *command_line = NULL;
58 static gchar *cmdline_short = NULL;
59 static struct passwd *pw;
60
61 #ifndef HAVE_CLEARENV
62 extern char **environ;
63
64 static int
65 clearenv (void)
66 {
67 if (environ != NULL)
68 environ[0] = NULL;
69 return 0;
70 }
71 #endif
72
73 static void
74 usage (int argc, char *argv[])
75 {
76 g_printerr ("pkexec --version |\n"
77 " --help |\n"
78 " --disable-internal-agent |\n"
79 " [--keep-cwd] [--user username] [PROGRAM] [ARGUMENTS...]\n"
80 "\n"
81 "See the pkexec manual page for more details.\n"
82 "\n"
83 "Report bugs to: %s\n"
84 "%s home page: <%s>\n", PACKAGE_BUGREPORT, PACKAGE_NAME,
85 PACKAGE_URL);
86 }
87
88 /* ---------------------------------------------------------------------------------------------------- */
89
90 G_GNUC_PRINTF(3, 4)
91 static void
92 log_message (gint level,
93 gboolean print_to_stderr,
94 const gchar *format,
95 ...)
96 {
97 static gboolean is_log_open = FALSE;
98 va_list var_args;
99 gchar *s;
100 const gchar *tty;
101
102 if (!is_log_open)
103 {
104 openlog ("pkexec",
105 LOG_PID,
106 LOG_AUTHPRIV); /* security/authorization messages (private) */
107 is_log_open = TRUE;
108 }
109
110 va_start (var_args, format);
111 s = g_strdup_vprintf (format, var_args);
112 va_end (var_args);
113
114 tty = ttyname (0);
115 if (tty == NULL)
116 tty = "unknown";
117
118 /* first complain to syslog */
119 syslog (level,
120 "%s: %s [USER=%s] [TTY=%s] [CWD=%s] [COMMAND=%s]",
121 original_user_name,
122 s,
123 pw->pw_name,
124 tty,
125 original_cwd,
126 command_line);
127
128 /* and then on stderr */
129 if (print_to_stderr)
130 g_printerr ("%s\n", s);
131
132 g_free (s);
133 }
134
135 /* ---------------------------------------------------------------------------------------------------- */
136
137 #ifdef POLKIT_AUTHFW_PAM
138 static int
139 pam_conversation_function (int n,
140 const struct pam_message **msg,
141 struct pam_response **resp,
142 void *data)
143 {
144 g_assert_not_reached ();
145 return PAM_CONV_ERR;
146 }
147
148 /* A work around for:
149 * https://bugzilla.redhat.com/show_bug.cgi?id=753882
150 */
151 static gboolean
152 xdg_runtime_dir_is_owned_by (const char *path,
153 uid_t target_uid)
154 {
155 struct stat stbuf;
156
157 return stat (path, &stbuf) == 0 &&
158 stbuf.st_uid == target_uid;
159 }
160
161 static gboolean
162 open_session (const gchar *user_to_auth,
163 uid_t target_uid)
164 {
165 gboolean ret;
166 gint rc;
167 pam_handle_t *pam_h;
168 char **envlist;
169 struct pam_conv conversation;
170
171 ret = FALSE;
172
173 pam_h = NULL;
174
175 conversation.conv = pam_conversation_function;
176 conversation.appdata_ptr = NULL;
177
178 /* start the pam stack */
179 rc = pam_start ("polkit-1",
180 user_to_auth,
181 &conversation,
182 &pam_h);
183 if (rc != PAM_SUCCESS)
184 {
185 g_printerr ("pam_start() failed: %s\n", pam_strerror (pam_h, rc));
186 goto out;
187 }
188
189 /* open a session */
190 rc = pam_open_session (pam_h,
191 0); /* flags */
192 if (rc != PAM_SUCCESS)
193 {
194 g_printerr ("pam_open_session() failed: %s\n", pam_strerror (pam_h, rc));
195 goto out;
196 }
197
198 ret = TRUE;
199
200 envlist = pam_getenvlist (pam_h);
201 if (envlist != NULL)
202 {
203 guint n;
204 for (n = 0; envlist[n]; n++)
205 {
206 const char *envitem = envlist[n];
207
208 if (g_str_has_prefix (envitem, "XDG_RUNTIME_DIR="))
209 {
210 const char *eq = strchr (envitem, '=');
211 g_assert (eq);
212 if (!xdg_runtime_dir_is_owned_by (eq + 1, target_uid))
213 continue;
214 }
215
216 putenv (envlist[n]);
217 }
218 free (envlist);
219 }
220
221 out:
222 if (pam_h != NULL)
223 pam_end (pam_h, rc);
224 return ret;
225 }
226 #endif /* POLKIT_AUTHFW_PAM */
227
228 /* ---------------------------------------------------------------------------------------------------- */
229
230 static gboolean
231 fdwalk_close_on_exec (guint fd_bottom)
232 {
233 /* On Linux we might have a very high FD limit, instead of blindly iterating
234 * try g_fdwalk_set_cloexec() first, then fallback to close_range() second,
235 * and if that also is not available or doesn't work, look at /proc/self/fd/
236 * and iterate over the actual open FDs instead */
237 #if GLIB_CHECK_VERSION (2, 80, 0)
238 /* This is newer than baseline so a warning is raised, but it's used with a
239 * compile time check so it's ok */
240 #pragma GCC diagnostic push
241 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
242 return g_fdwalk_set_cloexec (fd_bottom) == 0;
243 #pragma GCC diagnostic pop
244 #else
245 /* TODO: drop these fallbacks once the glib baseline is at least 2.80.0 */
246
247 #if defined(CLOSE_RANGE_CLOEXEC)
248 if (close_range (fd_bottom, G_MAXINT, CLOSE_RANGE_CLOEXEC) == 0)
249 return TRUE;
250 #endif
251
252 #ifdef __linux__
253 GDir *dir;
254 const gchar *file;
255 GError *error;
256
257 dir = g_dir_open ("/proc/self/fd/", 0, &error);
258 if (dir != NULL)
259 {
260 while ((file = g_dir_read_name (dir)) != NULL)
261 {
262 gchar *endptr;
263 guint64 fd;
264
265 fd = g_ascii_strtoull (file, &endptr, 10);
266 if (*endptr != '\0' || fd > G_MAXINT)
267 {
268 g_printerr ("Invalid file descriptor, ignoring: %s\n", file);
269 continue;
270 }
271
272 if (fd < fd_bottom)
273 continue;
274
275 if (fcntl (fd, F_SETFD, FD_CLOEXEC) != 0 && errno != EBADF)
276 {
277 g_dir_close (dir);
278 return FALSE;
279 }
280 }
281
282 g_dir_close (dir);
283 return TRUE;
284 }
285 /* If we can't open procfs for any reason fallback to the old method */
286 #endif /* __linux__ */
287
288 gint max_fd = sysconf (_SC_OPEN_MAX);
289
290 for (gint fd = fd_bottom; fd < max_fd; fd++)
291 {
292 if (fcntl (fd, F_SETFD, FD_CLOEXEC) != 0 && errno != EBADF)
293 return FALSE;
294 }
295
296 return TRUE;
297 #endif /* g_fdwalk_set_cloexec () */
298 }
299
300 /* ---------------------------------------------------------------------------------------------------- */
301
302 static gchar *
303 find_action_for_path (PolkitAuthority *authority,
304 const gchar *path,
305 const gchar *argv1,
306 gboolean *allow_gui)
307 {
308 GList *l;
309 GList *actions;
310 gchar *action_id;
311 GError *error;
312
313 actions = NULL;
314 action_id = NULL;
315 error = NULL;
316 *allow_gui = FALSE;
317
318 actions = polkit_authority_enumerate_actions_sync (authority,
319 NULL,
320 &error);
321 if (actions == NULL)
322 {
323 g_warning ("Error enumerating actions: %s", error->message);
324 g_error_free (error);
325 goto out;
326 }
327
328 for (l = actions; l != NULL; l = l->next)
329 {
330 PolkitActionDescription *action_desc = POLKIT_ACTION_DESCRIPTION (l->data);
331 const gchar *argv1_for_action;
332 const gchar *path_for_action;
333 const gchar *allow_gui_annotation;
334
335 path_for_action = polkit_action_description_get_annotation (action_desc, "org.freedesktop.policykit.exec.path");
336 if (path_for_action == NULL)
337 continue;
338
339 argv1_for_action = polkit_action_description_get_annotation (action_desc, "org.freedesktop.policykit.exec.argv1");
340
341 if (g_strcmp0 (path_for_action, path) == 0)
342 {
343 /* check against org.freedesktop.policykit.exec.argv1 but only if set */
344 if (argv1_for_action != NULL)
345 {
346 if (g_strcmp0 (argv1, argv1_for_action) != 0)
347 continue;
348 }
349
350 action_id = g_strdup (polkit_action_description_get_action_id (action_desc));
351
352 allow_gui_annotation = polkit_action_description_get_annotation (action_desc, "org.freedesktop.policykit.exec.allow_gui");
353
354 if (allow_gui_annotation != NULL && strlen (allow_gui_annotation) > 0)
355 *allow_gui = TRUE;
356
357 goto out;
358 }
359 }
360
361 out:
362 g_list_foreach (actions, (GFunc) g_object_unref, NULL);
363 g_list_free (actions);
364
365 /* Fall back to org.freedesktop.policykit.exec */
366
367 if (action_id == NULL)
368 action_id = g_strdup ("org.freedesktop.policykit.exec");
369
370 return action_id;
371 }
372
373 /* ---------------------------------------------------------------------------------------------------- */
374
375 static gboolean
376 is_valid_shell (const gchar *shell)
377 {
378 gboolean ret;
379 gchar *contents;
380 gchar **shells;
381 GError *error;
382 guint n;
383
384 ret = FALSE;
385
386 contents = NULL;
387 shells = NULL;
388
389 error = NULL;
390 if (!g_file_get_contents ("/etc/shells",
391 &contents,
392 NULL, /* gsize *length */
393 &error))
394 {
395 g_printerr ("Error getting contents of /etc/shells: %s\n", error->message);
396 g_error_free (error);
397 goto out;
398 }
399
400 shells = g_strsplit (contents, "\n", 0);
401 for (n = 0; shells != NULL && shells[n] != NULL; n++)
402 {
403 if (shells[n][0] == '/' && g_strcmp0 (shell, shells[n]) == 0)
404 {
405 ret = TRUE;
406 goto out;
407 }
408 }
409
410 out:
411 g_free (contents);
412 g_strfreev (shells);
413 return ret;
414 }
415
416 static gboolean
417 validate_environment_variable (const gchar *key,
418 const gchar *value)
419 {
420 gboolean ret;
421
422 /* Generally we bail if any environment variable value contains
423 *
424 * - '/' characters
425 * - '%' characters
426 * - '..' substrings
427 */
428
429 g_return_val_if_fail (key != NULL, FALSE);
430 g_return_val_if_fail (value != NULL, FALSE);
431
432 ret = FALSE;
433
434 /* special case $SHELL */
435 if (g_strcmp0 (key, "SHELL") == 0)
436 {
437 /* check if it's in /etc/shells */
438 if (!is_valid_shell (value))
439 {
440 log_message (LOG_CRIT, TRUE,
441 "The value for the SHELL variable was not found in the /etc/shells file");
442 g_printerr ("\n"
443 "This incident has been reported.\n");
444 goto out;
445 }
446 }
447 else if ((g_strcmp0 (key, "XAUTHORITY") != 0 && strstr (value, "/") != NULL) ||
448 strstr (value, "%") != NULL ||
449 strstr (value, "..") != NULL)
450 {
451 log_message (LOG_CRIT, TRUE,
452 "The value for environment variable %s contains suspicious content",
453 key);
454 g_printerr ("\n"
455 "This incident has been reported.\n");
456 goto out;
457 }
458
459 ret = TRUE;
460
461 out:
462 return ret;
463 }
464
465
466 /* ---------------------------------------------------------------------------------------------------- */
467
468 int
469 main (int argc, char *argv[])
470 {
471 guint n;
472 guint ret;
473 gint rc;
474 gboolean opt_show_help;
475 gboolean opt_show_version;
476 gboolean opt_disable_internal_agent;
477 gboolean opt_keep_cwd;
478 PolkitAuthority *authority;
479 PolkitAuthorizationResult *result;
480 PolkitSubject *subject;
481 PolkitDetails *details;
482 GError *error;
483 gchar *action_id;
484 gboolean allow_gui;
485 gchar **exec_argv;
486 gchar *path_abs;
487 gchar *path;
488 struct passwd pwstruct;
489 gchar pwbuf[8192];
490 gchar *s;
491 const gchar *environment_variables_to_save[] = {
492 "SHELL",
493 "LANG",
494 "LINGUAS",
495 "LANGUAGE",
496 "LC_COLLATE",
497 "LC_CTYPE",
498 "LC_MESSAGES",
499 "LC_MONETARY",
500 "LC_NUMERIC",
501 "LC_TIME",
502 "LC_ALL",
503 "TERM",
504 "COLORTERM",
505
506 /* By default we don't allow running X11 apps, as it does not work in the
507 * general case. See
508 *
509 * https://bugs.freedesktop.org/show_bug.cgi?id=17970#c26
510 *
511 * and surrounding comments for a lot of discussion about this.
512 *
513 * However, it can be enabled for some selected and tested legacy programs
514 * which previously used e. g. gksu, by setting the
515 * org.freedesktop.policykit.exec.allow_gui annotation to a nonempty value.
516 * See https://bugs.freedesktop.org/show_bug.cgi?id=38769 for details.
517 */
518 "DISPLAY",
519 "XAUTHORITY",
520 NULL
521 };
522 GPtrArray *saved_env;
523 gchar *opt_user;
524 pid_t pid_of_caller;
525 gpointer local_agent_handle;
526
527
528 /*
529 * If 'pkexec' is called THIS wrong, someone's probably evil-doing. Don't be nice, just bail out.
530 */
531 if (argc<1)
532 {
533 exit(127);
534 }
535
536 ret = 127;
537 authority = NULL;
538 subject = NULL;
539 details = NULL;
540 result = NULL;
541 action_id = NULL;
542 saved_env = NULL;
543 path_abs = NULL;
544 path = NULL;
545 exec_argv = NULL;
546 command_line = NULL;
547 cmdline_short = NULL;
548 opt_user = NULL;
549 local_agent_handle = NULL;
550
551 /* Disable remote file access from GIO. */
552 setenv ("GIO_USE_VFS", "local", 1);
553
554 /* First process options and find the command-line to invoke. Avoid using fancy library routines
555 * that depend on environment variables since we haven't cleared the environment just yet.
556 */
557 opt_show_help = FALSE;
558 opt_show_version = FALSE;
559 opt_disable_internal_agent = FALSE;
560 opt_keep_cwd = FALSE;
561 for (n = 1; n < (guint) argc; n++)
562 {
563 if (strcmp (argv[n], "--help") == 0)
564 {
565 opt_show_help = TRUE;
566 }
567 else if (strcmp (argv[n], "--version") == 0)
568 {
569 opt_show_version = TRUE;
570 }
571 else if (strcmp (argv[n], "--user") == 0 || strcmp (argv[n], "-u") == 0)
572 {
573 n++;
574 if (n >= (guint) argc)
575 {
576 usage (argc, argv);
577 goto out;
578 }
579
580 if (opt_user != NULL)
581 {
582 g_printerr ("--user specified twice\n");
583 goto out;
584 }
585 opt_user = g_strdup (argv[n]);
586 }
587 else if (strcmp (argv[n], "--disable-internal-agent") == 0)
588 {
589 opt_disable_internal_agent = TRUE;
590 }
591 else if (strcmp (argv[n], "--keep-cwd") == 0)
592 {
593 opt_keep_cwd = TRUE;
594 }
595 else
596 {
597 break;
598 }
599 }
600
601 if (opt_show_help)
602 {
603 usage (argc, argv);
604 ret = 0;
605 goto out;
606 }
607 else if (opt_show_version)
608 {
609 g_print ("pkexec version %s\n", PACKAGE_VERSION);
610 ret = 0;
611 goto out;
612 }
613
614 /* check for correct invocation */
615 if (geteuid () != 0)
616 {
617 g_printerr ("pkexec must be setuid root\n");
618 goto out;
619 }
620
621 original_user_name = g_strdup (g_get_user_name ());
622 if (original_user_name == NULL)
623 {
624 g_printerr ("Error getting user name.\n");
625 goto out;
626 }
627
628 if ((original_cwd = g_get_current_dir ()) == NULL)
629 {
630 g_printerr ("Error getting cwd: %s\n",
631 g_strerror (errno));
632 goto out;
633 }
634
635 if (opt_user == NULL)
636 opt_user = g_strdup ("root");
637
638 /* Look up information about the user we care about - yes, the return
639 * value of this function is a bit funky
640 */
641 rc = getpwnam_r (opt_user, &pwstruct, pwbuf, sizeof pwbuf, &pw);
642 if (rc == 0 && pw == NULL)
643 {
644 g_printerr ("User `%s' does not exist.\n", opt_user);
645 goto out;
646 }
647 else if (pw == NULL)
648 {
649 g_printerr ("Error getting information for user `%s': %s\n", opt_user, g_strerror (rc));
650 goto out;
651 }
652
653 /* Now figure out the command-line to run - argv is guaranteed to be NULL-terminated, see
654 *
655 * http://lkml.indiana.edu/hypermail/linux/kernel/0409.2/0287.html
656 *
657 * but do check this is the case.
658 *
659 * We also try to locate the program in the path if a non-absolute path is given.
660 *
661 * And then we resolve the real path of the program.
662 */
663 g_assert (argv[argc] == NULL);
664 path = g_strdup (argv[n]);
665 if (path == NULL)
666 {
667 GPtrArray *shell_argv;
668
669 path = g_strdup (pwstruct.pw_shell);
670 if (!path)
671 {
672 g_printerr ("No shell configured or error retrieving pw_shell\n");
673 goto out;
674 }
675 /* If you change this, be sure to change the if (!command_line)
676 case below too */
677 command_line = g_strdup (path);
678 shell_argv = g_ptr_array_new ();
679 g_ptr_array_add (shell_argv, path);
680 g_ptr_array_add (shell_argv, NULL);
681 exec_argv = (char**)g_ptr_array_free (shell_argv, FALSE);
682 }
683 if (path[0] != '/')
684 {
685 /* g_find_program_in_path() is not susceptible to attacks via the environment */
686 s = g_find_program_in_path (path);
687 if (s == NULL)
688 {
689 g_printerr ("Cannot run program %s: %s\n", path, strerror (ENOENT));
690 goto out;
691 }
692 g_free (path);
693 path = s;
694
695 /* argc<2 and pkexec runs just shell, argv is guaranteed to be null-terminated.
696 * /-less shell shouldn't happen, but let's be defensive and don't write to null-termination
697 */
698 if (argv[n] != NULL)
699 {
700 /* Must copy because we might replace path later on. */
701 path_abs = g_strdup(path);
702 /* argv[n:] is used as argv arguments to execv(). The called program
703 * sees the original called path, but we make sure it's absolute. */
704 if (path_abs != NULL)
705 argv[n] = path_abs;
706 }
707 }
708
709 s = realpath(path, NULL);
710 if (s != NULL)
711 {
712 /* The called program resolved to the canonical location. We don't update
713 * argv[n] this time. The called program still sees the original
714 * called path. This is very important for multi-call binaries like
715 * busybox. */
716 g_free (path);
717 path = s;
718 }
719 if (access (path, F_OK) != 0)
720 {
721 g_printerr ("Error accessing %s: %s\n", path, g_strerror (errno));
722 goto out;
723 }
724
725 if (!command_line)
726 {
727 /* If you change this, be sure to change the path == NULL case
728 above too */
729 command_line = g_strjoinv (" ", argv + n);
730 exec_argv = argv + n;
731 }
732
733 /* now save the environment variables we care about */
734 saved_env = g_ptr_array_new ();
735 for (n = 0; environment_variables_to_save[n] != NULL; n++)
736 {
737 const gchar *key = environment_variables_to_save[n];
738 const gchar *value;
739
740 value = g_getenv (key);
741 if (value == NULL)
742 continue;
743
744 /* To qualify for the paranoia goldstar - we validate the value of each
745 * environment variable passed through - this is to attempt to avoid
746 * exploits in (potentially broken) programs launched via pkexec(1).
747 */
748 if (!validate_environment_variable (key, value))
749 goto out;
750
751 g_ptr_array_add (saved_env, g_strdup (key));
752 g_ptr_array_add (saved_env, g_strdup (value));
753 }
754
755 /* $XAUTHORITY is "special" - if unset, we need to set it to ~/.Xauthority. Yes,
756 * this is broken but it's unfortunately how things work (see fdo #51623 for
757 * details)
758 */
759 if (g_getenv ("XAUTHORITY") == NULL)
760 {
761 const gchar *home;
762
763 /* pre-2.36 GLib does not examine $HOME (it always looks in /etc/passwd) and
764 * this is not what we want
765 */
766 home = g_getenv ("HOME");
767 if (home == NULL)
768 home = g_get_home_dir ();
769
770 if (home != NULL)
771 {
772 g_ptr_array_add (saved_env, g_strdup ("XAUTHORITY"));
773 g_ptr_array_add (saved_env, g_build_filename (home, ".Xauthority", NULL));
774 }
775 }
776
777 /* Nuke the environment to get a well-known and sanitized environment to avoid attacks
778 * via e.g. the DBUS_SYSTEM_BUS_ADDRESS environment variable and similar.
779 */
780 if (clearenv () != 0)
781 {
782 g_printerr ("Error clearing environment: %s\n", g_strerror (errno));
783 goto out;
784 }
785
786 /* make sure we are nuked if the parent process dies */
787 #if defined(__linux__)
788 if (prctl (PR_SET_PDEATHSIG, SIGTERM) != 0)
789 {
790 g_printerr ("prctl(PR_SET_PDEATHSIG, SIGTERM) failed: %s\n", g_strerror (errno));
791 goto out;
792 }
793 #elif defined(__FreeBSD__)
794 int _sig = SIGTERM;
795 if (procctl (P_PID, 0, PROC_PDEATHSIG_CTL, &_sig) != 0)
796 {
797 g_printerr ("procctl(2) failed: %s\n", g_strerror (errno));
798 goto out;
799 }
800 #else
801 #warning "Please add OS specific code to catch when the parent dies"
802 #endif
803
804 /* Figure out the parent process */
805 pid_of_caller = getppid ();
806 if (pid_of_caller == 1)
807 {
808 /* getppid() can return 1 if the parent died (meaning that we are reaped
809 * by /sbin/init); In that case we simpy bail.
810 */
811 g_printerr ("Refusing to render service to dead parents.\n");
812 goto out;
813 }
814
815 /* This process we want to check an authorization for is the process
816 * that launched us - our parent process.
817 *
818 * At the time the parent process fork()'ed and exec()'ed us, the
819 * process had the same real-uid that we have now. So we use this
820 * real-uid instead of of looking it up to avoid TOCTTOU issues
821 * (consider the parent process exec()'ing a setuid helper).
822 *
823 * On the other hand, the monotonic process start-time is guaranteed
824 * to never change so it's safe to look that up given only the PID
825 * since we are guaranteed to be nuked if the parent goes away
826 * (cf. the prctl(2) call above).
827 */
828 subject = polkit_unix_process_new_for_owner (pid_of_caller,
829 0, /* 0 means "look up start-time in /proc" */
830 getuid ());
831 /* really double-check the invariants guaranteed by the PolkitUnixProcess class */
832 g_assert (subject != NULL);
833 g_assert (polkit_unix_process_get_pid (POLKIT_UNIX_PROCESS (subject)) == pid_of_caller);
834 g_assert (polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)) >= 0);
835 g_assert (polkit_unix_process_get_start_time (POLKIT_UNIX_PROCESS (subject)) > 0);
836
837 error = NULL;
838 authority = polkit_authority_get_sync (NULL /* GCancellable* */, &error);
839 if (authority == NULL)
840 {
841 g_printerr ("Error getting authority: %s\n", error->message);
842 g_error_free (error);
843 goto out;
844 }
845
846 g_assert (path != NULL);
847 g_assert (exec_argv != NULL);
848 action_id = find_action_for_path (authority,
849 path,
850 exec_argv[1],
851 &allow_gui);
852 g_assert (action_id != NULL);
853
854 details = polkit_details_new ();
855 polkit_details_insert (details, "user", pw->pw_name);
856 if (pw->pw_gecos != NULL)
857 polkit_details_insert (details, "user.gecos", pw->pw_gecos);
858 if (pw->pw_gecos != NULL && strlen (pw->pw_gecos) > 0)
859 s = g_strdup_printf ("%s (%s)", pw->pw_gecos, pw->pw_name);
860 else
861 s = g_strdup_printf ("%s", pw->pw_name);
862 polkit_details_insert (details, "user.display", s);
863 g_free (s);
864 polkit_details_insert (details, "program", path);
865 polkit_details_insert (details, "command_line", command_line);
866
867 cmdline_short = g_strdup(command_line);
868 if (cmdline_short == NULL)
869 {
870 g_printerr ("Failed to allocate memory for shortened command line.\n");
871 goto out;
872 }
873 if (strlen(command_line) > 80)
874 g_stpcpy(g_stpcpy( cmdline_short + 38, " ... " ),
875 command_line + strlen(command_line) - 37 );
876 polkit_details_insert (details, "cmdline_short", cmdline_short);
877
878 if (g_strcmp0 (action_id, "org.freedesktop.policykit.exec") == 0)
879 {
880 if (pw->pw_uid == 0)
881 {
882 polkit_details_insert (details, "polkit.message",
883 /* Translators: message shown when trying to run a program as root. Do not
884 * translate the $(program) fragment - it will be expanded to the path
885 * of the program e.g. /bin/bash.
886 */
887 N_("Authentication is needed to run `$(cmdline_short)' as the super user"));
888 }
889 else
890 {
891 polkit_details_insert (details, "polkit.message",
892 /* Translators: message shown when trying to run a program as another user.
893 * Do not translate the $(program) or $(user) fragments - the former will
894 * be expanded to the path of the program e.g. "/bin/bash" and the latter
895 * to the user e.g. "John Doe (johndoe)" or "johndoe".
896 */
897 N_("Authentication is needed to run `$(cmdline_short)' as user $(user.display)"));
898 }
899 }
900 polkit_details_insert (details, "polkit.gettext_domain", GETTEXT_PACKAGE);
901
902 try_again:
903 error = NULL;
904 result = polkit_authority_check_authorization_sync (authority,
905 subject,
906 action_id,
907 details,
908 POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION,
909 NULL,
910 &error);
911 if (result == NULL)
912 {
913 g_printerr ("Error checking for authorization %s: %s\n",
914 action_id,
915 error ? error->message : "Could not verify; error object not present.");
916 goto out;
917 }
918
919 if (polkit_authorization_result_get_is_authorized (result))
920 {
921 /* do nothing */
922 }
923 else if (polkit_authorization_result_get_is_challenge (result))
924 {
925 if (local_agent_handle == NULL && !opt_disable_internal_agent)
926 {
927 PolkitAgentListener *listener;
928 error = NULL;
929 /* this will fail if we can't find a controlling terminal */
930 listener = polkit_agent_text_listener_new (NULL, &error);
931 if (listener == NULL)
932 {
933 g_printerr ("Error creating textual authentication agent: %s\n", error->message);
934 g_error_free (error);
935 goto out;
936 }
937 local_agent_handle = polkit_agent_listener_register (listener,
938 POLKIT_AGENT_REGISTER_FLAGS_RUN_IN_THREAD,
939 subject,
940 NULL, /* object_path */
941 NULL, /* GCancellable */
942 &error);
943 g_object_unref (listener);
944 if (local_agent_handle == NULL)
945 {
946 g_printerr ("Error registering local authentication agent: %s\n", error->message);
947 g_error_free (error);
948 goto out;
949 }
950 g_object_unref (result);
951 result = NULL;
952 goto try_again;
953 }
954 else
955 {
956 g_printerr ("Error executing command as another user: No authentication agent found.\n");
957 goto out;
958 }
959 }
960 else
961 {
962 if (polkit_authorization_result_get_dismissed (result))
963 {
964 log_message (LOG_WARNING, TRUE,
965 "Error executing command as another user: Request dismissed");
966 ret = 126;
967 }
968 else
969 {
970 log_message (LOG_WARNING, TRUE,
971 "Error executing command as another user: Not authorized");
972 g_printerr ("\n"
973 "This incident has been reported.\n");
974 }
975 goto out;
976 }
977
978 /* Set PATH to a safe list */
979 g_ptr_array_add (saved_env, g_strdup ("PATH"));
980 if (pw->pw_uid != 0)
981 s = g_strdup_printf ("/usr/bin:/bin:/usr/sbin:/sbin:%s/bin", pw->pw_dir);
982 else
983 s = g_strdup_printf ("/usr/sbin:/usr/bin:/sbin:/bin:%s/bin", pw->pw_dir);
984 g_ptr_array_add (saved_env, s);
985 g_ptr_array_add (saved_env, g_strdup ("LOGNAME"));
986 g_ptr_array_add (saved_env, g_strdup (pw->pw_name));
987 g_ptr_array_add (saved_env, g_strdup ("USER"));
988 g_ptr_array_add (saved_env, g_strdup (pw->pw_name));
989 g_ptr_array_add (saved_env, g_strdup ("HOME"));
990 g_ptr_array_add (saved_env, g_strdup (pw->pw_dir));
991
992 s = g_strdup_printf ("%d", getuid ());
993 g_ptr_array_add (saved_env, g_strdup ("PKEXEC_UID"));
994 g_ptr_array_add (saved_env, g_strdup (s));
995 g_ptr_array_add (saved_env, g_strdup ("SUDO_UID")); /* compat with sudo */
996 g_ptr_array_add (saved_env, s);
997
998 s = g_strdup_printf ("%d", getgid ());
999 g_ptr_array_add (saved_env, g_strdup ("SUDO_GID")); /* compat with sudo */
1000 g_ptr_array_add (saved_env, s);
1001
1002 /* set the environment */
1003 for (n = 0; n < saved_env->len - 1; n += 2)
1004 {
1005 const gchar *key = saved_env->pdata[n];
1006 const gchar *value = saved_env->pdata[n + 1];
1007
1008 /* Only set $DISPLAY and $XAUTHORITY when explicitly allowed in the .policy */
1009 if (!allow_gui &&
1010 (strcmp (key, "DISPLAY") == 0 || strcmp (key, "XAUTHORITY") == 0))
1011 continue;
1012
1013 if (!g_setenv (key, value, TRUE))
1014 {
1015 g_printerr ("Error setting environment variable %s to '%s': %s\n",
1016 key,
1017 value,
1018 g_strerror (errno));
1019 goto out;
1020 }
1021 }
1022
1023 /* set close_on_exec on all file descriptors except stdin, stdout, stderr */
1024 if (!fdwalk_close_on_exec (3))
1025 {
1026 g_printerr ("Error setting close-on-exec for file descriptors\n");
1027 goto out;
1028 }
1029
1030 /* if not changing to uid 0, become uid 0 before changing to the user */
1031 if (pw->pw_uid != 0)
1032 {
1033 (void) setreuid (0, 0);
1034 if ((geteuid () != 0) || (getuid () != 0))
1035 {
1036 g_printerr ("Error becoming uid 0: %s\n", g_strerror (errno));
1037 goto out;
1038 }
1039 }
1040
1041 /* open session - with PAM enabled, this runs the open_session() part of the PAM
1042 * stack - this includes applying limits via pam_limits.so but also other things
1043 * requested via the current PAM configuration.
1044 *
1045 * NOTE NOTE NOTE: pam_limits.so doesn't seem to clear existing limits - e.g.
1046 *
1047 * $ ulimit -t
1048 * unlimited
1049 *
1050 * $ su -
1051 * Password:
1052 * # ulimit -t
1053 * unlimited
1054 * # logout
1055 *
1056 * $ ulimit -t 1000
1057 * $ ulimit -t
1058 * 1000
1059 * $ su -
1060 * Password:
1061 * # ulimit -t
1062 * 1000
1063 *
1064 * TODO: The question here is whether we should clear the limits before applying them?
1065 * As evident above, neither su(1) (and, for that matter, nor sudo(8)) does this.
1066 */
1067 #ifdef POLKIT_AUTHFW_PAM
1068 if (!open_session (pw->pw_name,
1069 pw->pw_uid))
1070 {
1071 goto out;
1072 }
1073 #endif /* POLKIT_AUTHFW_PAM */
1074
1075 /* become the user */
1076 if (setgroups (0, NULL) != 0)
1077 {
1078 g_printerr ("Error setting groups: %s\n", g_strerror (errno));
1079 goto out;
1080 }
1081 if (initgroups (pw->pw_name, pw->pw_gid) != 0)
1082 {
1083 g_printerr ("Error initializing groups for %s: %s\n", pw->pw_name, g_strerror (errno));
1084 goto out;
1085 }
1086 (void) setregid (pw->pw_gid, pw->pw_gid);
1087 (void) setreuid (pw->pw_uid, pw->pw_uid);
1088 if ((geteuid () != pw->pw_uid) || (getuid () != pw->pw_uid) ||
1089 (getegid () != pw->pw_gid) || (getgid () != pw->pw_gid))
1090 {
1091 g_printerr ("Error becoming real+effective uid %d and gid %d: %s\n", pw->pw_uid, pw->pw_gid, g_strerror (errno));
1092 goto out;
1093 }
1094
1095 /* change to home directory */
1096 if (!opt_keep_cwd)
1097 {
1098 if (chdir (pw->pw_dir) != 0)
1099 {
1100 g_printerr ("Error changing to home directory %s: %s\n", pw->pw_dir, g_strerror (errno));
1101 goto out;
1102 }
1103 }
1104
1105 /* Log the fact that we're executing a command */
1106 log_message (LOG_NOTICE, FALSE, "Executing command");
1107
1108 /* exec the program */
1109 if (execv (path, exec_argv) != 0)
1110 {
1111 g_printerr ("Error executing %s: %s\n", path, g_strerror (errno));
1112 goto out;
1113 }
1114
1115 /* if exec doesn't fail, it never returns... */
1116 g_assert_not_reached ();
1117
1118 out:
1119 /* if applicable, nuke the local authentication agent */
1120 if (local_agent_handle != NULL)
1121 polkit_agent_listener_unregister (local_agent_handle);
1122
1123 if (result != NULL)
1124 g_object_unref (result);
1125
1126 g_free (action_id);
1127
1128 if (details != NULL)
1129 g_object_unref (details);
1130
1131 if (subject != NULL)
1132 g_object_unref (subject);
1133
1134 if (authority != NULL)
1135 g_object_unref (authority);
1136
1137 if (saved_env != NULL)
1138 {
1139 g_ptr_array_foreach (saved_env, (GFunc) g_free, NULL);
1140 g_ptr_array_free (saved_env, TRUE);
1141 }
1142
1143 g_free (original_cwd);
1144 g_free (path_abs);
1145 g_free (path);
1146 g_free (command_line);
1147 g_free (cmdline_short);
1148 g_free (opt_user);
1149 g_free (original_user_name);
1150
1151 return ret;
1152 }
1153