diff --git a/NmapOps.cc b/NmapOps.cc index 78cd6690b..9b85af0a4 100644 --- a/NmapOps.cc +++ b/NmapOps.cc @@ -227,8 +227,13 @@ void NmapOps::Initialize() { isr00t = 1; else if (getenv("NMAP_UNPRIVILEGED")) isr00t = 0; - else - isr00t = !(geteuid()); + else { +#ifdef __linux__ + isr00t = (geteuid() == 0) || have_net_capabilities(); +#else + isr00t = (geteuid() == 0); +#endif + } #endif have_pcap = true; debugging = 0; diff --git a/nbase/nbase.h b/nbase/nbase.h index 33aaf80e2..740028665 100644 --- a/nbase/nbase.h +++ b/nbase/nbase.h @@ -590,6 +590,12 @@ typedef bitvector_t octet_bitvector[(256 - 1) / (sizeof(unsigned long) * CHAR_BI #include "nbase_ipv6.h" +#ifdef __linux__ +/* Returns non-zero if the process has CAP_NET_RAW effective. + * See nbase_misc.c for details. */ +int have_net_capabilities(void); +#endif + #ifdef __cplusplus } #endif diff --git a/nbase/nbase_misc.c b/nbase/nbase_misc.c index 319c31bb5..ace30d1c6 100644 --- a/nbase/nbase_misc.c +++ b/nbase/nbase_misc.c @@ -858,3 +858,29 @@ const char *sockaddr_storage_iptop(const struct sockaddr_storage * addr, char * return NULL; }} } + +/* Returns non-zero if the process has CAP_NET_RAW in its effective capability + * set. Handles setcap deployments where the binary runs as a non-root UID: + * sudo setcap cap_net_raw=ep /usr/bin/nmap + * CAP_NET_RAW is sufficient for the raw sockets and pcap packet capture nmap + * performs (promiscuous mode via PACKET_MR_PROMISC on an AF_PACKET socket + * requires only CAP_NET_RAW). + * Uses /proc/self/status to avoid a libcap dependency. */ +#ifdef __linux__ +int have_net_capabilities(void) { + FILE *f = fopen("/proc/self/status", "r"); + if (!f) + return 0; + char line[256]; + uint64_t capeff = 0; + while (fgets(line, sizeof(line), f)) { + if (strncmp(line, "CapEff:", 7) == 0) { + sscanf(line + 7, "%" SCNx64, &capeff); + break; + } + } + fclose(f); + /* CAP_NET_RAW=13 */ + return (capeff & (UINT64_C(1) << 13)) != 0; +} +#endif /* __linux__ */ diff --git a/nping/NpingOps.cc b/nping/NpingOps.cc index 84fcc0bdf..08aed6a60 100644 --- a/nping/NpingOps.cc +++ b/nping/NpingOps.cc @@ -136,8 +136,13 @@ NpingOps::NpingOps() { isr00t=true; else if (getenv("NMAP_UNPRIVILEGED") || getenv("NPING_UNPRIVILEGED")) isr00t=false; - else - isr00t = !(geteuid()); + else { +#ifdef __linux__ + isr00t = (geteuid() == 0) || have_net_capabilities(); +#else + isr00t = (geteuid() == 0); +#endif + } #endif /* Payloads */