How to write file using PolicyKit to get privilege

105 views Asked by At

There is a PyQt5 program that has a method for writing some text to a file. Before writing (or reading) I have to check if I have permissions for this action. If I don't have such permissions, then I have to somehow contact Policykit (using dbus?) to increase the permissions and then execute the method. After a week of surfing the internet, I still haven't found a reliable instruction to perform the described algorithm. P.S. I cannot use the python library polkit due to repository restrictions.

It's all jumbled up in my head by now, but here's what I've tried so far: I've added .policy, .conf and .service files to the right directories, but I guess I don't fully understand their purpose. Roughly I understand that my program with the help of dbus should access policykit and this will give the necessary permissions to execute the method

1

There are 1 answers

4
user1686 On

PolicyKit on its own does not have the ability to increase privileges that your process has.

Its primary use is access control when you're contacting another service (one that already has the necessary privileges) and asking it to do something on your behalf. For example, PolicyKit does not directly grant KDE privileges to mount a USB stick – rather, it grants KDE privileges to ask UDisks2 to mount a USB stick, and the UDisks2 service is already sufficiently privileged to do that.

Also, you don't have to contact polkitd – it's the privileged service (e.g. UDisks2) that would do so before performing the action.

If there is no existing privileged service that would do what you need, then PolicyKit alone will not help you much.

  • You could, of course, write your own D-Bus service which does that and install the D-Bus .service config to have it run as a system service with root privileges. (Try to keep the operations as limited and fine-grained as is reasonable; e.g. "enable global mode foo" – not "write arbitrary data to arbitrary file".)

  • Failing that, one common method is to spawn pkexec to perform operations, which is… really just su with a nicer password prompt. Note that some distributions have recently removed pkexec.

  • If your app is allowed to use either GNOME's GLib or KDE's KIO libraries, then both of those already have PolicyKit integration built-in for privileged file updates – the app could open admin:///etc/foo and GLib or KIO would elevate as needed.