3

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?

Paolo M
  • 12,403
  • 6
  • 52
  • 73

2 Answers2

9

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.

Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • Thank you, It worked! But, if I try to debug it in Eclipse, the socket function returns -1 again. I've tryed to set the cap_new_raw capability both to eclipse and gdb, but it doesn't work. – Paolo M Mar 04 '15 at 15:38
  • 1
    Ah. Yes, debugging programs with capabilities (or that have the suid bit set) is a bit of a problem, because allowing an unprivileged user to `ptrace` them would be a rather big security hole. Perhaps you can configure eclipse to run gdb with sudo, which would allow you to debug the application by diving head-first into the security nightmare of giving an unprivileged user the ability to run a suid debugger. I don't think there's a perfect solution for this problem. – Wintermute Mar 04 '15 at 15:50
  • A workaround I've found is to run eclipse as a superuser. It's not very elegant, but it works. – Paolo M Mar 20 '15 at 14:31
  • Ok, opening eclipse with sudo is not a good idea! A better solution is described here: http://stackoverflow.com/questions/2891356/how-to-debug-application-as-root-in-eclipse-in-ubuntu – Paolo M Mar 20 '15 at 14:46
1

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.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • And still no way to debug SUID programm from non-root, just like with `setcap cap_net_raw+ep` – osgx Mar 04 '15 at 15:52