Merge pull request #60775 from azat/fix-32-bit-capabilities

Use 64-bit capabilities if available
This commit is contained in:
Alexey Milovidov 2024-03-05 04:52:27 +03:00 committed by GitHub
commit fb9250a1ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,6 +5,8 @@
#include <syscall.h> #include <syscall.h>
#include <unistd.h> #include <unistd.h>
#include <linux/capability.h> #include <linux/capability.h>
#include <cstdint>
#include <base/types.h>
#include <Common/Exception.h> #include <Common/Exception.h>
@ -16,25 +18,48 @@ namespace ErrorCodes
extern const int NETLINK_ERROR; extern const int NETLINK_ERROR;
} }
static __user_cap_data_struct getCapabilities() struct Capabilities
{
UInt64 effective;
UInt64 permitted;
UInt64 inheritable;
};
static Capabilities getCapabilities()
{ {
/// See man getcap. /// See man getcap.
__user_cap_header_struct request{}; __user_cap_header_struct request{};
request.version = _LINUX_CAPABILITY_VERSION_1; /// It's enough to check just single CAP_NET_ADMIN capability we are interested. request.version = _LINUX_CAPABILITY_VERSION_3;
request.pid = getpid(); request.pid = getpid();
__user_cap_data_struct response{}; Capabilities ret{};
__user_cap_data_struct response[2] = {};
/// Avoid dependency on 'libcap'. /// Avoid dependency on 'libcap'.
if (0 != syscall(SYS_capget, &request, &response)) if (0 == syscall(SYS_capget, &request, response))
throw ErrnoException(ErrorCodes::NETLINK_ERROR, "Cannot do 'capget' syscall"); {
ret.effective = static_cast<UInt64>(response[1].effective) << 32 | response[0].effective;
ret.permitted = static_cast<UInt64>(response[1].permitted) << 32 | response[0].permitted;
ret.inheritable = static_cast<UInt64>(response[1].inheritable) << 32 | response[0].inheritable;
return ret;
}
return response; /// Does not supports V3, fallback to V1.
/// It's enough to check just single CAP_NET_ADMIN capability we are interested.
if (errno == EINVAL && 0 == syscall(SYS_capget, &request, response))
{
ret.effective = response[0].effective;
ret.permitted = response[0].permitted;
ret.inheritable = response[0].inheritable;
return ret;
}
throw ErrnoException(ErrorCodes::NETLINK_ERROR, "Cannot do 'capget' syscall");
} }
bool hasLinuxCapability(int cap) bool hasLinuxCapability(int cap)
{ {
static __user_cap_data_struct capabilities = getCapabilities(); static Capabilities capabilities = getCapabilities();
return (1 << cap) & capabilities.effective; return (1 << cap) & capabilities.effective;
} }