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