Starting systemd services using dbus without root

1.6k Views Asked by At

I've made this polkit rule:

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units") {
       return "yes";
    }
});

It works with the command below, I don't need to be root to start/stop.

busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager StopUnit ss "cups.service" "replace"

However, I've written a C program to start/stop the service and it doesn't work, I get this error no matter what I do (unless I run as root):

Name Error (Connection ":1.689" is not allowed to own the service "org.freedesktop.systemd1" due to security policies in the configuration file)

Here's the source code for that program, I removed the error checking for clarity.

#include <stdlib.h>
#include <stdio.h>

#include <dbus/dbus.h>

int main(int argc, char *argv[])
{

const char* params = "cups.service fail";

const char* destination = "org.freedesktop.systemd1";
const char* path = "/org/freedesktop/systemd1";
const char* interface = "org.freedesktop.systemd1.Manager"; 
const char* method = "StopUnit";

DBusMessage* msg;
DBusMessage *response;
DBusMessageIter args;
DBusPendingCall* pending;

DBusError err;
DBusConnection* conn;
int ret;

// connect to the bus
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);

// The error happens here
ret = dbus_bus_request_name(conn,
                            destination,
                            DBUS_NAME_FLAG_REPLACE_EXISTING,
                            &err);

msg = dbus_message_new_method_call(destination, // target for the method call
                                   path, // object to call on
                                   interface, // interface to call on
                                   method); // method name

dbus_message_iter_init_append(msg, &args);

dbus_connection_send_with_reply(conn, msg, &pending, -1);

dbus_connection_flush(conn);
dbus_message_unref(msg);

This application seems to do something pretty similar.

0

There are 0 best solutions below