POLKIT(8)

๐Ÿ’– NAME ๐Ÿ’–

polkit โ€” the Authorization Manager, aka your system's designated vibes-checker for "should this rando be allowed to do The Thing" ๐ŸŽ€

โœจ OVERVIEW โœจ

okay so picture this, bestie: polkit ships an authorization API, and it's literally made for privileged programs โ€” those are called โ€œMECHANISMSโ€ โ€” that offer services to unprivileged programs, aka โ€œSUBJECTSโ€, usually over some kind of inter-process communication thingy. In this whole situation, the mechanism treats the subject as untrusted (fair, honestly ๐Ÿ™ˆ). So for every single request that comes in from a subject, the mechanism has to figure out: is this authorized, or do I refuse to serve them?

And here's the slay part ๐Ÿซถ โ€” using the polkit APIs, a mechanism can just offload that whole decision to a trusted party: the polkit authority.

The polkit authority is implemented as a system daemon, polkitd(8), and the way it lowkey has barely any privilege of its own is iconic โ€” it runs as the polkitd system user. Mechanisms, subjects and authentication agents all talk to the authority over the system message bus. ๐Ÿ’…

In addition to acting as an authority, polkit also lets users get temporary authorization by authenticating as either an administrative user or the owner of the session the client belongs to. This is giving very much "are you actually the operator of this system, or are you actually an administrative user" energy โ€” which is super useful when a mechanism needs to verify exactly that. โœจ


๐Ÿ›  SYSTEM ARCHITECTURE ๐Ÿ› 

The system architecture of polkit is comprised of the Authority (implemented as a service on the system message bus) and an Authentication Agent per user session (provided and started by the user's graphical environment). Actions are defined by applications. Vendors, sites and system administrators can control authorization policy through Authorization Rules. ๐Ÿ‘‘

Here's the diagram, and ngl it ate:

           [IMAGE][1]

                +-------------------+
                |   Authentication  |
                |       Agent       |
                +-------------------+
                | libpolkit-agent-1 |
                +-------------------+
                       ^                                  +---------+
                       |                                  | Subject |
                       +--------------+                   +---------+
                                      |                        ^
                                      |                        |
               User Session           |                        |
               =======================|========================|=============
               System Context         |                        |
                                      |                        |
                                      |                    +---+
                                      V                    |
                                    /------------\         |
                                    | System Bus |         |
                                    \------------/         |
                                      ^        ^           V
                                      |        |      +---------------------+
                       +--------------+        |      |      Mechanism      |
                       |                       |      +---------------------+
                       V                       +----> | libpolkit-gobject-1 |
               +------------------+                   +---------------------+
               |    polkitd(8)    |
               +------------------+
               | org.freedesktop. |
               |    PolicyKit1    |<---------+
               +------------------+          |
                         ^                   |
                         |            +--------------------------------------------+
                         |            | /etc/polkit-1/actions/*.policy             |
                         |            | /run/polkit-1/actions/*.policy             |
                         |            | /usr/local/share/polkit-1/actions/*.policy |
                         |            | /usr/share/polkit-1/actions/*.policy       |
                         |            +--------------------------------------------+
                         |
                  +--------------------------------------------+
                  | /etc/polkit-1/rules.d/*.rules              |
                  | /run/polkit-1/rules.d/*.rules              |
                  | /usr/local/share/polkit-1/rules.d/*.rules  |
                  | /usr/share/polkit-1/rules.d/*.rules        |
                  +--------------------------------------------+

For convenience โ€” and this is the part that's giving main character energy โ€” the libpolkit-gobject-1 library wraps the polkit D-Bus API, and it's usable from any C/C++ program plus higher-level languages that support GObjectIntrospection, like JavaScript and Python. ๐Ÿ A mechanism can also use the D-Bus API directly, or the pkcheck(1) command, to check authorizations. Meanwhile the libpolkit-agent-1 library hands you an abstraction of the native authentication system โ€” pam(8), for example โ€” along with facilities for registration and communication with the polkit D-Bus service. ๐Ÿฆ‹

See the developer documentation for more info about writing polkit applications. (yep, that's the third link in the original, bestie โ€” go read it, iykyk)

๐Ÿงš AUTHENTICATION AGENTS ๐Ÿงš

An authentication agent exists to make the user of a session prove that the user of the session really is the user (by authenticating as the user) or really is an administrative user (by authenticating as an administrator). ๐Ÿ’…

And because everyone wants things to match, authentication agents are meant to be provided by the user session that the user actually uses โ€” that way they integrate well with the rest of the session, look and feel included. โœจ For example, an authentication agent may look like this:

           [IMAGE][4]

               +----------------------------------------------------------+
               |                                                          |
               |  [Icon]  Authentication required                         |
               |                                                          |
               |          Authentication is required to format INTEL      |
               |          SSDSA2MH080G1GC (/dev/sda)                      |
               |                                                          |
               |          Administrator                                   |
               |                                                          |
               |          Password: [__________________________________]  |
               |                                                          |
               | [Cancel]                                  [Authenticate] |
               +----------------------------------------------------------+

Now, if the system is configured without a root account, it may prompt for a specific user designated as the administrative user instead โ€” same vibe, different name on the card:

           [IMAGE][5]

               +----------------------------------------------------------+
               |                                                          |
               |  [Icon]  Authentication required                         |
               |                                                          |
               |          Authentication is required to format INTEL      |
               |          SSDSA2MH080G1GC (/dev/sda)                      |
               |                                                          |
               |          [Icon] David Zeuthen                            |
               |                                                          |
               |          Password: [__________________________________]  |
               |                                                          |
               | [Cancel]                                  [Authenticate] |
               +----------------------------------------------------------+

Here's the thing though ๐Ÿซถ โ€” applications that don't run under a desktop environment (say, launched from an ssh(1) login) may not have an authentication agent associated with them at all. For those, an app can use the PolkitAgentTextListener type or the pkttyagent(1) helper, so the user can still authenticate using a textual interface. no cap, it works. โŒจ๏ธ

And the polkit-agent-helper-1 binary is the one doing the privileged credential verification on behalf of the agent. ๐Ÿ‘‘ When it's run as a systemd socket-activated service it operates in a restricted sandbox โ€” so PAM module creators who need additional access should go consult the polkit-agent-helper(8) man page for guidance on shipping drop-in overrides. that's the whole tea. ๐Ÿ“


okay that's the architecture and agent situation all wrapped up โ€” plenty more polkit coming your way, so don't go anywhere ๐Ÿ’œ

๐ŸŽ€ DECLARING ACTIONS ๐ŸŽ€

okay so listen โ€” for a mechanism to actually use polkit, it has to declare a set of actions first. no actions, no vibes, no authorization. an action is basically "a thing clients can ask the mechanism to do," and you define them in XML files that the mechanism installs into the /usr/share/polkit-1/actions directory. that's the spot. ๐Ÿ’…

polkit actions are namespaced, and the name can only contain the characters "[A-Z][a-z][0-9].-" โ€” so like, ASCII letters, digits, period and hyphen. that's it, bestie, no freestyle. each XML file can hold more than one action, but every action in a file needs to be in the same namespace, and the file itself needs to be named after that namespace and have the .policy extension. ๐Ÿ‘‘

your XML file must have this doctype declaration, no exceptions:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD polkit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/software/polkit/policyconfig-1.dtd">

the policyconfig element has to be present exactly once. and the elements you can put inside policyconfig include:

  • vendor โ€” the name of the project or vendor supplying the actions in the XML document. optional.
  • vendor_url โ€” a URL to the project or vendor supplying the actions in the XML document. optional.
  • icon_name โ€” an icon representing the project or vendor supplying the actions in the XML document. the icon name has to adhere to the Freedesktop.org Icon Naming Specification[6]. optional.
  • action โ€” declares an action. the action name is specified using the id attribute and can only contain the characters "[A-Z][a-z][0-9].- " โ€” again, ASCII, digits, period and hyphen.

and the elements you can put inside action include:

  • description โ€” a human readable description of the action, e.g. "Install unsigned software".
  • message โ€” a human readable message displayed to the user when asking for credentials when authentication is needed, e.g. "Installing unsigned software requires authentication".
  • defaults โ€” this element is used to specify implicit authorizations for clients. the elements you can put inside defaults include:
    • allow_any โ€” implicit authorizations that apply to any client. optional.
    • allow_inactive โ€” implicit authorizations that apply to clients in inactive sessions on local consoles. optional.
    • allow_active โ€” implicit authorizations that apply to clients in active sessions on local consoles. optional.

each of the allow_any, allow_inactive and allow_active elements can contain the following values:

  • no โ€” not authorized.
  • yes โ€” authorized.
  • auth_self โ€” authentication by the owner of the session that the client originates from is required. โš ๏ธ note that this is not restrictive enough for most uses on multi-user systems; auth_admin* is generally recommended.
  • auth_admin โ€” authentication by an administrative user is required.
  • auth_self_keep โ€” like auth_self but the authorization is kept for a brief period (e.g. five minutes). the warning about auth_self above applies likewise.
  • auth_admin_keep โ€” like auth_admin but the authorization is kept for a brief period (e.g. five minutes).
  • annotate โ€” used for annotating an action with a key/value pair. the key is specified using the key attribute and the value is specified using the value attribute. this element may appear zero or more times. see below for known annotations.
  • vendor โ€” used for overriding the vendor on a per-action basis. optional.
  • vendor_url โ€” used for overriding the vendor URL on a per-action basis. optional.
  • icon_name โ€” used for overriding the icon name on a per-action basis. optional.

for localization, description and message elements may occur multiple times with different xml:lang attributes. ๐ŸŒโœจ

and to actually list the installed polkit actions? that's pkaction(1), bestie. go look at them.

๐ŸŒธ Known annotations ๐ŸŒธ

the org.freedesktop.policykit.exec.path annotation is used by the pkexec program shipped with polkit โ€” see the pkexec(1) man page for the deets.

the org.freedesktop.policykit.imply annotation (its value is a string containing a space-separated list of action identifiers) can be used to define meta actions. the way it works is that if a subject is authorized for an action with this annotation, then it's also authorized for any action specified by the annotation. a typical use of this one is when you're defining a UI shell with a single lock button that should unlock multiple actions from distinct mechanisms. one button, many vibes. ๐Ÿ”ฅ

the org.freedesktop.policykit.owner annotation can be used to define a set of users who can query whether a client is authorized to perform this action. if this annotation isn't specified, then only root can query whether a client running as a different user is authorized for an action. the value of this annotation is a string containing a space-separated list of PolkitIdentity entries, for example "unix-user:42 unix-user:colord". a typical use of this annotation is for a daemon process that runs as a system user rather than root. ๐Ÿซถ


๐Ÿฆ‹ AUTHORIZATION RULES ๐Ÿฆ‹

polkitd reads .rules files from these directories, in this exact order:

  • /etc/polkit-1/rules.d
  • /run/polkit-1/rules.d
  • /usr/local/share/polkit-1/rules.d
  • /usr/share/polkit-1/rules.d

these directories are processed in lexical order based on the basename of each file. if there's a tie, files in directories earlier in the list get processed first. so like, for the following four files, the order is:

  • /etc/polkit-1/rules.d/10-auth.rules
  • /run/polkit-1/rules.d/10-auth.rules
  • /usr/local/share/polkit-1/rules.d/10-auth.rules
  • /usr/share/polkit-1/rules.d/10-auth.rules

all of these directories are monitored, so if a rules file is changed, added, or removed, existing rules are purged and all the files are read and processed again. self-healing queen behavior, honestly. ๐Ÿ’…

rules files are written in the JavaScript[7] programming language and interface with polkitd through the global polkit object (of type Polkit).

โš ๏ธ authorization rules must conform to ECMA-262 edition 5[8], because that's the only version supported by the current Javascript interpreter used in polkit. no fancy new syntax, bestie. the engine said no.

๐Ÿ‘‘ The Polkit type ๐Ÿ‘‘

the following methods are available on the polkit object:

void addRule(polkit.Result function(action, subject) {...});

void addAdminRule(string[] function(action, subject) {...});

void log(string message);

string spawn(string[] argv);

the addRule() method is used for adding a function that may be called whenever an authorization check for action and subject is performed. functions are called in the order they've been added until one of them returns a value. so if you want an authorization rule processed before other rules, put it in a file in /etc/polkit-1/rules.d with a name that sorts before the other rules files โ€” for example 00-early-checks.rules. each function should return a value from polkit.Result:

polkit.Result = {
    NO              : "no",
    YES             : "yes",
    AUTH_SELF       : "auth_self",
    AUTH_SELF_KEEP  : "auth_self_keep",
    AUTH_ADMIN      : "auth_admin",
    AUTH_ADMIN_KEEP : "auth_admin_keep",
    NOT_HANDLED     : null
};

these correspond to the values that can be used as defaults. if the function returns polkit.Result.NOT_HANDLED, null, undefined, or just doesn't return a value at all, the next user function gets tried. keep the chain moving. ๐Ÿ”ฅ

๐Ÿ˜ญ okay this part is important โ€” keep in mind that if polkit.Result.AUTH_SELF_KEEP or polkit.Result.AUTH_ADMIN_KEEP is returned, authorization checks for the same action identifier and subject will succeed (that is, return polkit.Result.YES) for the next brief period (e.g. five minutes) even if the variables passed along with the check are different. so if the result of an authorization rule depends on such variables, it should not use the "*_KEEP" constants. (and if similar functionality is needed, the authorization rule can easily implement temporary authorizations using the Date[9] type for timestamps.)

the addAdminRule() method is used for adding a function that may be called whenever administrator authentication is required. the function is used to specify what identities may be used for administrator authentication for the authorization check identified by action and subject. functions added are called in the order they've been added until one of the functions returns a value. each function should return an array of strings where each string is of the form "unix-group:<group>", "unix-netgroup:<netgroup>" or "unix-user:<user>". if the function returns null, undefined, or doesn't return a value at all, the next function is tried.

๐Ÿ’€ and here's the thing โ€” there is no guarantee that a function registered with addRule() or addAdminRule() is ever called. for example, an early rules file could register a function that always returns a value, hence ensuring that functions added later are never called. brutal but true.

if user-provided code takes a long time to execute, no exception will be thrown โ€” the script will be killed right away (the current limit is 15 seconds). this is used to catch runaway scripts. bye felicia. โœ‚๏ธ

the spawn() method spawns an external helper identified by the argument vector argv and waits for it to terminate. if an error occurs or the helper doesn't exit normally with exit code 0, an exception is thrown. if the helper doesn't exit within 10 seconds, it's killed. otherwise, the program's standard output is returned as a string. the spawn() method should be used sparingly, because helpers may take a very long or indeterminate amount of time to complete and no other authorization check can be handled while the helper is running. also note that the spawned programs will run as the unprivileged polkitd system user. ๐Ÿซถ

the log() method writes the given message to the system logger, prefixed with the JavaScript filename and line number. log entries are emitted using the LOG_AUTHPRIV flag, meaning the log entries usually end up in the file /var/log/secure. the log() method is usually only used when debugging rules. the Action and Subject types have suitable toString() methods defined for easy logging โ€” for example:

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.policykit.exec") {
        polkit.log("action=" + action);
        polkit.log("subject=" + subject);
    }
});

will produce the following when the user runs pkexec -u bateman bash -i from a shell:

May 24 14:28:50 thinkpad polkitd[32217]: /etc/polkit-1/rules.d/10-test.rules:3: action=[Action id='org.freedesktop.policykit.exec' command_line='/usr/bin/bash -i' program='/usr/bin/bash' user='bateman' user.gecos='Patrick Bateman' user.display='Patrick Bateman (bateman)']
May 24 14:28:50 thinkpad polkitd[32217]: /etc/polkit-1/rules.d/10-test.rules:4: subject=[Subject pid=1352 user='davidz' groups=davidz,wheel, seat='seat0' session='1' local=true active=true]

๐ŸŽ€ The Action type ๐ŸŽ€

Okay so the action parameter your user functions get handed is literally an object stuffed with deets about the action being checked. Type is Action, and it's giving exactly one attribute:

  • string id โ€” the action identifier, like org.freedesktop.policykit.exec. That's the whole vibe of this field, bestie.

And here are the methods you can call on the Action type:

  • string lookup(string key);

The lookup() method is your little key-fetcher โ€” it grabs the polkit variables that the mechanism passed in. Real talk: the pkexec(1) mechanism sets a variable called program, and you can scoop it up in JavaScript with action.lookup("program"). If there's genuinely no value for the key you asked for, you get undefined back. No drama, just undefined. ๐Ÿ’…

Heads up ๐Ÿซถ: go read the documentation for each individual mechanism to find out which variables are actually available for each action โ€” don't guess!

๐Ÿฆ‹ The Subject type ๐Ÿฆ‹

The subject parameter passed to your user functions? That's an object loaded with info about the process being checked. It's type Subject and it comes with these attributes:

  • int pid โ€” the process id. Classic.
  • int uid โ€” the UID of the user of the subject.
  • string user โ€” the user name, bestie.
  • string[] groups โ€” an array of all the groups that user user belongs to.
  • string seat โ€” the seat the subject is associated with โ€” and it's blank if the subject isn't on a local seat.
  • string session โ€” the session the subject is associated with.
  • string system_unit โ€” the systemd unit that the subject's process is part of (if there is one). โš ๏ธ Important caveat, no cap: this can only ever match on system units, because user units can be created with any name by anyone and need zero privileges โ€” unlike system units, which need root to create. So a process running in a user unit will just return the user session unit in this attribute (for example: user-1000.service).
  • boolean local โ€” set to true only if seat is local. That's it.
  • boolean no_new_privileges โ€” set only if system_unit is not empty, and set to true only if the referenced systemd service unit has the NoNewPrivileges= setting enabled. Why do we care? Because this guarantees the process can't gain any new privileges via executing setuid binaries. ๐Ÿ‘‘
  • boolean active โ€” set to true only if the session is active.

Methods available on the Subject type:

  • boolean isInGroup(string groupName);
  • boolean isInNetGroup(string netGroupName);

isInGroup() lets you check if the subject is in a given group, and isInNetGroup() lets you check if the subject is in a given netgroup. Two little bouncers at the door. ๐Ÿšชโœจ


๐ŸŒˆ Authorization Rules Examples ๐ŸŒˆ

Allow all users in the admin group to perform user administration without changing policy for other users:

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.accounts.user-administration" &&
        subject.isInGroup("admin")) {
        return polkit.Result.YES;
    }
});

Define administrative users to be the users in the wheel group:

polkit.addAdminRule(function(action, subject) {
    return ["unix-group:wheel"];
});

Forbid users in group children to change hostname configuration (that means any action with an identifier starting with org.freedesktop.hostname1.) and allow anyone else to do it after authenticating as themselves:

polkit.addRule(function(action, subject) {
    if (action.id.indexOf("org.freedesktop.hostname1.") == 0) {
        if (subject.isInGroup("children")) {
            return polkit.Result.NO;
        } else {
            return polkit.Result.AUTH_SELF_KEEP;
        }
    }
});

Run an external helper to determine if the current user may reboot the system:

polkit.addRule(function(action, subject) {
    if (action.id.indexOf("org.freedesktop.login1.reboot") == 0) {
        try {
            // user-may-reboot exits with success (exit code 0)
            // only if the passed username is authorized
            polkit.spawn(["/opt/company/bin/user-may-reboot",
                          subject.user]);
            return polkit.Result.YES;
        } catch (error) {
            // Nope, but do allow admin authentication
            return polkit.Result.AUTH_ADMIN;
        }
    }
});

The next one shows how the authorization decision can depend on variables passed by the pkexec(1) mechanism:

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.policykit.exec" &&
        action.lookup("program") == "/usr/bin/cat") {
        return polkit.Result.AUTH_ADMIN;
    }
});

And this one is another use of variables passed from the mechanism. In this case the mechanism is UDisks[10], which defines a set of actions and variables[11] that get used to match on:

// Allow users in group 'engineers' to perform any operation on
// some drives without having to authenticate
//
polkit.addRule(function(action, subject) {
    if (action.id.indexOf("org.freedesktop.udisks2.") == 0 &&
        action.lookup("drive.vendor") == "SEAGATE" &&
        action.lookup("drive.model") == "ST3300657SS" &&
        subject.isInGroup("engineers")) {
            return polkit.Result.YES;
        }
    }
});

Allow all processes running as part of the admin.service systemd system unit to perform user administration, as long as they cannot gain new privileges:

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.accounts.user-administration" &&
        subject.system_unit == "admin.service" &&
        subject.no_new_privileges) {
        return polkit.Result.YES;
    }
});

๐Ÿ’œ AUTHOR ๐Ÿ’œ

Written by David Zeuthen <davidz@redhat.com> with a lot of help from many others. Shoutout to the whole squad, honestly. ๐Ÿซถโœจ


๐Ÿ’€ BUGS ๐Ÿ’€

Please send bug reports to either your distribution or the polkit-devel mailing list โ€” see https://github.com/polkit-org/polkit#bugs-and-development. Don't suffer in silence, bestie, tell somebody. ๐Ÿ™ˆ


โญ SEE ALSO โญ

polkitd(8), pkaction(1), pkcheck(1), pkexec(1), pkttyagent(1)


๐ŸŒธ NOTES ๐ŸŒธ

  1. /usr/share/gtk-doc/html/polkit-1/polkit-architecture.png
  2. GObjectIntrospection โ€” https://live.gnome.org/GObjectIntrospection
  3. developer documentation โ€” http://www.freedesktop.org/software/polkit/docs/latest/
  4. /usr/share/gtk-doc/html/polkit-1/polkit-authentication-agent-example.png
  5. /usr/share/gtk-doc/html/polkit-1/polkit-authentication-agent-example-wheel.png
  6. Freedesktop.org Icon Naming Specification โ€” http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
  7. JavaScript โ€” http://en.wikipedia.org/wiki/JavaScript
  8. ECMA-262 edition 5 โ€” http://en.wikipedia.org/wiki/ECMAScript#ECMAScript.2C_5th_Edition
  9. Date โ€” https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
  10. UDisks โ€” http://udisks.freedesktop.org/docs/latest/udisks.8.html
  11. actions and variables โ€” http://udisks.freedesktop.org/docs/latest/udisks-polkit-actions.html

And that's a wrap, bestie! ๐ŸŽ€โœจ This page is <rainbow>polkit</rainbow>, dated February 2021, and it lives under the name POLKIT(8) โ€” go forth and authorize responsibly, ily ๐Ÿ’–๐Ÿฆ‹๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from