685fc3d9a7f64c4db8db37f06e64b4c194ca93a5
[oweals/gnunet.git] / src / transport / gnunet-nat-server.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file src/transport/gnunet-nat-server.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as root (SUID will do)
24  *        This code will work under GNU/Linux only (or maybe BSDs, but never W32)
25  * @author Christian Grothoff
26  *
27  * This program will send ONE ICMP message every 500 ms RAW sockets
28  * to a DUMMY IP address and also listens for ICMP replies.  Since
29  * it uses RAW sockets, it must be installed SUID or run as 'root'.
30  * In order to keep the security risk of the resulting SUID binary
31  * minimal, the program ONLY opens the two RAW sockets with root
32  * priviledges, then drops them and only then starts to process
33  * command line arguments.  The code also does not link against
34  * any shared libraries (except libc) and is strictly minimal
35  * (except for checking for errors).  The following list of people
36  * have reviewed this code and considered it safe since the last
37  * modification (if you reviewed it, please have your name added
38  * to the list):
39  *
40  * - Christian Grothoff
41  */
42 #define _GNU_SOURCE
43 #include <sys/types.h> 
44 #include <sys/socket.h>
45 #include <arpa/inet.h>
46 #include <sys/select.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <errno.h>
53 #include <stdlib.h>
54 #include <stdint.h>
55 #include <time.h>
56 #include <netinet/ip.h>
57 #include <netinet/ip_icmp.h>
58 #include <netinet/in.h> 
59
60 /**
61  * Must match IP given in the client.
62  */
63 #define DUMMY_IP "1.2.3.4"
64
65 /**
66  * How often do we send our ICMP messages to receive replies?
67  */
68 #define ICMP_SEND_FREQUENCY_MS 500
69
70 struct ip_packet 
71 {
72   uint8_t vers_ihl;
73   uint8_t tos;
74   uint16_t pkt_len;
75   uint16_t id;
76   uint16_t flags_frag_offset;
77   uint8_t ttl;
78   uint8_t proto;
79   uint16_t checksum;
80   uint32_t src_ip;
81   uint32_t dst_ip;
82 };
83
84 struct icmp_packet 
85 {
86   uint8_t type;
87   uint8_t code;
88   uint16_t checksum;
89   uint32_t reserved;
90 };
91
92
93 static int icmpsock;
94
95 static int rawsock;
96
97 static struct in_addr dummy;
98
99 static uint16_t 
100 calc_checksum(const uint16_t *data, 
101               unsigned int bytes)
102 {
103   uint32_t sum;
104   unsigned int i;
105
106   sum = 0;
107   for (i=0;i<bytes/2;i++) 
108     sum += data[i];        
109   sum = (sum & 0xffff) + (sum >> 16);
110   sum = htons(0xffff - sum);
111   return sum;
112 }
113
114
115 static void
116 make_echo (const struct in_addr *src_ip,
117            struct icmp_packet *echo)
118 {
119   memset(echo, 0, sizeof(struct icmp_packet));
120   echo->type = ICMP_ECHO;
121   echo->code = 0;
122   echo->reserved = 0;
123   echo->checksum = 0;
124   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
125 }
126
127
128 /**
129  * Send an ICMP message to the dummy IP.
130  *
131  * @param my_ip source address (our ip address)
132  */
133 static void
134 send_icmp_echo (const struct in_addr *my_ip)
135 {
136   struct icmp_packet icmp_echo;
137   struct sockaddr_in dst;
138   size_t off;
139   int err;
140   struct ip_packet ip_pkt;
141   struct icmp_packet icmp_pkt;
142   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
143
144   off = 0;
145   memset(&ip_pkt, 0, sizeof(ip_pkt));
146   ip_pkt.vers_ihl = 0x45;
147   ip_pkt.tos = 0;
148   ip_pkt.pkt_len = sizeof (packet);
149   ip_pkt.id = 1;
150   ip_pkt.flags_frag_offset = 0;
151   ip_pkt.ttl = IPDEFTTL;
152   ip_pkt.proto = IPPROTO_ICMP;
153   ip_pkt.checksum = 0; 
154   ip_pkt.src_ip = my_ip->s_addr;
155   ip_pkt.dst_ip = dummy.s_addr;
156   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
157   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
158   off += sizeof (ip_pkt);
159   make_echo (my_ip, &icmp_echo);
160   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
161   off += sizeof (icmp_echo);
162  
163   memset (&dst, 0, sizeof (dst));
164   dst.sin_family = AF_INET;
165   dst.sin_addr = dummy;
166   err = sendto(rawsock, 
167                packet, off, 0, 
168                (struct sockaddr*)&dst, 
169                sizeof(dst));
170   if (err < 0) 
171     {
172       fprintf(stderr,
173               "sendto failed: %s\n", strerror(errno));
174     }
175   else if (err != off) 
176     {
177       fprintf(stderr,
178               "Error: partial send of ICMP message\n");
179     }
180 }
181
182
183 static void
184 process_icmp_response ()
185 {
186   char buf[65536];
187   ssize_t have;
188   struct in_addr sip;
189   struct ip_packet ip_pkt;
190   struct icmp_packet icmp_pkt;
191   size_t off;
192   
193   have = read (icmpsock, buf, sizeof (buf));
194   if (have == -1)
195     {
196       fprintf (stderr,
197                "Error reading raw socket: %s\n",
198                strerror (errno));
199       return; 
200     }
201   if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
202     {
203       fprintf (stderr,
204                "Received ICMP message of unexpected size: %u bytes\n",
205                (unsigned int) have);
206       return;
207     }
208   off = 0;
209   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
210   off += sizeof (ip_pkt);
211   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
212   off += sizeof (icmp_pkt);
213   if ( (ip_pkt.proto != IPPROTO_ICMP) ||
214        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
215        (icmp_pkt.code != 0) )
216     {
217       /* maybe we got an actual reply back... */
218       return;    
219     }
220   memcpy(&sip, 
221          &ip_pkt.src_ip, 
222          sizeof (sip));
223   fprintf (stdout,
224            "%s\n",
225            inet_ntop (AF_INET,
226                       &sip,
227                       buf,
228                       sizeof (buf)));
229   fflush (stdout);
230 }
231
232
233 static int
234 make_icmp_socket ()
235 {
236   int ret;
237
238   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
239   if (-1 == ret)
240     {
241       fprintf (stderr,
242                "Error opening RAW socket: %s\n",
243                strerror (errno));
244       return -1;
245     }  
246   if (ret >= FD_SETSIZE) 
247     {
248       fprintf (stderr,
249                "Socket number too large (%d > %u)\n",
250                ret,
251                (unsigned int) FD_SETSIZE);
252       close (ret);
253       return -1;
254     }
255   return ret;
256 }
257
258
259 static int
260 make_raw_socket ()
261 {
262   const int one = 1;
263   int ret;
264
265   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
266   if (-1 == ret)
267     {
268       fprintf (stderr,
269                "Error opening RAW socket: %s\n",
270                strerror (errno));
271       return -1;
272     }  
273   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
274                  (char *)&one, sizeof(one)) == -1)
275     fprintf(stderr,
276             "setsockopt failed: %s\n",
277             strerror (errno));
278   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
279                  (char *)&one, sizeof(one)) == -1)
280     fprintf(stderr,
281             "setsockopt failed: %s\n",
282             strerror (errno));
283   return ret;
284 }
285
286
287 int
288 main (int argc, char *const *argv)
289 {
290   struct in_addr external;
291   fd_set rs;
292   struct timeval tv;
293   uid_t uid;
294
295   if (-1 == (icmpsock = make_icmp_socket()))
296     return 1; 
297   if (-1 == (rawsock = make_raw_socket()))
298     {
299       close (icmpsock);
300       return 1; 
301     }
302   uid = getuid ();
303   if (0 != setresuid (uid, uid, uid))
304     fprintf (stderr,
305              "Failed to setresuid: %s\n",
306              strerror (errno));    
307   if (argc != 2)
308     {
309       fprintf (stderr,
310                "This program must be started with our external IP as the only argument.\n");
311       return 1;
312     }
313   if (1 != inet_pton (AF_INET, argv[1], &external))
314     {
315       fprintf (stderr,
316                "Error parsing IPv4 address: %s\n",
317                strerror (errno));
318       return 1;
319     }
320   inet_pton (AF_INET, DUMMY_IP, &dummy);
321   while (1)
322     {
323       FD_ZERO (&rs);
324       FD_SET (icmpsock, &rs);
325       tv.tv_sec = 0;
326       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
327       select (icmpsock + 1, &rs, NULL, NULL, &tv);
328       if (FD_ISSET (icmpsock, &rs))
329         process_icmp_response ();
330       send_icmp_echo (&external);
331     }  
332   return 0;
333 }
334
335
336 /* end of gnunet-nat-server.c */