Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening RAW sockets in linux without being superuser

Tags:

c++

c

linux

sockets

I have to write a ping function to run on Linux. The language is C++, so C if fine too.

Searching on the Internet and looking at the source code for the ping command, it turns out that I should create a raw socket:

icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

If I run my application without being superuser, the socket function returns -1 i.e. the socket is not created successfully. If I run it as a superuser, all works fine.

Now, the ping command do create a raw socket and I can run it without superuser rights.

My question is: how can I grant my application all permissions needed to create a raw socket without being executed by a superuser?

like image 687
Paolo M Avatar asked Jan 29 '26 03:01

Paolo M


2 Answers

ping needs the cap_net_raw capability to do this without (other) superuser rights, and so does your program. Run

setcap cap_net_raw+ep your_executable_file

as root, and then normal users will be able to use the program.

like image 90
Wintermute Avatar answered Jan 30 '26 15:01

Wintermute


You can make your program a SUID command, granting it effectively root permissions, without granting them to the executing user. For an example and explanation see here.

like image 36
Eugene Sh. Avatar answered Jan 30 '26 17:01

Eugene Sh.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!