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