Debian Codegraph @

src/polkit/polkitunixprocess.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 #ifdef __linux__
23 #include <fcntl.h>
24 #include <sys/ioctl.h>
25 #include <sys/stat.h>
26 #include <sys/sysmacros.h>
27 #include <sys/vfs.h>
28 #endif
29 #include <sys/types.h>
30 #ifdef HAVE_FREEBSD
31 #include <sys/param.h>
32 #include <sys/sysctl.h>
33 #include <sys/user.h>
34 #endif
35 #ifdef HAVE_NETBSD
36 #include <sys/param.h>
37 #include <sys/sysctl.h>
38 #endif
39 #ifdef HAVE_OPENBSD
40 #include <sys/sysctl.h>
41 #endif
42 #ifdef HAVE_PIDFD_OPEN
43 #include <sys/syscall.h>
44 #endif /* HAVE_PIDFD_OPEN */
45 #include <stdlib.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <stdio.h>
49
50 #include "polkitunixprocess.h"
51 #include "polkitsubject.h"
52 #include "polkitprivate.h"
53 #include "polkiterror.h"
54
55 /**
56 * SECTION:polkitunixprocess
57 * @title: PolkitUnixProcess
58 * @short_description: Unix processs
59 *
60 * An object for representing a UNIX process. In order to be reliable and
61 * race-free, this requires support for PID File Descriptors in the kernel,
62 * dbus-daemon/broker and systemd. With this functionality, we can reliably
63 * track processes without risking PID reuse and race conditions, and compare
64 * them.
65 *
66 * NOTE: If PID FDs are not available, this object will fall back to using
67 * PIDs, and this designed is now known broken; a mechanism to exploit a delay
68 * in start time in the Linux kernel was identified. Avoid
69 * calling polkit_subject_equal() to compare two processes.
70 *
71 * To uniquely identify processes, both the process id and the start
72 * time of the process (a monotonic increasing value representing the
73 * time since the kernel was started) is used.
74 *
75 * NOTE: This object stores, and provides access to, the real UID of the
76 * process. That value can change over time (with set*uid*(2) and exec*(2)).
77 * Checks whether an operation is allowed need to take care to use the UID
78 * value as of the time when the operation was made (or, following the open()
79 * privilege check model, when the connection making the operation possible
80 * was initiated). That is usually done by initializing this with
81 * polkit_unix_process_new_for_owner() with trusted data.
82 */
83
84 /* See https://gitlab.freedesktop.org/polkit/polkit/issues/75
85
86 But quoting the original email in full here to ensure it's preserved:
87
88 From: Jann Horn <[email protected]>
89 Subject: [SECURITY] polkit: temporary auth hijacking via PID reuse and non-atomic fork
90 Date: Wednesday, October 10, 2018 5:34 PM
91
92 When a (non-root) user attempts to e.g. control systemd units in the system
93 instance from an active session over DBus, the access is gated by a polkit
94 policy that requires "auth_admin_keep" auth. This results in an auth prompt
95 being shown to the user, asking the user to confirm the action by entering the
96 password of an administrator account.
97
98 After the action has been confirmed, the auth decision for "auth_admin_keep" is
99 cached for up to five minutes. Subject to some restrictions, similar actions can
100 then be performed in this timespan without requiring re-auth:
101
102 - The PID of the DBus client requesting the new action must match the PID of
103 the DBus client requesting the old action (based on SO_PEERCRED information
104 forwarded by the DBus daemon).
105 - The "start time" of the client's PID (as seen in /proc/$pid/stat, field 22)
106 must not have changed. The granularity of this timestamp is in the
107 millisecond range.
108 - polkit polls every two seconds whether a process with the expected start time
109 still exists. If not, the temporary auth entry is purged.
110
111 Without the start time check, this would obviously be buggy because an attacker
112 could simply wait for the legitimate client to disappear, then create a new
113 client with the same PID.
114
115 Unfortunately, the start time check is bypassable because fork() is not atomic.
116 Looking at the source code of copy_process() in the kernel:
117
118 p->start_time = ktime_get_ns();
119 p->real_start_time = ktime_get_boot_ns();
120 [...]
121 retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
122 if (retval)
123 goto bad_fork_cleanup_io;
124
125 if (pid != &init_struct_pid) {
126 pid = alloc_pid(p->nsproxy->pid_ns_for_children);
127 if (IS_ERR(pid)) {
128 retval = PTR_ERR(pid);
129 goto bad_fork_cleanup_thread;
130 }
131 }
132
133 The ktime_get_boot_ns() call is where the "start time" of the process is
134 recorded. The alloc_pid() call is where a free PID is allocated. In between
135 these, some time passes; and because the copy_thread_tls() call between them can
136 access userspace memory when sys_clone() is invoked through the 32-bit syscall
137 entry point, an attacker can even stall the kernel arbitrarily long at this
138 point (by supplying a pointer into userspace memory that is associated with a
139 userfaultfd or is backed by a custom FUSE filesystem).
140
141 This means that an attacker can immediately call sys_clone() when the victim
142 process is created, often resulting in a process that has the exact same start
143 time reported in procfs; and then the attacker can delay the alloc_pid() call
144 until after the victim process has died and the PID assignment has cycled
145 around. This results in an attacker process that polkit can't distinguish from
146 the victim process.
147 */
148
149
150 /**
151 * PolkitUnixProcess:
152 *
153 * The #PolkitUnixProcess struct should not be accessed directly.
154 */
155 struct _PolkitUnixProcess
156 {
157 GObject parent_instance;
158
159 gint pid;
160 guint64 start_time;
161 guint64 cgroupid;
162 gint uid;
163 gint pidfd;
164 gint ppidfd;
165 guint ctty;
166 gboolean pidfd_is_safe;
167 GArray *gids;
168 };
169
170 struct _PolkitUnixProcessClass
171 {
172 GObjectClass parent_class;
173 };
174
175 enum
176 {
177 PROP_0,
178 PROP_PID,
179 PROP_PPID,
180 PROP_START_TIME,
181 PROP_CGROUPID,
182 PROP_UID,
183 PROP_PIDFD,
184 PROP_PIDFD_IS_SAFE,
185 PROP_PPIDFD,
186 PROP_CTTY,
187 PROP_GIDS,
188 };
189
190 static void subject_iface_init (PolkitSubjectIface *subject_iface);
191
192 static guint64 get_start_time_for_pid (gint pid,
193 GError **error);
194
195 static gint
196 get_ppidfd_for_pidfd (gint pidfd,
197 GError **error);
198
199 static guint
200 get_ctty_number_for_pidfd (gint pidfd,
201 GError **error);
202
203 static guint64
204 get_cgroupid_for_pidfd (gint pidfd,
205 GError **error);
206
207 #if defined(HAVE_FREEBSD) || defined(HAVE_NETBSD) || defined(HAVE_OPENBSD)
208 static gboolean get_kinfo_proc (gint pid,
209 #if defined(HAVE_NETBSD)
210 struct kinfo_proc2 *p);
211 #else
212 struct kinfo_proc *p);
213 #endif
214 #endif
215
216 G_DEFINE_TYPE_WITH_CODE (PolkitUnixProcess, polkit_unix_process, G_TYPE_OBJECT,
217 G_IMPLEMENT_INTERFACE (POLKIT_TYPE_SUBJECT, subject_iface_init)
218 );
219
220 static void
221 polkit_unix_process_init (PolkitUnixProcess *unix_process)
222 {
223 unix_process->uid = -1;
224 unix_process->pidfd = -1;
225 unix_process->ppidfd = -1;
226 }
227
228 static void
229 polkit_unix_process_get_property (GObject *object,
230 guint prop_id,
231 GValue *value,
232 GParamSpec *pspec)
233 {
234 PolkitUnixProcess *unix_process = POLKIT_UNIX_PROCESS (object);
235
236 switch (prop_id)
237 {
238 case PROP_PID:
239 g_value_set_int (value, polkit_unix_process_get_pid (unix_process));
240 break;
241
242 case PROP_PPID:
243 g_value_set_int (value, polkit_unix_process_get_ppid (unix_process));
244 break;
245
246 case PROP_UID:
247 g_value_set_int (value, unix_process->uid);
248 break;
249
250 case PROP_GIDS:
251 g_value_set_boxed (value, unix_process->gids);
252 break;
253
254 case PROP_PIDFD:
255 g_value_set_int (value, unix_process->pidfd);
256 break;
257
258 case PROP_PPIDFD:
259 g_value_set_int (value, unix_process->ppidfd);
260 break;
261
262 case PROP_CTTY:
263 g_value_set_uint (value, unix_process->ctty);
264 break;
265
266 case PROP_PIDFD_IS_SAFE:
267 g_value_set_boolean (value, unix_process->pidfd_is_safe);
268 break;
269
270 case PROP_START_TIME:
271 g_value_set_uint64 (value, unix_process->start_time);
272 break;
273
274 case PROP_CGROUPID:
275 g_value_set_uint64 (value, unix_process->cgroupid);
276 break;
277
278 default:
279 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
280 break;
281 }
282 }
283
284 static void
285 polkit_unix_process_set_property (GObject *object,
286 guint prop_id,
287 const GValue *value,
288 GParamSpec *pspec)
289 {
290 PolkitUnixProcess *unix_process = POLKIT_UNIX_PROCESS (object);
291
292 switch (prop_id)
293 {
294 case PROP_PID:
295 polkit_unix_process_set_pid (unix_process, g_value_get_int (value));
296 break;
297
298 case PROP_UID:
299 polkit_unix_process_set_uid (unix_process, g_value_get_int (value));
300 break;
301
302 case PROP_GIDS:
303 polkit_unix_process_set_gids (unix_process, g_value_get_boxed (value));
304 break;
305
306 case PROP_PIDFD:
307 polkit_unix_process_set_pidfd (unix_process, g_value_get_int (value));
308 break;
309
310 case PROP_START_TIME:
311 polkit_unix_process_set_start_time (unix_process, g_value_get_uint64 (value));
312 break;
313
314 default:
315 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
316 break;
317 }
318 }
319
320 static gint
321 polkit_unix_process_get_pid_from_pidfd (gint pidfd,
322 GError **error)
323 {
324 gint result;
325 gchar *contents;
326 gchar **lines;
327 gchar filename[64];
328 guint n;
329
330 g_return_val_if_fail (pidfd >= 0, -1);
331 g_return_val_if_fail (error == NULL || *error == NULL, -1);
332
333 result = -1;
334 lines = NULL;
335 contents = NULL;
336
337 g_snprintf (filename, sizeof filename, "/proc/self/fdinfo/%d", pidfd);
338 if (!g_file_get_contents (filename,
339 &contents,
340 NULL,
341 error))
342 goto out;
343
344 lines = g_strsplit (contents, "\n", -1);
345 for (n = 0; lines != NULL && lines[n] != NULL; n++)
346 {
347 gint pid;
348 if (!g_str_has_prefix (lines[n], "Pid:"))
349 continue;
350 if (sscanf (lines[n] + 4, "%d", &pid) != 1)
351 g_set_error (error,
352 POLKIT_ERROR,
353 POLKIT_ERROR_FAILED,
354 "Unexpected line `%s' in file %s",
355 lines[n],
356 filename);
357 else
358 result = pid;
359 goto out;
360 }
361
362 g_set_error (error,
363 POLKIT_ERROR,
364 POLKIT_ERROR_FAILED,
365 "Didn't find any line starting with `Pid:' in file %s",
366 filename);
367
368 out:
369 g_strfreev (lines);
370 g_free (contents);
371 return result;
372 }
373
374 static void
375 polkit_unix_process_constructed (GObject *object)
376 {
377 PolkitUnixProcess *process = POLKIT_UNIX_PROCESS (object);
378
379 /* sets pidfd, start_time and uid in case they are unset */
380
381 /* We didn't open it ourselves here, so we must have got it
382 * from D-Bus, mark it as safe to use */
383 if (process->pidfd >= 0)
384 process->pidfd_is_safe = TRUE;
385
386 #ifdef HAVE_PIDFD_OPEN
387 if (process->pid > 0 && process->pidfd < 0)
388 {
389 gint pidfd = (int) syscall (SYS_pidfd_open, process->pid, 0);
390 if (pidfd >= 0)
391 {
392 process->pidfd = pidfd;
393 process->pid = 0;
394 }
395 }
396
397 if (process->pidfd >= 0)
398 {
399 GError *error;
400 error = NULL;
401
402 if (process->ppidfd < 0)
403 {
404 process->ppidfd = get_ppidfd_for_pidfd (process->pidfd, &error);
405 if (error != NULL)
406 {
407 g_error_free (error);
408 error = NULL;
409 process->ppidfd = -1;
410 }
411 }
412
413 process->cgroupid = get_cgroupid_for_pidfd (process->pidfd, &error);
414 if (error != NULL)
415 {
416 g_error_free (error);
417 error = NULL;
418 }
419
420 process->ctty = get_ctty_number_for_pidfd (process->pidfd, &error);
421 if (error != NULL)
422 g_error_free (error);
423 }
424 #endif /* HAVE_PIDFD_OPEN */
425
426 if (process->start_time == 0)
427 process->start_time = get_start_time_for_pid (polkit_unix_process_get_pid (process), NULL);
428
429 if (process->uid == -1)
430 {
431 GError *error;
432 error = NULL;
433 process->uid = polkit_unix_process_get_racy_uid__ (process, &error);
434 if (error != NULL)
435 {
436 process->uid = -1;
437 g_error_free (error);
438 }
439 }
440
441 if (G_OBJECT_CLASS (polkit_unix_process_parent_class)->constructed != NULL)
442 G_OBJECT_CLASS (polkit_unix_process_parent_class)->constructed (object);
443 }
444
445 static void
446 polkit_unix_process_finalize (GObject *object)
447 {
448 PolkitUnixProcess *process = POLKIT_UNIX_PROCESS (object);
449
450 if (process->pidfd >= 0)
451 {
452 close (process->pidfd);
453 process->pidfd = -1;
454 }
455
456 if (process->ppidfd >= 0)
457 {
458 close (process->ppidfd);
459 process->ppidfd = -1;
460 }
461
462 if (process->gids)
463 g_array_unref (process->gids);
464
465 if (G_OBJECT_CLASS (polkit_unix_process_parent_class)->finalize != NULL)
466 G_OBJECT_CLASS (polkit_unix_process_parent_class)->finalize (object);
467 }
468
469 static void
470 polkit_unix_process_class_init (PolkitUnixProcessClass *klass)
471 {
472 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
473
474 gobject_class->get_property = polkit_unix_process_get_property;
475 gobject_class->set_property = polkit_unix_process_set_property;
476 gobject_class->constructed = polkit_unix_process_constructed;
477 gobject_class->finalize = polkit_unix_process_finalize;
478
479 /**
480 * PolkitUnixProcess:pid:
481 *
482 * The UNIX process id.
483 */
484 g_object_class_install_property (gobject_class,
485 PROP_PID,
486 g_param_spec_int ("pid",
487 "Process ID",
488 "The UNIX process ID",
489 0,
490 G_MAXINT,
491 0,
492 G_PARAM_CONSTRUCT |
493 G_PARAM_READWRITE |
494 G_PARAM_STATIC_NAME |
495 G_PARAM_STATIC_BLURB |
496 G_PARAM_STATIC_NICK));
497
498 /**
499 * PolkitUnixProcess:uid:
500 *
501 * The UNIX user id of the process or -1 if unknown.
502 *
503 * Note that this is the real user-id, not the effective user-id.
504 */
505 g_object_class_install_property (gobject_class,
506 PROP_UID,
507 g_param_spec_int ("uid",
508 "User ID",
509 "The UNIX user ID",
510 G_MININT,
511 G_MAXINT,
512 -1,
513 G_PARAM_CONSTRUCT |
514 G_PARAM_READWRITE |
515 G_PARAM_STATIC_NAME |
516 G_PARAM_STATIC_BLURB |
517 G_PARAM_STATIC_NICK));
518
519 /**
520 * PolkitUnixProcess:start-time:
521 *
522 * The start time of the process.
523 */
524 g_object_class_install_property (gobject_class,
525 PROP_START_TIME,
526 g_param_spec_uint64 ("start-time",
527 "Start Time",
528 "The start time of the process, since the machine booted",
529 0,
530 G_MAXUINT64,
531 0,
532 G_PARAM_CONSTRUCT |
533 G_PARAM_READWRITE |
534 G_PARAM_STATIC_NAME |
535 G_PARAM_STATIC_BLURB |
536 G_PARAM_STATIC_NICK));
537
538 /**
539 * PolkitUnixProcess:cgroupid:
540 *
541 * The start time of the process.
542 */
543 g_object_class_install_property (gobject_class,
544 PROP_CGROUPID,
545 g_param_spec_uint64 ("cgroupid",
546 "ControlGroup ID",
547 "The ID of the Control Group of the process",
548 0,
549 G_MAXUINT64,
550 0,
551 G_PARAM_READABLE |
552 G_PARAM_STATIC_NAME |
553 G_PARAM_STATIC_BLURB |
554 G_PARAM_STATIC_NICK));
555
556 /**
557 * PolkitUnixProcess:pidfd:
558 *
559 * The UNIX process id file descriptor.
560 */
561 g_object_class_install_property (gobject_class,
562 PROP_PIDFD,
563 g_param_spec_int ("pidfd",
564 "Process ID FD",
565 "The UNIX process ID file descriptor",
566 -1,
567 G_MAXINT,
568 -1,
569 G_PARAM_CONSTRUCT |
570 G_PARAM_READWRITE |
571 G_PARAM_STATIC_NAME |
572 G_PARAM_STATIC_BLURB |
573 G_PARAM_STATIC_NICK));
574
575 /**
576 * PolkitUnixProcess:ppidfd:
577 *
578 * The UNIX process' parent id file descriptor.
579 */
580 g_object_class_install_property (gobject_class,
581 PROP_PPIDFD,
582 g_param_spec_int ("ppidfd",
583 "Process' parent ID FD",
584 "The UNIX process' parent ID file descriptor",
585 -1,
586 G_MAXINT,
587 -1,
588 G_PARAM_READABLE |
589 G_PARAM_STATIC_NAME |
590 G_PARAM_STATIC_BLURB |
591 G_PARAM_STATIC_NICK));
592
593 /**
594 * PolkitUnixProcess:ctty:
595 *
596 * The UNIX process controlling TTY.
597 */
598 g_object_class_install_property (gobject_class,
599 PROP_CTTY,
600 g_param_spec_uint ("ctty",
601 "Process controlling TTY",
602 "The UNIX process controlling TTY",
603 0,
604 G_MAXINT,
605 0,
606 G_PARAM_READABLE |
607 G_PARAM_STATIC_NAME |
608 G_PARAM_STATIC_BLURB |
609 G_PARAM_STATIC_NICK));
610
611 /**
612 * PolkitUnixProcess:pidfd_is_safe:
613 *
614 * Whether the UNIX process id file descriptor is safe end-to-end
615 * or it was opened locally.
616 */
617 g_object_class_install_property (gobject_class,
618 PROP_PIDFD_IS_SAFE,
619 g_param_spec_boolean ("pidfd-is-safe",
620 "Process ID FD",
621 "Whether the UNIX process ID file descriptor is safe",
622 FALSE,
623 G_PARAM_READABLE |
624 G_PARAM_STATIC_NAME |
625 G_PARAM_STATIC_BLURB |
626 G_PARAM_STATIC_NICK));
627
628 /**
629 * PolkitUnixProcess:gids:
630 *
631 * The UNIX group ids of the process.
632 */
633 g_object_class_install_property (gobject_class,
634 PROP_GIDS,
635 g_param_spec_boxed ("gids",
636 "Group IDs",
637 "The UNIX group IDs",
638 G_TYPE_ARRAY,
639 G_PARAM_CONSTRUCT |
640 G_PARAM_READWRITE |
641 G_PARAM_STATIC_NAME |
642 G_PARAM_STATIC_BLURB |
643 G_PARAM_STATIC_NICK));
644 }
645
646 /**
647 * polkit_unix_process_get_uid:
648 * @process: A #PolkitUnixProcess.
649 *
650 * Gets the user id for @process. Note that this is the real user-id,
651 * not the effective user-id.
652 *
653 * NOTE: The UID may change over time, so the returned value may not match the
654 * current state of the underlying process; or the UID may have been set by
655 * polkit_unix_process_new_for_owner() or polkit_unix_process_set_uid(),
656 * in which case it may not correspond to the actual UID of the referenced
657 * process at all (at any point in time).
658 *
659 * Returns: The user id for @process or -1 if unknown.
660 */
661 gint
662 polkit_unix_process_get_uid (PolkitUnixProcess *process)
663 {
664 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), -1);
665 return process->uid;
666 }
667
668 /**
669 * polkit_unix_process_set_uid:
670 * @process: A #PolkitUnixProcess.
671 * @uid: The user id to set for @process or -1 to unset it.
672 *
673 * Sets the (real, not effective) user id for @process.
674 */
675 void
676 polkit_unix_process_set_uid (PolkitUnixProcess *process,
677 gint uid)
678 {
679 g_return_if_fail (POLKIT_IS_UNIX_PROCESS (process));
680 process->uid = uid;
681 }
682
683 /**
684 * polkit_unix_process_get_gids:
685 * @process: A #PolkitUnixProcess.
686 *
687 * Gets the group ids for @process. Note that this is the real group-ids,
688 * not the effective group-ids.
689 *
690 * Returns: (element-type GArray) (transfer full) (allow-none): a #GArray
691 * of #gid_t containing the group ids for @process or NULL if unknown,
692 * as a new reference to the array, caller must deref it when done.
693 */
694 GArray *
695 polkit_unix_process_get_gids (PolkitUnixProcess *process)
696 {
697 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), NULL);
698 return process->gids ? g_array_ref (process->gids) : NULL;
699 }
700
701 /**
702 * polkit_unix_process_set_gids:
703 * @process: A #PolkitUnixProcess.
704 * @gids: (element-type GArray): A #GList of #gid_t containing the group
705 * ids to set for @process or NULL to unset them.
706 * A reference to @gids is taken.
707 *
708 * Sets the (real, not effective) group ids for @process.
709 */
710 void
711 polkit_unix_process_set_gids (PolkitUnixProcess *process,
712 GArray *gids)
713 {
714 g_return_if_fail (POLKIT_IS_UNIX_PROCESS (process));
715 if (process->gids)
716 g_array_unref (g_steal_pointer (&process->gids));
717 if (gids)
718 process->gids = g_array_ref (gids);
719 }
720
721 /**
722 * polkit_unix_process_get_pid:
723 * @process: A #PolkitUnixProcess.
724 *
725 * Gets the process id for @process.
726 *
727 * Returns: The process id for @process.
728 */
729 gint
730 polkit_unix_process_get_pid (PolkitUnixProcess *process)
731 {
732 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), 0);
733
734 if (process->pidfd >= 0)
735 {
736 GError *error = NULL;
737 gint pid = polkit_unix_process_get_pid_from_pidfd(process->pidfd, &error);
738
739 if (pid > 0)
740 return pid;
741
742 if (error)
743 g_error_free (error);
744 return 0;
745 }
746
747 return process->pid;
748 }
749
750 /**
751 * polkit_unix_process_get_ppid:
752 * @process: A #PolkitUnixProcess.
753 *
754 * Gets the process' parent id for @process.
755 *
756 * Returns: The process id for the parent of @process.
757 */
758 gint
759 polkit_unix_process_get_ppid (PolkitUnixProcess *process)
760 {
761 GError *error = NULL;
762 gint ppid;
763
764 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), 0);
765
766 if (process->ppidfd < 0)
767 return 0;
768
769 ppid = polkit_unix_process_get_pid_from_pidfd(process->ppidfd, &error);
770 if (ppid > 0)
771 return ppid;
772
773 if (error)
774 g_error_free (error);
775 return 0;
776 }
777
778 /**
779 * polkit_unix_process_get_cgroupid:
780 * @process: A #PolkitUnixProcess.
781 *
782 * Gets the cgroupid of @process.
783 *
784 * Returns: The cgroupid of @process.
785 */
786 guint64
787 polkit_unix_process_get_cgroupid (PolkitUnixProcess *process)
788 {
789 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), 0);
790 return process->cgroupid;
791 }
792
793 /**
794 * polkit_unix_process_get_start_time:
795 * @process: A #PolkitUnixProcess.
796 *
797 * Gets the start time of @process.
798 *
799 * Returns: The start time of @process.
800 */
801 guint64
802 polkit_unix_process_get_start_time (PolkitUnixProcess *process)
803 {
804 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), 0);
805 return process->start_time;
806 }
807
808 /**
809 * polkit_unix_process_set_start_time:
810 * @process: A #PolkitUnixProcess.
811 * @start_time: The start time for @pid.
812 *
813 * Set the start time of @process.
814 */
815 void
816 polkit_unix_process_set_start_time (PolkitUnixProcess *process,
817 guint64 start_time)
818 {
819 g_return_if_fail (POLKIT_IS_UNIX_PROCESS (process));
820 process->start_time = start_time;
821 }
822
823 /**
824 * polkit_unix_process_set_pid:
825 * @process: A #PolkitUnixProcess.
826 * @pid: A process id.
827 *
828 * Sets @pid for @process.
829 */
830 void
831 polkit_unix_process_set_pid (PolkitUnixProcess *process,
832 gint pid)
833 {
834 g_return_if_fail (POLKIT_IS_UNIX_PROCESS (process));
835
836 #ifdef HAVE_PIDFD_OPEN
837 if (process->pidfd >= 0)
838 {
839 close (process->pidfd);
840 process->pidfd = -1;
841 process->pidfd_is_safe = FALSE;
842 }
843 if (pid > 0)
844 {
845 gint pidfd = (int) syscall (SYS_pidfd_open, process->pid, 0);
846 if (pidfd >= 0)
847 {
848 GError *error;
849 error = NULL;
850
851 process->pidfd_is_safe = FALSE;
852 process->pidfd = pidfd;
853 process->pid = 0;
854 if (process->ppidfd >= 0)
855 {
856 close (process->ppidfd);
857 process->ppidfd = -1;
858 }
859 process->ppidfd = get_ppidfd_for_pidfd (process->pidfd, &error);
860 if (error != NULL)
861 {
862 g_error_free (error);
863 process->ppidfd = -1;
864 }
865 return;
866 }
867 }
868 #endif /* HAVE_PIDFD_OPEN */
869
870 process->pid = pid;
871 }
872
873 /**
874 * polkit_unix_process_get_pidfd:
875 * @process: A #PolkitUnixProcess.
876 *
877 * Gets the process id file descriptor for @process.
878 *
879 * Returns: The process id file descriptor for @process.
880 */
881 gint
882 polkit_unix_process_get_pidfd (PolkitUnixProcess *process)
883 {
884 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), -1);
885 return process->pidfd;
886 }
887
888 /**
889 * polkit_unix_process_get_ppidfd:
890 * @process: A #PolkitUnixProcess.
891 *
892 * Gets the process' parent id file descriptor for @process.
893 *
894 * Returns: The process id file descriptor for the parent of @process.
895 */
896 gint
897 polkit_unix_process_get_ppidfd (PolkitUnixProcess *process)
898 {
899 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), -1);
900 return process->ppidfd;
901 }
902
903 /**
904 * polkit_unix_process_get_ctty:
905 * @process: A #PolkitUnixProcess.
906 *
907 * Gets the controlling TTY for @process.
908 *
909 * Returns: The dev_t of the controlling TTY of @process.
910 */
911 guint
912 polkit_unix_process_get_ctty (PolkitUnixProcess *process)
913 {
914 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), 0);
915 return process->ctty;
916 }
917
918 /**
919 * polkit_unix_process_get_pidfd_is_safe:
920 * @process: A #PolkitUnixProcess.
921 *
922 * Checks if the process id file descriptor for @process is safe
923 * or if it was opened locally and thus vulnerable to reuse.
924 *
925 * Returns: TRUE or FALSE.
926 */
927 gboolean
928 polkit_unix_process_get_pidfd_is_safe (PolkitUnixProcess *process)
929 {
930 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), FALSE);
931 return process->pidfd_is_safe;
932 }
933
934 /**
935 * polkit_unix_process_set_pidfd:
936 * @process: A #PolkitUnixProcess.
937 * @pidfd: A process id file descriptor.
938 *
939 * Sets @pidfd for @process.
940 */
941 void
942 polkit_unix_process_set_pidfd (PolkitUnixProcess *process,
943 gint pidfd)
944 {
945 g_return_if_fail (POLKIT_IS_UNIX_PROCESS (process));
946 if (process->pidfd >= 0)
947 {
948 close (process->pidfd);
949 process->pidfd_is_safe = FALSE;
950 }
951 process->pidfd = pidfd;
952
953 if (process->pidfd >= 0)
954 {
955 GError *error;
956 error = NULL;
957
958 if (process->ppidfd >= 0)
959 {
960 close (process->ppidfd);
961 process->ppidfd = -1;
962 }
963 process->ppidfd = get_ppidfd_for_pidfd (process->pidfd, &error);
964 if (error != NULL)
965 {
966 g_error_free (error);
967 process->ppidfd = -1;
968 }
969 }
970 }
971
972 /**
973 * polkit_unix_process_new:
974 * @pid: The process id.
975 *
976 * Creates a new #PolkitUnixProcess for @pid.
977 *
978 * The uid and start time of the process will be looked up in using
979 * e.g. the <filename>/proc</filename> filesystem depending on the
980 * platform in use.
981 *
982 * Returns: (transfer full): A #PolkitSubject. Free with g_object_unref().
983 */
984 PolkitSubject *
985 polkit_unix_process_new (gint pid)
986 {
987 return POLKIT_SUBJECT (g_object_new (POLKIT_TYPE_UNIX_PROCESS,
988 "pid", pid,
989 NULL));
990 }
991
992 /**
993 * polkit_unix_process_new_full:
994 * @pid: The process id.
995 * @start_time: The start time for @pid.
996 *
997 * Creates a new #PolkitUnixProcess object for @pid and @start_time.
998 *
999 * The uid of the process will be looked up in using e.g. the
1000 * <filename>/proc</filename> filesystem depending on the platform in
1001 * use.
1002 *
1003 * Returns: (transfer full): A #PolkitSubject. Free with g_object_unref().
1004 */
1005 PolkitSubject *
1006 polkit_unix_process_new_full (gint pid,
1007 guint64 start_time)
1008 {
1009 return POLKIT_SUBJECT (g_object_new (POLKIT_TYPE_UNIX_PROCESS,
1010 "pid", pid,
1011 "start_time", start_time,
1012 NULL));
1013 }
1014
1015 /**
1016 * polkit_unix_process_new_for_owner:
1017 * @pid: The process id.
1018 * @start_time: The start time for @pid or 0 to look it up in e.g. <filename>/proc</filename>.
1019 * @uid: The (real, not effective) uid of the owner of @pid or -1 to look it up in e.g. <filename>/proc</filename>.
1020 *
1021 * Creates a new #PolkitUnixProcess object for @pid, @start_time and @uid.
1022 *
1023 * Returns: (transfer full): A #PolkitSubject. Free with g_object_unref().
1024 */
1025 PolkitSubject *
1026 polkit_unix_process_new_for_owner (gint pid,
1027 guint64 start_time,
1028 gint uid)
1029 {
1030 return POLKIT_SUBJECT (g_object_new (POLKIT_TYPE_UNIX_PROCESS,
1031 "pid", pid,
1032 "start_time", start_time,
1033 "uid", uid,
1034 NULL));
1035 }
1036
1037 /**
1038 * polkit_unix_process_new_pidfd:
1039 * @pidfd: The process id file descriptor.
1040 * @uid: The (real, not effective) uid of the owner of @pid or -1 to look it up in e.g. <filename>/proc</filename>.
1041 * @gids: (element-type gint) (allow-none): The (real, not effective) gids of the owner of @pid or %NULL.
1042 *
1043 * Creates a new #PolkitUnixProcess object for @pidfd and @uid.
1044 *
1045 * Returns: (transfer full): A #PolkitSubject. Free with g_object_unref().
1046 */
1047 PolkitSubject *
1048 polkit_unix_process_new_pidfd (gint pidfd,
1049 gint uid,
1050 GArray *gids)
1051 {
1052 return POLKIT_SUBJECT (g_object_new (POLKIT_TYPE_UNIX_PROCESS,
1053 "pidfd", pidfd,
1054 "uid", uid,
1055 "gids", gids,
1056 NULL));
1057 }
1058
1059 static guint
1060 polkit_unix_process_hash (PolkitSubject *subject)
1061 {
1062 PolkitUnixProcess *process = POLKIT_UNIX_PROCESS (subject);
1063
1064 return g_direct_hash (GSIZE_TO_POINTER ((polkit_unix_process_get_pid(process) + process->start_time))) ;
1065 }
1066
1067 static gboolean
1068 polkit_unix_process_equal (PolkitSubject *a,
1069 PolkitSubject *b)
1070 {
1071 PolkitUnixProcess *process_a;
1072 PolkitUnixProcess *process_b;
1073 gint pid_a, pid_b;
1074 gint pidfd_a, pidfd_b;
1075
1076 process_a = POLKIT_UNIX_PROCESS (a);
1077 process_b = POLKIT_UNIX_PROCESS (b);
1078
1079 pid_a = polkit_unix_process_get_pid(process_a);
1080 pid_b = polkit_unix_process_get_pid(process_b);
1081
1082 pidfd_a = polkit_unix_process_get_pidfd(process_a);
1083 pidfd_b = polkit_unix_process_get_pidfd(process_b);
1084
1085 return
1086 (pid_a > 0) &&
1087 (pid_b > 0) &&
1088 (pid_a == pid_b) &&
1089 ((pidfd_a >= 0 && pidfd_b >= 0) ||
1090 (process_a->start_time == process_b->start_time));
1091 }
1092
1093 static gchar *
1094 polkit_unix_process_to_string (PolkitSubject *subject)
1095 {
1096 PolkitUnixProcess *process = POLKIT_UNIX_PROCESS (subject);
1097 gint pid = polkit_unix_process_get_pid(process);
1098 if (pid <= 0)
1099 return g_strdup_printf ("unix-process:unknown");
1100
1101 return g_strdup_printf ("unix-process:%d:%" G_GUINT64_FORMAT, pid, process->start_time);
1102 }
1103
1104 static gboolean
1105 polkit_unix_process_exists_sync (PolkitSubject *subject,
1106 GCancellable *cancellable,
1107 GError **error)
1108 {
1109 PolkitUnixProcess *process = POLKIT_UNIX_PROCESS (subject);
1110 GError *local_error;
1111 guint64 start_time;
1112 gboolean ret;
1113 gint pid;
1114
1115 ret = TRUE;
1116
1117 pid = polkit_unix_process_get_pid(process);
1118 if (pid <= 0)
1119 return FALSE;
1120
1121 /* If we have both a valid PID and a PID FD then we know the process is still the
1122 * same and it hasn't exited. */
1123 if (polkit_unix_process_get_pidfd(process) >= 0)
1124 return TRUE;
1125
1126 local_error = NULL;
1127 start_time = get_start_time_for_pid (pid, &local_error);
1128 if (local_error != NULL)
1129 {
1130 /* Don't propagate the error - it just means there is no process with this pid */
1131 g_error_free (local_error);
1132 ret = FALSE;
1133 }
1134 else
1135 {
1136 if (start_time != process->start_time)
1137 {
1138 ret = FALSE;
1139 }
1140 }
1141
1142 return ret;
1143 }
1144
1145 static void
1146 polkit_unix_process_exists (PolkitSubject *subject,
1147 GCancellable *cancellable,
1148 GAsyncReadyCallback callback,
1149 gpointer user_data)
1150 {
1151 GSimpleAsyncResult *simple;
1152 simple = g_simple_async_result_new (G_OBJECT (subject),
1153 callback,
1154 user_data,
1155 polkit_unix_process_exists);
1156 g_simple_async_result_complete (simple);
1157 g_object_unref (simple);
1158 }
1159
1160 static gboolean
1161 polkit_unix_process_exists_finish (PolkitSubject *subject,
1162 GAsyncResult *res,
1163 GError **error)
1164 {
1165 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1166
1167 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == polkit_unix_process_exists);
1168
1169 return polkit_unix_process_exists_sync (subject,
1170 NULL,
1171 error);
1172 }
1173
1174
1175 static void
1176 subject_iface_init (PolkitSubjectIface *subject_iface)
1177 {
1178 subject_iface->hash = polkit_unix_process_hash;
1179 subject_iface->equal = polkit_unix_process_equal;
1180 subject_iface->to_string = polkit_unix_process_to_string;
1181 subject_iface->exists = polkit_unix_process_exists;
1182 subject_iface->exists_finish = polkit_unix_process_exists_finish;
1183 subject_iface->exists_sync = polkit_unix_process_exists_sync;
1184 }
1185
1186 #ifdef HAVE_SOLARIS
1187 static int
1188 get_pid_psinfo (pid_t pid, struct psinfo *ps)
1189 {
1190 char pname[32];
1191 int procfd;
1192
1193 (void) snprintf(pname, sizeof(pname), "/proc/%d/psinfo", pid);
1194 if ((procfd = open(pname, O_RDONLY)) == -1)
1195 {
1196 return -1;
1197 }
1198 if (read(procfd, ps, sizeof(struct psinfo)) < 0)
1199 {
1200 (void) close(procfd);
1201 return -1;
1202 }
1203 (void) close(procfd);
1204 return 0;
1205 }
1206 #endif
1207
1208 #ifdef HAVE_FREEBSD
1209 static gboolean
1210 get_kinfo_proc (pid_t pid, struct kinfo_proc *p)
1211 {
1212 int mib[4];
1213 size_t len;
1214
1215 len = 4;
1216 sysctlnametomib ("kern.proc.pid", mib, &len);
1217
1218 len = sizeof (struct kinfo_proc);
1219 mib[3] = pid;
1220
1221 if (sysctl (mib, 4, p, &len, NULL, 0) == -1)
1222 return FALSE;
1223
1224 return TRUE;
1225 }
1226 #endif
1227
1228 #if defined(HAVE_NETBSD) || defined(HAVE_OPENBSD)
1229 static gboolean
1230 get_kinfo_proc (gint pid,
1231 #ifdef HAVE_NETBSD
1232 struct kinfo_proc2 *p)
1233 #else
1234 struct kinfo_proc *p)
1235 #endif
1236 {
1237 int name[6];
1238 u_int namelen;
1239 size_t sz;
1240
1241 sz = sizeof(*p);
1242 namelen = 0;
1243 name[namelen++] = CTL_KERN;
1244 #ifdef HAVE_NETBSD
1245 name[namelen++] = KERN_PROC2;
1246 #else
1247 name[namelen++] = KERN_PROC;
1248 #endif
1249 name[namelen++] = KERN_PROC_PID;
1250 name[namelen++] = pid;
1251 name[namelen++] = sz;
1252 name[namelen++] = 1;
1253
1254 if (sysctl (name, namelen, p, &sz, NULL, 0) == -1)
1255 return FALSE;
1256
1257 return TRUE;
1258 }
1259 #endif
1260
1261 static guint64
1262 get_start_time_for_pid (pid_t pid,
1263 GError **error)
1264 {
1265 guint64 start_time;
1266 #if !defined(HAVE_FREEBSD) && !defined(HAVE_NETBSD) && !defined(HAVE_OPENBSD)
1267 gchar *filename;
1268 gchar *contents;
1269 size_t length;
1270 gchar **tokens;
1271 guint num_tokens;
1272 gchar *p;
1273 gchar *endp;
1274
1275 start_time = 0;
1276 contents = NULL;
1277
1278 filename = g_strdup_printf ("/proc/%d/stat", pid);
1279
1280 if (!g_file_get_contents (filename, &contents, &length, error))
1281 goto out;
1282
1283 /* start time is the token at index 19 after the '(process name)' entry - since only this
1284 * field can contain the ')' character, search backwards for this to avoid malicious
1285 * processes trying to fool us
1286 */
1287 p = strrchr (contents, ')');
1288 if (p == NULL)
1289 {
1290 g_set_error (error,
1291 POLKIT_ERROR,
1292 POLKIT_ERROR_FAILED,
1293 "Error parsing file %s",
1294 filename);
1295 goto out;
1296 }
1297 p += 2; /* skip ') ' */
1298 if (p - contents >= (int) length)
1299 {
1300 g_set_error (error,
1301 POLKIT_ERROR,
1302 POLKIT_ERROR_FAILED,
1303 "Error parsing file %s",
1304 filename);
1305 goto out;
1306 }
1307
1308 tokens = g_strsplit (p, " ", 0);
1309
1310 num_tokens = g_strv_length (tokens);
1311
1312 if (num_tokens < 20)
1313 {
1314 g_set_error (error,
1315 POLKIT_ERROR,
1316 POLKIT_ERROR_FAILED,
1317 "Error parsing file %s",
1318 filename);
1319 goto out;
1320 }
1321
1322 start_time = strtoull (tokens[19], &endp, 10);
1323 if (endp == tokens[19])
1324 {
1325 g_set_error (error,
1326 POLKIT_ERROR,
1327 POLKIT_ERROR_FAILED,
1328 "Error parsing file %s",
1329 filename);
1330 goto out;
1331 }
1332
1333 g_strfreev (tokens);
1334
1335 out:
1336 g_free (filename);
1337 g_free (contents);
1338 #else
1339 #ifdef HAVE_NETBSD
1340 struct kinfo_proc2 p;
1341 #else
1342 struct kinfo_proc p;
1343 #endif
1344
1345 start_time = 0;
1346
1347 if (! get_kinfo_proc (pid, &p))
1348 {
1349 g_set_error (error,
1350 POLKIT_ERROR,
1351 POLKIT_ERROR_FAILED,
1352 "Error obtaining start time for %d (%s)",
1353 (gint) pid,
1354 g_strerror (errno));
1355 goto out;
1356 }
1357
1358 #ifdef HAVE_FREEBSD
1359 start_time = (guint64) p.ki_start.tv_sec;
1360 #else
1361 start_time = (guint64) p.p_ustart_sec;
1362 #endif
1363
1364 out:
1365 #endif
1366
1367 return start_time;
1368 }
1369
1370 static guint64
1371 get_cgroupid_for_pidfd (gint pidfd,
1372 GError **error)
1373 {
1374 #ifdef __linux__
1375 guint64 cgroupid;
1376 gint pid;
1377 gchar *filename;
1378 gchar *cgroup_path;
1379 gchar *contents;
1380 size_t length;
1381 gchar *p;
1382 struct file_handle *fhp;
1383 int mount_id;
1384
1385 pid = 0;
1386 filename = NULL;
1387 contents = NULL;
1388 cgroup_path = NULL;
1389 cgroupid = 0;
1390 fhp = NULL;
1391
1392 g_return_val_if_fail (pidfd >= 0, 0);
1393
1394 pid = polkit_unix_process_get_pid_from_pidfd (pidfd, error);
1395 if (pid <= 0)
1396 return 0;
1397
1398 filename = g_strdup_printf ("/proc/%d/cgroup", pid);
1399
1400 if (!g_file_get_contents (filename, &contents, &length, error))
1401 goto out;
1402
1403 /* The format is '0::/cgroup/path\n */
1404 p = strchr (contents, ':');
1405 if (p == NULL)
1406 {
1407 g_set_error (error,
1408 POLKIT_ERROR,
1409 POLKIT_ERROR_FAILED,
1410 "Error parsing file %s",
1411 filename);
1412 goto out;
1413 }
1414 p += 2; /* skip '::' */
1415 if (p - contents >= (int) length)
1416 {
1417 g_set_error (error,
1418 POLKIT_ERROR,
1419 POLKIT_ERROR_FAILED,
1420 "Error parsing file %s",
1421 filename);
1422 goto out;
1423 }
1424
1425 contents[length - 1] = '\0'; /* remove the newline */
1426
1427 cgroup_path = g_strdup_printf ("/sys/fs/cgroup%s", p);
1428
1429 /* We know in advance the size of the field, cgroupid is a uint64 */
1430 fhp = g_malloc (offsetof(struct file_handle, f_handle) + sizeof(guint64));
1431 *fhp = (struct file_handle) {
1432 .handle_bytes = sizeof(guint64),
1433 .handle_type = 0xfe, /* FILEID_KERNFS from linux/exportfs.h */
1434 };
1435
1436 if (name_to_handle_at (AT_FDCWD, cgroup_path, fhp, &mount_id, 0) < 0)
1437 {
1438 g_set_error (error,
1439 POLKIT_ERROR,
1440 POLKIT_ERROR_FAILED,
1441 "Error getting cgroup ID for process %d: %s",
1442 pid,
1443 g_strerror (errno));
1444 goto out;
1445 }
1446
1447 cgroupid = *(guint64 *) fhp->f_handle;
1448
1449 /* Ensure the process is still running */
1450 if (pid != polkit_unix_process_get_pid_from_pidfd (pidfd, error))
1451 {
1452 if (error && *error == NULL)
1453 g_set_error (error,
1454 POLKIT_ERROR,
1455 POLKIT_ERROR_FAILED,
1456 "Process exited while parsing cgroup id");
1457 goto out;
1458 }
1459
1460 out:
1461 g_free (contents);
1462 g_free (filename);
1463 g_free (cgroup_path);
1464 free (fhp);
1465
1466 return cgroupid;
1467 #else /* !__linux__ */
1468 return 0;
1469 #endif /* __linux__ */
1470 }
1471
1472 static guint
1473 get_ctty_number_for_pidfd (gint pidfd,
1474 GError **error)
1475 {
1476 #ifdef __linux__
1477 guint tty_nr;
1478 gint tty_fd;
1479 gint pid;
1480 struct stat st;
1481 struct statfs stfs;
1482 gchar *tty_name;
1483 gchar *filename;
1484 gchar *contents;
1485 size_t length;
1486 gchar **tokens;
1487 guint num_tokens;
1488 gchar *p;
1489 gchar *endp;
1490
1491 tty_nr = 0;
1492 tty_fd = -1;
1493 pid = 0;
1494 tty_name = NULL;
1495 contents = NULL;
1496 tokens = NULL;
1497
1498 g_return_val_if_fail (pidfd >= 0, 0);
1499
1500 pid = polkit_unix_process_get_pid_from_pidfd (pidfd, error);
1501 if (pid <= 0)
1502 return 0;
1503
1504 filename = g_strdup_printf ("/proc/%d/stat", pid);
1505 if (!filename)
1506 {
1507 g_set_error (error,
1508 POLKIT_ERROR,
1509 POLKIT_ERROR_FAILED,
1510 "Error allocating memory for procfs path");
1511 goto out;
1512 }
1513
1514 if (!g_file_get_contents (filename, &contents, &length, error))
1515 goto out;
1516
1517 /* parent's pid is the token at index 1 after the '(process name)' entry - since only this
1518 * field can contain the ')' character, search backwards for this to avoid malicious
1519 * processes trying to fool us
1520 */
1521 p = strrchr (contents, ')');
1522 if (p == NULL)
1523 {
1524 g_set_error (error,
1525 POLKIT_ERROR,
1526 POLKIT_ERROR_FAILED,
1527 "Error parsing file %s",
1528 filename);
1529 goto out;
1530 }
1531 p += 2; /* skip ') ' */
1532 if (p - contents >= (int) length)
1533 {
1534 g_set_error (error,
1535 POLKIT_ERROR,
1536 POLKIT_ERROR_FAILED,
1537 "Error parsing file %s",
1538 filename);
1539 goto out;
1540 }
1541
1542 tokens = g_strsplit (p, " ", 0);
1543
1544 num_tokens = g_strv_length (tokens);
1545
1546 if (num_tokens < 5)
1547 {
1548 g_set_error (error,
1549 POLKIT_ERROR,
1550 POLKIT_ERROR_FAILED,
1551 "Error parsing file %s",
1552 filename);
1553 goto out;
1554 }
1555
1556 /*
1557 * The string can have negative representation, but it's actually an unsigned int,
1558 * cast it to convert it
1559 */
1560 tty_nr = (guint) strtoll (tokens[4], &endp, 10);
1561 if (endp == tokens[4])
1562 {
1563 g_set_error (error,
1564 POLKIT_ERROR,
1565 POLKIT_ERROR_FAILED,
1566 "Error parsing file %s",
1567 filename);
1568 goto out;
1569 }
1570
1571 if (tty_nr == 0)
1572 {
1573 g_set_error (error,
1574 POLKIT_ERROR,
1575 POLKIT_ERROR_FAILED,
1576 "No TTY associated with process %d",
1577 pid);
1578 goto out;
1579 }
1580
1581 /* Now do some sanity checks to ensure we are really looking at a TTY. */
1582
1583 tty_name = g_strdup_printf ("/dev/pts/%u", minor (tty_nr));
1584
1585 tty_fd = open (tty_name, O_CLOEXEC|O_NOCTTY|O_PATH);
1586 if (tty_fd < 0)
1587 {
1588 g_set_error (error,
1589 POLKIT_ERROR,
1590 POLKIT_ERROR_FAILED,
1591 "Error opening TTY %s for process %d: %s",
1592 tty_name,
1593 pid,
1594 g_strerror (errno));
1595 goto out;
1596 }
1597
1598 if (fstat (tty_fd, &st) < 0)
1599 {
1600 g_set_error (error,
1601 POLKIT_ERROR,
1602 POLKIT_ERROR_FAILED,
1603 "Error getting TTY name for process %d: %s",
1604 pid,
1605 g_strerror (errno));
1606 goto out;
1607 }
1608
1609 if (!S_ISCHR (st.st_mode))
1610 {
1611 g_set_error (error,
1612 POLKIT_ERROR,
1613 POLKIT_ERROR_FAILED,
1614 "TTY name for process %d is not a character device",
1615 pid);
1616 goto out;
1617 }
1618
1619 if (major (tty_nr) != major (st.st_rdev) || minor (tty_nr) != minor (st.st_rdev))
1620 {
1621 g_set_error (error,
1622 POLKIT_ERROR,
1623 POLKIT_ERROR_FAILED,
1624 "TTY device number mismatch for process %d",
1625 pid);
1626 goto out;
1627 }
1628
1629 if (fstatfs (tty_fd, &stfs) < 0)
1630 {
1631 g_set_error (error,
1632 POLKIT_ERROR,
1633 POLKIT_ERROR_FAILED,
1634 "Error getting TTY filesystem information for process %d: %s",
1635 pid,
1636 g_strerror (errno));
1637 goto out;
1638 }
1639
1640 if (stfs.f_type != 0x1cd1) /* 0x1cd1 is the magic number for devpts */
1641 {
1642 g_set_error (error,
1643 POLKIT_ERROR,
1644 POLKIT_ERROR_FAILED,
1645 "TTY filesystem type mismatch for process %d",
1646 pid);
1647 goto out;
1648 }
1649
1650 /*
1651 * The ptmx device is weird, it exists twice, once inside and once outside devpts. To detect the
1652 * latter case, let's fire off an ioctl() that only works on ptmx devices.
1653 */
1654 int v;
1655 if (ioctl (tty_fd, TIOCGPKT, &v) < 0)
1656 {
1657 g_set_error (error,
1658 POLKIT_ERROR,
1659 POLKIT_ERROR_FAILED,
1660 "Error getting TTY packet mode for process %d: %s",
1661 pid,
1662 g_strerror (errno));
1663 goto out;
1664 }
1665
1666 /* Ensure the process is still running */
1667 if (pid != polkit_unix_process_get_pid_from_pidfd (pidfd, error))
1668 {
1669 if (error && *error == NULL)
1670 g_set_error (error,
1671 POLKIT_ERROR,
1672 POLKIT_ERROR_FAILED,
1673 "Process exited while reading TTY name");
1674 goto out;
1675 }
1676
1677 out:
1678 g_strfreev (tokens);
1679 g_free (filename);
1680 g_free (contents);
1681 g_free (tty_name);
1682 if (tty_fd >= 0)
1683 close (tty_fd);
1684
1685 return tty_nr;
1686 #else /* !__linux__ */
1687 return 0;
1688 #endif /* __linux__ */
1689 }
1690
1691 static gint
1692 get_ppidfd_for_pidfd (gint pidfd,
1693 GError **error)
1694 {
1695 gint ppidfd;
1696 gint pid, ppid;
1697 gchar *filename;
1698 gchar *contents;
1699 size_t length;
1700 gchar **tokens;
1701 guint num_tokens;
1702 gchar *p;
1703 gchar *endp;
1704
1705 ppidfd = -1;
1706 pid = ppid = 0;
1707 contents = NULL;
1708
1709 g_return_val_if_fail (pidfd >= 0, -1);
1710
1711 pid = polkit_unix_process_get_pid_from_pidfd (pidfd, error);
1712 if (pid <= 0)
1713 return -1;
1714
1715 filename = g_strdup_printf ("/proc/%d/stat", pid);
1716
1717 if (!g_file_get_contents (filename, &contents, &length, error))
1718 goto out;
1719
1720 /* parent's pid is the token at index 1 after the '(process name)' entry - since only this
1721 * field can contain the ')' character, search backwards for this to avoid malicious
1722 * processes trying to fool us
1723 */
1724 p = strrchr (contents, ')');
1725 if (p == NULL)
1726 {
1727 g_set_error (error,
1728 POLKIT_ERROR,
1729 POLKIT_ERROR_FAILED,
1730 "Error parsing file %s",
1731 filename);
1732 goto out;
1733 }
1734 p += 2; /* skip ') ' */
1735 if (p - contents >= (int) length)
1736 {
1737 g_set_error (error,
1738 POLKIT_ERROR,
1739 POLKIT_ERROR_FAILED,
1740 "Error parsing file %s",
1741 filename);
1742 goto out;
1743 }
1744
1745 tokens = g_strsplit (p, " ", 0);
1746
1747 num_tokens = g_strv_length (tokens);
1748
1749 if (num_tokens < 2)
1750 {
1751 g_set_error (error,
1752 POLKIT_ERROR,
1753 POLKIT_ERROR_FAILED,
1754 "Error parsing file %s",
1755 filename);
1756 goto out;
1757 }
1758
1759 ppid = strtoull (tokens[1], &endp, 10);
1760 if (endp == tokens[1])
1761 {
1762 g_set_error (error,
1763 POLKIT_ERROR,
1764 POLKIT_ERROR_FAILED,
1765 "Error parsing file %s",
1766 filename);
1767 goto out;
1768 }
1769
1770 g_strfreev (tokens);
1771
1772 #ifdef HAVE_PIDFD_OPEN
1773 /*
1774 * Ensure the actual parent hasn't exited, in which case the process would
1775 * be reparented to PID 1
1776 */
1777 if (ppid > 1)
1778 {
1779 ppidfd = (int) syscall (SYS_pidfd_open, ppid, 0);
1780
1781 /* Ensure the processes are still running */
1782 if (ppidfd >= 0 &&
1783 (pid != polkit_unix_process_get_pid_from_pidfd (pidfd, error) ||
1784 ppid != polkit_unix_process_get_pid_from_pidfd (ppidfd, error)))
1785 {
1786 close (ppidfd);
1787 ppidfd = -1;
1788 }
1789 }
1790 #endif /* HAVE_PIDFD_OPEN */
1791
1792 out:
1793 g_free (filename);
1794 g_free (contents);
1795
1796 return ppidfd;
1797 }
1798
1799 /*
1800 * Private: Return the "current" UID. Note that this is inherently racy,
1801 * and the value may already be obsolete by the time this function returns;
1802 * this function only guarantees that the UID was valid at some point during
1803 * its execution.
1804 */
1805 gint
1806 polkit_unix_process_get_racy_uid__ (PolkitUnixProcess *process,
1807 GError **error)
1808 {
1809 gint result, pid;
1810 gchar *contents;
1811 gchar **lines;
1812 guint64 start_time;
1813 #if defined(HAVE_FREEBSD) || defined(HAVE_OPENBSD)
1814 struct kinfo_proc p;
1815 #elif defined(HAVE_NETBSD)
1816 struct kinfo_proc2 p;
1817 #else
1818 gchar filename[64];
1819 guint n;
1820 GError *local_error;
1821 #endif
1822
1823 g_return_val_if_fail (POLKIT_IS_UNIX_PROCESS (process), 0);
1824 g_return_val_if_fail (error == NULL || *error == NULL, 0);
1825
1826 result = 0;
1827 lines = NULL;
1828 contents = NULL;
1829
1830 pid = polkit_unix_process_get_pid(process);
1831 if (pid <= 0)
1832 {
1833 g_set_error (error,
1834 POLKIT_ERROR,
1835 POLKIT_ERROR_FAILED,
1836 "Process not found");
1837 goto out;
1838 }
1839
1840 #if defined(HAVE_FREEBSD) || defined(HAVE_NETBSD) || defined(HAVE_OPENBSD)
1841 if (get_kinfo_proc (pid, &p) == 0)
1842 {
1843 g_set_error (error,
1844 POLKIT_ERROR,
1845 POLKIT_ERROR_FAILED,
1846 "get_kinfo_proc() failed for pid %d: %s",
1847 pid,
1848 g_strerror (errno));
1849 goto out;
1850 }
1851
1852 #if defined(HAVE_FREEBSD)
1853 result = p.ki_uid;
1854 start_time = (guint64) p.ki_start.tv_sec;
1855 #else
1856 result = p.p_uid;
1857 start_time = (guint64) p.p_ustart_sec;
1858 #endif
1859 #else
1860
1861 /* see 'man proc' for layout of the status file
1862 *
1863 * Uid, Gid: Real, effective, saved set, and file system UIDs (GIDs).
1864 */
1865 g_snprintf (filename, sizeof filename, "/proc/%d/status", pid);
1866 if (!g_file_get_contents (filename,
1867 &contents,
1868 NULL,
1869 error))
1870 {
1871 goto out;
1872 }
1873 lines = g_strsplit (contents, "\n", -1);
1874 for (n = 0; lines != NULL && lines[n] != NULL; n++)
1875 {
1876 gint real_uid, effective_uid;
1877 if (!g_str_has_prefix (lines[n], "Uid:"))
1878 continue;
1879 if (sscanf (lines[n] + 4, "%d %d", &real_uid, &effective_uid) != 2)
1880 {
1881 g_set_error (error,
1882 POLKIT_ERROR,
1883 POLKIT_ERROR_FAILED,
1884 "Unexpected line `%s' in file %s",
1885 lines[n],
1886 filename);
1887 goto out;
1888 }
1889 else
1890 {
1891 result = real_uid;
1892 goto found;
1893 }
1894 }
1895 g_set_error (error,
1896 POLKIT_ERROR,
1897 POLKIT_ERROR_FAILED,
1898 "Didn't find any line starting with `Uid:' in file %s",
1899 filename);
1900 goto out;
1901
1902 found:
1903 /* The UID and start time are, sadly, not available in a single file. So,
1904 * read the UID first, and then the start time; if the start time is the same
1905 * before and after reading the UID, it couldn't have changed.
1906 */
1907 local_error = NULL;
1908 start_time = get_start_time_for_pid (pid, &local_error);
1909 if (local_error != NULL)
1910 {
1911 g_propagate_error (error, local_error);
1912 goto out;
1913 }
1914 #endif
1915
1916 if (process->start_time != start_time)
1917 {
1918 g_set_error (error, POLKIT_ERROR, POLKIT_ERROR_FAILED,
1919 "process with PID %d has been replaced", pid);
1920 goto out;
1921 }
1922
1923 out:
1924 g_strfreev (lines);
1925 g_free (contents);
1926 return result;
1927 }
1928
1929 /* deprecated public method */
1930 /**
1931 * polkit_unix_process_get_owner:
1932 * @process: A #PolkitUnixProcess.
1933 * @error: Return location for error.
1934 *
1935 * (deprecated)
1936 */
1937 gint
1938 polkit_unix_process_get_owner (PolkitUnixProcess *process,
1939 GError **error)
1940 {
1941 return polkit_unix_process_get_racy_uid__ (process, error);
1942 }