more code cleanup
[oweals/gnunet.git] / src / transport / gnunet-nat-client-windows.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-client-windows.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as
24  *        root (SUID will do) or administrator on W32
25  *        This code will work under GNU/Linux or W32.
26  * @author Nathan Evans
27  *
28  * This program will send ONE ICMP message using RAW sockets
29  * to the IP address specified as the second argument.  Since
30  * it uses RAW sockets, it must be installed SUID or run as 'root'.
31  * In order to keep the security risk of the resulting SUID binary
32  * minimal, the program ONLY opens the RAW socket with root
33  * privileges, then drops them and only then starts to process
34  * command line arguments.  The code also does not link against
35  * any shared libraries (except libc) and is strictly minimal
36  * (except for checking for errors).  The following list of people
37  * have reviewed this code and considered it safe since the last
38  * modification (if you reviewed it, please have your name added
39  * to the list):
40  *
41  * - Christian Grothoff
42  * - Nathan Evans
43  */
44 #define _GNU_SOURCE
45
46 #include <ws2tcpip.h>
47 #include <winsock2.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
58
59 #define ICMP_ECHO 8
60 #define IPDEFTTL 64
61 #define ICMP_TIME_EXCEEDED 11
62
63 /**
64  * Must match IP given in the server.
65  */
66 #define DUMMY_IP "192.0.2.86"
67
68 #define NAT_TRAV_PORT 22225
69
70 /**
71  * IPv4 header.
72  */
73 struct ip_packet 
74 {
75
76   /**
77    * Version (4 bits) + Internet header length (4 bits) 
78    */
79   uint8_t vers_ihl; 
80
81   /**
82    * Type of service
83    */
84   uint8_t tos;  
85
86   /**
87    * Total length
88    */
89   uint16_t pkt_len;  
90
91   /**
92    * Identification
93    */
94   uint16_t id;    
95
96   /**
97    * Flags (3 bits) + Fragment offset (13 bits)
98    */
99   uint16_t flags_frag_offset; 
100
101   /**
102    * Time to live
103    */
104   uint8_t  ttl;   
105
106   /**
107    * Protocol       
108    */
109   uint8_t  proto; 
110
111   /**
112    * Header checksum
113    */
114   uint16_t checksum; 
115
116   /**
117    * Source address
118    */
119   uint32_t  src_ip;  
120
121   /**
122    * Destination address 
123    */
124   uint32_t  dst_ip;  
125 };
126
127
128 /**
129  * Format of ICMP packet.
130  */
131 struct icmp_packet 
132 {
133   uint8_t type;
134
135   uint8_t code;
136
137   uint16_t checksum;
138
139   uint32_t reserved;
140 };
141
142 struct icmp_echo_packet
143 {
144   uint8_t type;
145   uint8_t code;
146   uint16_t checksum;
147   uint32_t reserved;
148   uint32_t data;
149 };
150
151 /**
152  * Beginning of UDP packet.
153  */
154 struct udp_packet
155 {
156   uint16_t src_port;
157
158   uint16_t dst_port;
159
160   uint32_t length;
161 };
162
163
164 /**
165  * Socket we use to send our ICMP packets.
166  */
167 static SOCKET rawsock;
168
169 /**
170  * Target "dummy" address.
171  */
172 static struct in_addr dummy;
173
174 /**
175  * Port we are listening on (communicated to the server).
176  */ 
177 static uint16_t port;
178
179
180
181 /**
182  * Convert IPv4 address from text to binary form.
183  *
184  * @param af address family
185  * @param cp the address to print
186  * @param buf where to write the address result
187  * @return 1 on success
188  */
189 static int 
190 inet_pton (int af, 
191            const char *cp, 
192            struct in_addr *buf)
193 {
194   buf->s_addr = inet_addr(cp);
195   if (buf->s_addr == INADDR_NONE)
196     {
197       fprintf(stderr, 
198               "Error %d handling address %s", 
199               WSAGetLastError(), 
200               cp);
201       return 0;
202     }
203   return 1;
204 }
205
206
207 /**
208  * CRC-16 for IP/ICMP headers.
209  *
210  * @param data what to calculate the CRC over
211  * @param bytes number of bytes in data (must be multiple of 2)
212  * @return the CRC 16.
213  */
214 static uint16_t 
215 calc_checksum(const uint16_t *data, 
216               unsigned int bytes)
217 {
218   uint32_t sum;
219   unsigned int i;
220
221   sum = 0;
222   for (i=0;i<bytes/2;i++) 
223     sum += data[i];        
224   sum = (sum & 0xffff) + (sum >> 16);
225   sum = htons(0xffff - sum);
226   return sum;
227 }
228
229
230 /**
231  * Send an ICMP message to the target.
232  *
233  * @param my_ip source address
234  * @param other target address
235  */
236 static void
237 send_icmp_udp (const struct in_addr *my_ip,
238                const struct in_addr *other)
239 {
240   struct ip_packet ip_pkt;
241   struct icmp_packet icmp_pkt;
242   struct udp_packet udp_pkt;
243
244   struct sockaddr_in dst;
245   char packet[sizeof(ip_pkt) * 2 + sizeof(icmp_pkt) * 2 + sizeof(uint32_t)];
246
247   size_t off;
248   int err;
249
250   /* ip header: send to (known) ip address */
251   off = 0;
252   ip_pkt.vers_ihl = 0x45;
253   ip_pkt.tos = 0;
254   ip_pkt.pkt_len = htons(sizeof (packet));
255   ip_pkt.id = htons(256);
256   ip_pkt.flags_frag_offset = 0;
257   ip_pkt.ttl = 128;
258   ip_pkt.proto = IPPROTO_ICMP;
259   ip_pkt.checksum = 0;
260   ip_pkt.src_ip = my_ip->s_addr;
261   ip_pkt.dst_ip = other->s_addr;
262   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
263   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
264   off += sizeof(ip_pkt);
265
266   /* ip header of the presumably 'lost' udp packet */
267   ip_pkt.vers_ihl = 0x45;
268   ip_pkt.tos = 0;
269   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
270
271   icmp_pkt.type = 11; /* TTL exceeded */
272   icmp_pkt.code = 0;
273   icmp_pkt.checksum = 0;
274   icmp_pkt.reserved = 0;
275   memcpy(&packet[off], &icmp_pkt, sizeof(icmp_pkt));
276   off += sizeof(icmp_pkt);
277
278   /* build inner IP header */
279   memset(&ip_pkt, 0, sizeof(ip_pkt));
280   ip_pkt.vers_ihl = 0x45;
281   ip_pkt.tos = 0;
282   ip_pkt.pkt_len = htons(sizeof (ip_pkt) + sizeof(udp_pkt));
283   ip_pkt.id = htons(0);
284   ip_pkt.flags_frag_offset = 0;
285   ip_pkt.ttl = 128;
286   ip_pkt.proto = IPPROTO_UDP;
287   ip_pkt.checksum = 0;
288   ip_pkt.src_ip = other->s_addr;
289   ip_pkt.dst_ip = dummy.s_addr;
290   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
291   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
292   off += sizeof(ip_pkt);
293
294   /* build UDP header */
295   udp_pkt.src_port = htons(NAT_TRAV_PORT);
296   udp_pkt.dst_port = htons(NAT_TRAV_PORT);
297
298   memset(&udp_pkt.length, 0, sizeof(uint32_t));
299   udp_pkt.length = htons (port);
300   memcpy(&packet[off], &udp_pkt, sizeof(udp_pkt));
301   off += sizeof(udp_pkt);
302
303   /* set ICMP checksum */
304   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&packet[sizeof(ip_pkt)],
305                             sizeof (icmp_pkt) + sizeof(ip_pkt) + sizeof(udp_pkt)));
306   memcpy (&packet[sizeof(ip_pkt)], &icmp_pkt, sizeof (icmp_pkt));
307
308
309   memset (&dst, 0, sizeof (dst));
310   dst.sin_family = AF_INET;
311   dst.sin_addr = *other;
312   err = sendto(rawsock,
313                packet,
314                off, 0,
315                (struct sockaddr*)&dst,
316                sizeof(dst));
317
318   if (err < 0)
319     {
320       fprintf(stderr,
321               "sendto failed: %s\n", strerror(errno));
322     }
323   else if (err != off)
324     {
325       fprintf(stderr,
326               "Error: partial send of ICMP message\n");
327     }
328 }
329
330
331 /**
332  * Send an ICMP message to the target.
333  *
334  * @param my_ip source address
335  * @param other target address
336  */
337 static void
338 send_icmp (const struct in_addr *my_ip,
339            const struct in_addr *other)
340 {
341   struct ip_packet ip_pkt;
342   struct icmp_packet *icmp_pkt;
343   struct icmp_echo_packet icmp_echo;
344   struct sockaddr_in dst;
345   char packet[sizeof (struct ip_packet)*2 + sizeof (struct icmp_packet) + sizeof(struct icmp_echo_packet)];
346
347   size_t off;
348   int err;
349
350   memset(packet, 0, sizeof(packet));
351   /* ip header: send to (known) ip address */
352   off = 0;
353   memset(&ip_pkt, 0, sizeof(ip_pkt));
354   ip_pkt.vers_ihl = 0x45;
355   ip_pkt.tos = 0;
356   ip_pkt.pkt_len = sizeof (packet); /* huh? */
357   ip_pkt.id = 1; 
358   ip_pkt.flags_frag_offset = 0;
359   ip_pkt.ttl = IPDEFTTL;
360   ip_pkt.proto = IPPROTO_ICMP;
361   ip_pkt.checksum = 0; 
362   ip_pkt.src_ip = my_ip->s_addr;
363   ip_pkt.dst_ip = other->s_addr;
364   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));
365
366   memcpy (packet, &ip_pkt, sizeof (struct ip_packet));
367   off += sizeof (ip_pkt);
368   memset (&dst, 0, sizeof (dst));
369   dst.sin_family = AF_INET;
370   dst.sin_addr = *other;
371
372   /* icmp reply: time exceeded */
373   icmp_pkt = (struct icmp_packet*) &packet[off];
374   memset(icmp_pkt, 0, sizeof(struct icmp_packet));
375   icmp_pkt->type = ICMP_TIME_EXCEEDED;
376   icmp_pkt->code = 0; 
377   icmp_pkt->reserved = 0;
378   icmp_pkt->checksum = 0;
379
380   off += sizeof (struct icmp_packet);
381
382   /* ip header of the presumably 'lost' udp packet */
383   ip_pkt.vers_ihl = 0x45;
384   ip_pkt.tos = 0;
385   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
386   ip_pkt.id = 1; 
387   ip_pkt.flags_frag_offset = 0;
388   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
389   ip_pkt.proto = IPPROTO_ICMP;
390   ip_pkt.src_ip = other->s_addr;
391   ip_pkt.dst_ip = dummy.s_addr;
392   ip_pkt.checksum = 0;
393   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));  
394   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_packet));
395   off += sizeof (struct ip_packet);
396
397   icmp_echo.type = ICMP_ECHO;
398   icmp_echo.code = 0;
399   icmp_echo.reserved = 0;
400   icmp_echo.checksum = 0;
401   icmp_echo.data = htons(port);
402   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
403                                            sizeof (struct icmp_echo_packet)));
404
405   memcpy (&packet[off], &icmp_echo, sizeof(struct icmp_echo_packet));
406   off += sizeof (struct icmp_echo_packet);
407
408   icmp_pkt->checksum = htons(calc_checksum((uint16_t*)icmp_pkt,
409                                              sizeof (struct icmp_packet) + sizeof(struct ip_packet) + sizeof(struct icmp_echo_packet)));
410
411   err = sendto(rawsock, 
412                &packet[0],
413                off, 0,
414                (struct sockaddr*)&dst, 
415                sizeof(dst)); /* or sizeof 'struct sockaddr'? */
416
417   if (err < 0) 
418     {
419       fprintf(stderr,
420               "sendto failed: %s\n", strerror(errno));
421     }
422   else if (err != off) 
423     {
424       fprintf(stderr,
425               "Error: partial send of ICMP message\n");
426     }
427 }
428
429
430 /**
431  * Create an ICMP raw socket.
432  *
433  * @return INVALID_SOCKET on error
434  */
435 static SOCKET
436 make_raw_socket ()
437 {
438   DWORD bOptVal = TRUE;
439   int bOptLen = sizeof(bOptVal);
440   SOCKET ret;
441
442   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
443   if (INVALID_SOCKET == ret)
444     {
445       fprintf (stderr,
446                "Error opening RAW socket: %s\n",
447                strerror (errno));
448       return INVALID_SOCKET;
449     }  
450   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen) != 0)
451     {
452       fprintf(stderr, 
453               "Error setting SO_BROADCAST to ON: %s\n",
454               strerror (errno));
455       closesocket(rawsock);
456       return INVALID_SOCKET;
457     }
458
459   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL, (char*)&bOptVal, bOptLen) != 0)
460     {
461       fprintf(stderr, 
462               "Error setting IP_HDRINCL to ON: %s\n",
463               strerror (errno));
464       closesocket(rawsock);
465       return INVALID_SOCKET;
466     }
467   return ret;
468 }
469
470
471 int
472 main (int argc, char *const *argv)
473 {
474   struct in_addr external;
475   struct in_addr target;
476   WSADATA wsaData;
477
478   unsigned int p;
479
480   if (argc != 4)
481     {
482       fprintf (stderr,
483                "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
484       return 1;
485     }
486   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
487        (1 != inet_pton (AF_INET, argv[2], &target)) )
488     {
489       fprintf (stderr,
490                "Error parsing IPv4 address: %s\n",
491                strerror (errno));
492       return 1;
493     }
494   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
495        (p == 0) ||
496        (p > 0xFFFF) )
497     {
498       fprintf (stderr,
499                "Error parsing port value `%s'\n",
500                argv[3]);
501       return 1;
502     }
503   port = (uint16_t) p;
504
505   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
506     {
507       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
508       return 2;
509     }
510   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
511     {
512       fprintf (stderr,
513                "Internal error converting dummy IP to binary.\n");
514       return 2;
515     }
516   if (-1 == (rawsock = make_raw_socket()))
517     return 3;
518   send_icmp (&external,
519              &target);
520   send_icmp_udp (&external,
521                  &target);
522   closesocket (rawsock);
523   WSACleanup ();
524   return 0;
525 }
526
527 /* end of gnunet-nat-client-windows.c */