(no commit message)
[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  * privileges, 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 "192.0.2.86"
64
65 #define VERBOSE 0
66
67 /**
68  * How often do we send our ICMP messages to receive replies?
69  */
70 #define ICMP_SEND_FREQUENCY_MS 500
71
72 struct ip_packet 
73 {
74   uint8_t vers_ihl;
75   uint8_t tos;
76   uint16_t pkt_len;
77   uint16_t id;
78   uint16_t flags_frag_offset;
79   uint8_t ttl;
80   uint8_t proto;
81   uint16_t checksum;
82   uint32_t src_ip;
83   uint32_t dst_ip;
84 };
85
86 struct icmp_packet 
87 {
88   uint8_t type;
89   uint8_t code;
90   uint16_t checksum;
91   uint32_t reserved;
92 };
93
94 struct udp_packet
95 {
96   uint16_t src_port;
97
98   uint16_t dst_port;
99
100   uint32_t length;
101 };
102
103 static int icmpsock;
104
105 static int rawsock;
106
107 static struct in_addr dummy;
108
109 static uint16_t 
110 calc_checksum(const uint16_t *data, 
111               unsigned int bytes)
112 {
113   uint32_t sum;
114   unsigned int i;
115
116   sum = 0;
117   for (i=0;i<bytes/2;i++) 
118     sum += data[i];        
119   sum = (sum & 0xffff) + (sum >> 16);
120   sum = htons(0xffff - sum);
121   return sum;
122 }
123
124
125 static void
126 make_echo (const struct in_addr *src_ip,
127            struct icmp_packet *echo)
128 {
129   memset(echo, 0, sizeof(struct icmp_packet));
130   echo->type = ICMP_ECHO;
131   echo->code = 0;
132   echo->reserved = 0;
133   echo->checksum = 0;
134   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
135 }
136
137
138 /**
139  * Send an ICMP message to the dummy IP.
140  *
141  * @param my_ip source address (our ip address)
142  */
143 static void
144 send_icmp_echo (const struct in_addr *my_ip)
145 {
146   struct icmp_packet icmp_echo;
147   struct sockaddr_in dst;
148   size_t off;
149   int err;
150   struct ip_packet ip_pkt;
151   struct icmp_packet icmp_pkt;
152   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
153
154   off = 0;
155   memset(&ip_pkt, 0, sizeof(ip_pkt));
156   ip_pkt.vers_ihl = 0x45;
157   ip_pkt.tos = 0;
158   ip_pkt.pkt_len = sizeof (packet);
159   ip_pkt.id = 1;
160   ip_pkt.flags_frag_offset = 0;
161   ip_pkt.ttl = IPDEFTTL;
162   ip_pkt.proto = IPPROTO_ICMP;
163   ip_pkt.checksum = 0; 
164   ip_pkt.src_ip = my_ip->s_addr;
165   ip_pkt.dst_ip = dummy.s_addr;
166   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
167   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
168   off += sizeof (ip_pkt);
169   make_echo (my_ip, &icmp_echo);
170   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
171   off += sizeof (icmp_echo);
172  
173   memset (&dst, 0, sizeof (dst));
174   dst.sin_family = AF_INET;
175   dst.sin_addr = dummy;
176   err = sendto(rawsock, 
177                packet, off, 0, 
178                (struct sockaddr*)&dst, 
179                sizeof(dst));
180   if (err < 0) 
181     {
182 #if VERBOSE
183       fprintf(stderr,
184               "sendto failed: %s\n", strerror(errno));
185 #endif
186     }
187   else if (err != off) 
188     {
189       fprintf(stderr,
190               "Error: partial send of ICMP message\n");
191     }
192 }
193
194
195 static void
196 process_icmp_response ()
197 {
198   char buf[65536];
199   ssize_t have;
200   struct in_addr sip;
201   struct ip_packet ip_pkt;
202   struct icmp_packet icmp_pkt;
203   struct udp_packet udp_pkt;
204   size_t off;
205   int have_port;
206   int have_udp;
207   uint32_t port;
208   
209   have = read (icmpsock, buf, sizeof (buf));
210   if (have == -1)
211     {
212       fprintf (stderr,
213                "Error reading raw socket: %s\n",
214                strerror (errno));
215       return; 
216     }
217   have_port = 0;
218
219   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
220     {
221       have_port = 1;
222     }
223   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
224     {
225 #if VERBOSE
226       fprintf (stderr,
227                "Received ICMP message of unexpected size: %u bytes\n",
228                (unsigned int) have);
229 #endif
230       return;
231     }
232   off = 0;
233   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
234   off += sizeof (ip_pkt);
235   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
236   off += sizeof (icmp_pkt);
237   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
238        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
239        (icmp_pkt.code != 0) )
240     {
241       /* maybe we got an actual reply back... */
242       return;    
243     }
244   memcpy(&sip, 
245          &ip_pkt.src_ip, 
246          sizeof (sip));
247
248   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
249   off += sizeof (ip_pkt);
250
251   have_udp = 0;
252   if (ip_pkt.proto == IPPROTO_UDP)
253     {
254       have_udp = 1;
255     }
256
257   if (have_port)
258     {
259       memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
260       port = ntohs(port);
261       fprintf (stdout,
262               "%s:%d\n",
263               inet_ntop (AF_INET,
264                          &sip,
265                          buf,
266                          sizeof (buf)), port);
267     }
268   else if (have_udp)
269     {
270       memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
271       fprintf (stdout,
272                "%s:%d\n",
273                inet_ntop (AF_INET,
274                           &sip,
275                           buf,
276                           sizeof (buf)), ntohl(udp_pkt.length));
277     }
278   else
279     {
280       fprintf (stdout,
281               "%s\n",
282               inet_ntop (AF_INET,
283                          &sip,
284                          buf,
285                          sizeof (buf)));
286     }
287   fflush (stdout);
288 }
289
290
291 static int
292 make_icmp_socket ()
293 {
294   int ret;
295
296   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
297   if (-1 == ret)
298     {
299       fprintf (stderr,
300                "Error opening RAW socket: %s\n",
301                strerror (errno));
302       return -1;
303     }  
304   if (ret >= FD_SETSIZE) 
305     {
306       fprintf (stderr,
307                "Socket number too large (%d > %u)\n",
308                ret,
309                (unsigned int) FD_SETSIZE);
310       close (ret);
311       return -1;
312     }
313   return ret;
314 }
315
316
317 static int
318 make_raw_socket ()
319 {
320   const int one = 1;
321   int ret;
322
323   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
324   if (-1 == ret)
325     {
326       fprintf (stderr,
327                "Error opening RAW socket: %s\n",
328                strerror (errno));
329       return -1;
330     }  
331   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
332                  (char *)&one, sizeof(one)) == -1)
333     fprintf(stderr,
334             "setsockopt failed: %s\n",
335             strerror (errno));
336   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
337                  (char *)&one, sizeof(one)) == -1)
338     fprintf(stderr,
339             "setsockopt failed: %s\n",
340             strerror (errno));
341   return ret;
342 }
343
344
345 int
346 main (int argc, char *const *argv)
347 {
348   struct in_addr external;
349   fd_set rs;
350   struct timeval tv;
351   uid_t uid;
352
353   if (-1 == (icmpsock = make_icmp_socket()))
354     return 1; 
355   if (-1 == (rawsock = make_raw_socket()))
356     {
357       close (icmpsock);
358       return 1; 
359     }
360   uid = getuid ();
361   if (0 != setresuid (uid, uid, uid))
362     fprintf (stderr,
363              "Failed to setresuid: %s\n",
364              strerror (errno));    
365   if (argc != 2)
366     {
367       fprintf (stderr,
368                "This program must be started with our (internal NAT) IP as the only argument.\n");
369       return 1;
370     }
371   if (1 != inet_pton (AF_INET, argv[1], &external))
372     {
373       fprintf (stderr,
374                "Error parsing IPv4 address: %s\n",
375                strerror (errno));
376       return 1;
377     }
378   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
379   while (1)
380     {
381       FD_ZERO (&rs);
382       FD_SET (icmpsock, &rs);
383       tv.tv_sec = 0;
384       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
385       select (icmpsock + 1, &rs, NULL, NULL, &tv);
386       if (FD_ISSET (icmpsock, &rs))
387         process_icmp_response ();
388       send_icmp_echo (&external);
389     }  
390   return 0;
391 }
392
393
394 /* end of gnunet-nat-server.c */