Skip to content

Commit 95bbd04

Browse files
committed
src: allow CAP_NET_BIND_SERVICE in SafeGetenv
This commit updates SafeGetenv to check if the current process has the effective capability cap_net_bind_service set, and if so allows environment variables to be read. The motivation for this change is a use-case where Node is run in a container, and the is a requirement to be able to listen to ports below 1024. This is done by setting the capability of cap_net_bind_service. In addition there is a need to set the environment variable `NODE_EXTRA_CA_CERTS`. But currently this environment variable will not be read when the capability has been set on the executable.
1 parent 13b569c commit 95bbd04

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/node_credentials.cc

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
#if !defined(_MSC_VER)
1212
#include <unistd.h> // setuid, getuid
1313
#endif
14+
#ifdef __linux__
15+
#include <linux/capability.h>
16+
#include <sys/syscall.h>
17+
#endif // __linux__
1418

1519
namespace node {
1620

@@ -33,11 +37,38 @@ bool linux_at_secure = false;
3337

3438
namespace credentials {
3539

36-
// Look up environment variable unless running as setuid root.
40+
#if defined(__linux__)
41+
// Returns true if the current process only has the passed-in capability.
42+
bool HasOnly(int capability) {
43+
DCHECK(cap_valid(capability));
44+
45+
struct __user_cap_data_struct cap_data[2];
46+
struct __user_cap_header_struct cap_header_data = {
47+
_LINUX_CAPABILITY_VERSION_3,
48+
getpid()};
49+
50+
51+
if (syscall(SYS_capget, &cap_header_data, &cap_data[0]) != 0) {
52+
return false;
53+
}
54+
return cap_data[0].effective ==
55+
static_cast<unsigned int>(CAP_TO_MASK(capability));
56+
}
57+
#endif
58+
59+
// Look up the environment variable and allow the lookup if the current
60+
// process only has the capability CAP_NET_BIND_SERVICE set. If the current
61+
// process does not have any capabilities set and the process is running as
62+
// setuid root then lookup will not be allowed.
3763
bool SafeGetenv(const char* key, std::string* text, Environment* env) {
3864
#if !defined(__CloudABI__) && !defined(_WIN32)
65+
#if defined(__linux__)
66+
if ((!HasOnly(CAP_NET_BIND_SERVICE) && per_process::linux_at_secure) ||
67+
getuid() != geteuid() || getgid() != getegid())
68+
#else
3969
if (per_process::linux_at_secure || getuid() != geteuid() ||
4070
getgid() != getegid())
71+
#endif
4172
goto fail;
4273
#endif
4374

0 commit comments

Comments
 (0)