Difference between revisions of "Development/Tutorials/PolicyKit/Helper HowTo"

Jump to: navigation, search
Line 42: Line 42:
 
* A DBus policy file
 
* A DBus policy file
 
* A file for DBus Activation
 
* A file for DBus Activation
* The main class
+
* The main class in the helper
  
 
We already know how create Policy files, let's get deeper on the other points and let's try to understand what we need to do, how and why.
 
We already know how create Policy files, let's get deeper on the other points and let's try to understand what we need to do, how and why.
Line 62: Line 62:
  
 
And that's enough. Remember to specify in the interface any needed signal/slot to communicate with the main application or library.
 
And that's enough. Remember to specify in the interface any needed signal/slot to communicate with the main application or library.
 +
 +
Let's save this file as org.kde.foohelper.xml
  
 
=== The DBus policy file ===
 
=== The DBus policy file ===
Line 88: Line 90:
  
 
What does this file implies? It tells DBus that only root can register the name org.kde.foohelper on the System Bus (so that we avoid misusage), and anyone is allowed to call or receive signals from it. Don't worry about security: this will come later.
 
What does this file implies? It tells DBus that only root can register the name org.kde.foohelper on the System Bus (so that we avoid misusage), and anyone is allowed to call or receive signals from it. Don't worry about security: this will come later.
 +
 +
Let's save this file as org.kde.foohelper.conf
  
 
=== DBus Activation ===
 
=== DBus Activation ===
Line 100: Line 104:
  
 
You might already have understood what this files tells DBus to do: whenever someone calls a method on org.kde.foohelper, if the interface is not present on the bus, DBus takes care of starting foohelper, that will provide the interface, and then call the method. The magic of starting it as root happens by appending "User=root". There is nothing else you have to do: now your helper is ready to be auto-activated as the root user.
 
You might already have understood what this files tells DBus to do: whenever someone calls a method on org.kde.foohelper, if the interface is not present on the bus, DBus takes care of starting foohelper, that will provide the interface, and then call the method. The magic of starting it as root happens by appending "User=root". There is nothing else you have to do: now your helper is ready to be auto-activated as the root user.
 +
 +
@LIBEXEC_INSTALL_DIR@ will be resolved by cmake. So let's save this file as org.kde.foohelper.service.in, as it will be configured at build time.
  
 
So now we have the infrastructure to run an helper as root, but anyone can do it, and that's definitely not what we want. But that's when PolicyKit comes into play.
 
So now we have the infrastructure to run an helper as root, but anyone can do it, and that's definitely not what we want. But that's when PolicyKit comes into play.
 +
 +
=== The helper's main class ===
 +
Our helper will consist of a single main class. Let's see how to do it:
 +
 +
<code cpp>
 +
class FooHelper : public QObject, protected QDBusContext
 +
{
 +
    Q_OBJECT
 +
    Q_CLASSINFO("D-Bus Interface", "org.kde.foohelper")
 +
public:
 +
    FooHelper(QObject *parent = 0);
 +
    ~FooHelper();
 +
 +
public slots:
 +
    void action2();
 +
 +
signals:
 +
    void action2Completed();
 +
</code>
 +
 +
The inheritance from QObject can be changed as you like, but '''inheriting from QDBusContext is compulsory.''' You'll understand why very soon. Let's define our constructor:
 +
 +
<code cpp>
 +
(void) new FooHelperAdaptor(this);
 +
if (!QDBusConnection::systemBus().registerService("org.kde.foohelper")) {
 +
    qDebug() << "another helper is already running";
 +
    QCoreApplication::instance()->quit();
 +
}
 +
 +
if (!QDBusConnection::systemBus().registerObject("/", this)) {
 +
    qDebug() << "unable to register service interface to dbus";
 +
    QCoreApplication::instance()->quit();
 +
}
 +
</code>
 +
 +
We simply connect to the '''system bus (be careful, not the session one!)''', and if something fail we quit, because it's quite likely that we're going over something weird. Now that we have done that and our application is inside it's main loop, it's time to see what action2() should do:
 +
 +
<code cpp>
 +
void FooHelper::action2()
 +
{
 +
    qDebug() << "Starting DB Update";
 +
 +
    PolKitResult result;
 +
    result = PolkitQt::Auth::isCallerAuthorized("org.kde.foo.action2",
 +
                                      message().service(),
 +
                                      true);
 +
    if (result == POLKIT_RESULT_YES) {
 +
        qDebug() << message().service() << QString(" authorized");
 +
    } else {
 +
        qDebug() << QString("Not authorized");
 +
        QCoreApplication::instance()->quit();
 +
        return;
 +
    }
 +
 +
    // If we got here, we have been authorized, so let's go:
 +
    eraseHardDrive();
 +
    killUser();
 +
    detonatePC();
 +
    runAsFastAsYouCan();
 +
 +
    // We have done our job, so let's notify everyone:
 +
    emit action2Completed();
 +
}
 +
</code>
 +
 +
Let's see this in detail. The '''FIRST THING you always have to do is calling the authorization check, otherwise everything will be useless'''. As you can see, we are using message().service() from QDBusContext, hence the compulsory inheritance. What we are doing boils down to:
 +
 +
* Check through Polkit-qt if the caller was authorized. Using the DBus name also grants us that the action can be called through DBus only.
 +
* If the result is not POLKIT_RESULT_YES, we simply quit, as we are not authorized to do the action. You can obviously provide means of authentication here, but we are supposing (in this tutorial) that you are doing this from the main application
 +
 +
So the security happens here: if PolicyKit says no, we simply quit out. This way, only authorized application will be able to get through the real method.

Revision as of 19:01, 11 March 2009


Contents

Development/Tutorials/PolicyKit/Introduction


Using the caller-helper model to perform actions as root
Tutorial Series   PolicyKit Tutorial
Previous   Development/Tutorials/PolicyKit/Introduction
What's Next   None

reading=None

Further Reading   n/a

Before you start

Applications running under root privileges has always been a major problem in Linux, and PolicyKit was created exactly to make the whole process easier and more secure. Though, running applications as root, even if small and controlled, can be still a major issue. So there are a few things you should take in account that will help you minimize possible issues:

  • Include in the helper just the strictly needed code. The fact itself that is a helper delegated to run just small parts of code implies that only the few lines of code you need to run as root should go in
  • Link against and use the minor number of libraries possible. The helper itself requires only QtCore and QtDBus. In particular, try not to use KDELibs as possible, as they were not designed to be used as root.
  • DO NOT USE SETUID IN HELPER. We'll see in this tutorial how to get root privileges without messing with the setuid bit.

If you are aware of this, and you're also sure that your application actually needs root privileges, you can go on reading.

What we need to do

What is cool about PolicyKit and this approach is that we need to write a minimum portion of code, don't need hacks or executon bits, and we actually get root privileges for a minimum portion of code. Suppose we still have our foo application we saw in the precedent Tutorial. From our .policy file, we know action2 actually does something that requires authentication as root. In fact, the following lines of code in action2 definitely require root privileges:

eraseHardDrive(); killUser(); detonatePC(); runAsFastAsYouCan();

But foo is a huge program that runs as standard user apart from those lines. So the option is to make it run as root as a whole, or split those 4 lines in a different program running as root. That is the approach that we will take in this tutorial.

Creating the Helper

Our helper will be a standard QCoreApplication. We need to create the following stuff:

  • A .policy file defining the various actions, that we should have already done
  • A DBus interface for our Helper
  • A DBus policy file
  • A file for DBus Activation
  • The main class in the helper

We already know how create Policy files, let's get deeper on the other points and let's try to understand what we need to do, how and why.

The DBus interface

We suppose you already know how to create DBus interfaces from XML files. In our interface we need to specify the means of communication between the helper and the main application. Consider that the only way we have to talk to our helper is DBus, so we need to rely on signals and slots streamed through the Bus. In our foo application, we have a signal that tells us when the helper has completed the action. So:

<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node>

  <interface name="org.kde.foohelper">
      <method name="action2" >
      </method>
      <signal name="action2completed">
      </signal>
  </interface>

</node>

And that's enough. Remember to specify in the interface any needed signal/slot to communicate with the main application or library.

Let's save this file as org.kde.foohelper.xml

The DBus policy file

Our helper will register itself on the system bus, as the session bus is reserved for the current user. DBus by default does not allow to register names on the System Bus, so we need a policy file for it. That's how it looks:

<!DOCTYPE busconfig PUBLIC

"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">

<busconfig>

 <policy user="root">
   <allow own="org.kde.foohelper"/>
 </policy>
 <policy context="default">
   <allow send_interface="org.kde.foohelper"/>
   <allow receive_sender="org.kde.foohelper"/>
   <allow receive_interface="org.kde.foohelper"/>
 </policy>

</busconfig>

What does this file implies? It tells DBus that only root can register the name org.kde.foohelper on the System Bus (so that we avoid misusage), and anyone is allowed to call or receive signals from it. Don't worry about security: this will come later.

Let's save this file as org.kde.foohelper.conf

DBus Activation

This is where the fun starts. DBus gives us an impressive and powerful functionality: DBus activation. By defining a simple .service file, DBus will take care of activating the interface (and so the program) for us. Let's see this in detail:

[D-BUS Service] Name=org.kde.foohelper Exec=@LIBEXEC_INSTALL_DIR@/foohelper User=root

You might already have understood what this files tells DBus to do: whenever someone calls a method on org.kde.foohelper, if the interface is not present on the bus, DBus takes care of starting foohelper, that will provide the interface, and then call the method. The magic of starting it as root happens by appending "User=root". There is nothing else you have to do: now your helper is ready to be auto-activated as the root user.

@LIBEXEC_INSTALL_DIR@ will be resolved by cmake. So let's save this file as org.kde.foohelper.service.in, as it will be configured at build time.

So now we have the infrastructure to run an helper as root, but anyone can do it, and that's definitely not what we want. But that's when PolicyKit comes into play.

The helper's main class

Our helper will consist of a single main class. Let's see how to do it:

class FooHelper : public QObject, protected QDBusContext {

   Q_OBJECT
   Q_CLASSINFO("D-Bus Interface", "org.kde.foohelper")

public:

   FooHelper(QObject *parent = 0);
   ~FooHelper();

public slots:

   void action2();

signals:

   void action2Completed();

The inheritance from QObject can be changed as you like, but inheriting from QDBusContext is compulsory. You'll understand why very soon. Let's define our constructor:

(void) new FooHelperAdaptor(this); if (!QDBusConnection::systemBus().registerService("org.kde.foohelper")) {

   qDebug() << "another helper is already running";
   QCoreApplication::instance()->quit();

}

if (!QDBusConnection::systemBus().registerObject("/", this)) {

   qDebug() << "unable to register service interface to dbus";
   QCoreApplication::instance()->quit();

}

We simply connect to the system bus (be careful, not the session one!), and if something fail we quit, because it's quite likely that we're going over something weird. Now that we have done that and our application is inside it's main loop, it's time to see what action2() should do:

void FooHelper::action2() {

   qDebug() << "Starting DB Update";
   PolKitResult result;
   result = PolkitQt::Auth::isCallerAuthorized("org.kde.foo.action2",
                                     message().service(),
                                     true);
   if (result == POLKIT_RESULT_YES) {
       qDebug() << message().service() << QString(" authorized");
   } else {
       qDebug() << QString("Not authorized");
       QCoreApplication::instance()->quit();
       return;
   }
   // If we got here, we have been authorized, so let's go:
   eraseHardDrive();
   killUser();
   detonatePC();
   runAsFastAsYouCan();
   // We have done our job, so let's notify everyone:
   emit action2Completed();

}

Let's see this in detail. The FIRST THING you always have to do is calling the authorization check, otherwise everything will be useless. As you can see, we are using message().service() from QDBusContext, hence the compulsory inheritance. What we are doing boils down to:

  • Check through Polkit-qt if the caller was authorized. Using the DBus name also grants us that the action can be called through DBus only.
  • If the result is not POLKIT_RESULT_YES, we simply quit, as we are not authorized to do the action. You can obviously provide means of authentication here, but we are supposing (in this tutorial) that you are doing this from the main application

So the security happens here: if PolicyKit says no, we simply quit out. This way, only authorized application will be able to get through the real method.


KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V.Legal