capng_have_permitted_capabilities - Linux


Overview

capng_have_permitted_capabilities checks if a set of capabilities is present in the permitted capability set of the calling process. This capability is useful for checking whether the process has specific privileges or permissions granted to it.

Syntax

int capng_have_permitted_capabilities(capng_set_t *permitted, capng_set_t *requested)

Parameters:

  • permitted: A set of capabilities to check against.
  • requested: A set of capabilities to test for in the permitted set.

Return Value:

  • Returns 0 if all capabilities in requested are present in permitted.
  • Returns -1 if any of the capabilities in requested are not present in permitted.

Options/Flags

None.

Examples

Check if the process has the CAP_NET_ADMIN capability:

#include <cap-ng.h>

int main() {
  capng_set_t permitted;
  capng_set_t requested;

  capng_have_permitted_capabilities(NULL, &permitted);

  capng_set_init(&requested);
  capng_set_add(&requested, CAP_NET_ADMIN);

  if (capng_have_permitted_capabilities(&permitted, &requested) == -1) {
    perror("Process does not have CAP_NET_ADMIN capability");
    return 1;
  }

  // The process has the CAP_NET_ADMIN capability
  return 0;
}

Check if the process has the CAP_SETPCAP and CAP_SYS_ADMIN capabilities:

#include <cap-ng.h>

int main() {
  capng_set_t permitted;
  capng_set_t requested;

  capng_have_permitted_capabilities(NULL, &permitted);

  capng_set_init(&requested);
  capng_set_add(&requested, CAP_SETPCAP);
  capng_set_add(&requested, CAP_SYS_ADMIN);

  if (capng_have_permitted_capabilities(&permitted, &requested) == 0) {
    // The process has both CAP_SETPCAP and CAP_SYS_ADMIN capabilities
    return 0;
  } else {
    perror("Process does not have both CAP_SETPCAP and CAP_SYS_ADMIN capabilities");
    return 1;
  }
}

Common Issues

  • Ensure that the cap-ng library is installed and configured correctly.
  • Verify that the process has sufficient privileges to perform the capability check.
  • If using the libcap-ng library, make sure to call capng_drop_permitted() after performing the check to release any elevated privileges.

Integration

capng_have_permitted_capabilities can be combined with other Linux commands and tools to create complex security checks or privilege escalation scenarios.

Example: Script to check for and escalate to root privileges:

#!/bin/bash

# Check if the process has CAP_SETUID
if capng_have_permitted_capabilities NULL CAP_SETUID; then
  # Process has CAP_SETUID, escalate to root
  sudo python -c 'import os; os.setuid(0)'
else
  echo "Process does not have CAP_SETUID"
fi

Related Commands

  • capng_get_permitted_capabilities: Gets the permitted capability set of the calling process.
  • capng_set_permitted_capabilities: Sets the permitted capability set of the calling process.
  • capng_drop_permitted: Drops all elevated privileges from the permitted capability set.