Why can't I create a raw socket in Ubuntu?

I am learning how to work with raw sockets on Linux. I am trying to create a socket like this:

if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { perror("socket() failed"); exit(-1); } 

But all I got after launch:

socket () failed: operation not allowed

I know that only root can create raw sockets, but if I run it with the SUID or sudo bit, the problem is the same. What's wrong? Ubuntu 11.04 system.

Perhaps I include unnecessary headers?

 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <netdb.h> #include <sys/time.h> #include <signal.h> #include <unistd.h> 

And I wonder - why is SUID useless?

+4
source share
3 answers

My money for you does not work correctly with your code.

I copied and pasted your exact code into empty main() . I get the same error if I run it as myself, but it works correctly under sudo . This is on Ubuntu.

Code:

 #include <sys/socket.h> #include <netinet/in.h> int main() { int sd; if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { perror("socket() failed"); return -1; } return 0; } 

Run like me:

 aix@aix :~$ ./a.out socket() failed: Operation not permitted aix@aix :~$ 

Run as root:

 aix@aix :~$ sudo ./a.out aix@aix :~$ 
+13
source

according to the person: only processes with effective user ID 0 or CAP_NET_RAW capabilities are allowed to open raw sockets

So, you can run the application using sudo, as suggested below, or set CAP_NET_RAW features for it (in fact, you will need CAP_NET_ADMIN):

 # setcap cap_net_raw,cap_net_admin=eip PATH_TO_YOUR_APPLICATION 

Details can be found at http://ftp.kernel.org/pub/linux/libs/security/linux-privs/kernel-2.4/capfaq-0.2.txt

+6
source

The title will not affect it in any way.

Even if you add a few unnecessary files, this will not affect the program.

0
source

All Articles