- debug info
[oweals/gnunet.git] / src / nat / nat_stun.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2015 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * 
23  * This code provides some support for doing STUN transactions.
24  * We send simplest possible packet ia REQUEST with BIND to a STUN server.
25  *
26  * All STUN packets start with a simple header made of a type,
27  * length (excluding the header) and a 16-byte random transaction id.
28  * Following the header we may have zero or more attributes, each
29  * structured as a type, length and a value (whose format depends
30  * on the type, but often contains addresses).
31  * Of course all fields are in network format.
32  * 
33  * This code was based on ministun.c.
34  *
35  *
36  * @file nat/nat_stun.c
37  * @brief Functions for STUN functionality
38  * @author Bruno Souza Cabral
39  */
40
41 #include "platform.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet_resolver_service.h"
44 #include "gnunet_nat_lib.h"
45
46
47 #include "nat_stun.h"
48
49 #define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)
50
51
52
53 /**
54  * Handle to a request given to the resolver.  Can be used to cancel
55  * the request prior to the timeout or successful execution.  Also
56  * used to track our internal state for the request.
57  */
58 struct GNUNET_NAT_StunRequestHandle {
59
60      /**
61      * Handle to a pending DNS lookup request.
62      */
63      struct GNUNET_RESOLVER_RequestHandle *dns_active;
64
65
66      /**
67      * Handle to the listen socket
68      */
69      struct GNUNET_NETWORK_Handle * sock;
70
71      /**
72      * Stun server address
73      */
74      char *stun_server ;
75
76      /**
77      * STUN port
78      */
79      int stun_port;
80
81 };
82
83
84
85 /* here we store credentials extracted from a message */
86 struct StunState {
87      uint16_t attr;
88 };
89
90
91 /**
92  * Convert a message to a StunClass
93  *
94  * @param msg the received message
95  * @return the converted StunClass
96  */
97 static int decode_class(int msg)
98 {
99      return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);
100 }
101
102 /**
103  * Convert a message to a StunMethod
104  *
105  * @param msg the received message
106  * @return the converted StunMethod
107  */
108 static int decode_method(int msg)
109 {
110      return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);
111 }
112
113 /**
114  * Encode a class and method to a compatible STUN format
115  *
116  * @param msg_class class to be converted
117  * @param method method to be converted
118  * @return message in a STUN compatible format
119  */
120 static int encode_message(StunClasses msg_class, StunMethods method)
121 {
122      return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
123             (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
124 }
125
126 /**
127  * Print a class and method from a STUN message
128  *
129  * @param msg
130  * @return string with the message class and method
131  */
132 static const char *stun_msg2str(int msg)
133 {
134
135      const struct { enum StunClasses value; const char *name; } classes[] = {
136              { STUN_REQUEST, "Request" },
137              { STUN_INDICATION, "Indication" },
138              { STUN_RESPONSE, "Response" },
139              { STUN_ERROR_RESPONSE, "Error Response" },
140              { 0, NULL }
141      };
142
143      const struct { enum StunMethods value; const char *name; } methods[] = {
144              { STUN_BINDING, "Binding" },
145              { 0, NULL }
146      };
147
148      static char result[32];
149      const char *msg_class = NULL;
150      const char *method = NULL;
151      int i;
152      int value;
153
154      value = decode_class(msg);
155      for (i = 0; classes[i].name; i++) {
156           msg_class = classes[i].name;
157           if (classes[i].value == value)
158                break;
159      }
160      value = decode_method(msg);
161      for (i = 0; methods[i].name; i++) {
162           method = methods[i].name;
163           if (methods[i].value == value)
164                break;
165      }
166      snprintf(result, sizeof(result), "%s %s",
167               method ? : "Unknown Method",
168               msg_class ? : "Unknown Class Message");
169      return result;
170 }
171
172 /**
173  * Print attribute name
174  *
175  * @param msg with a attribute type
176  * @return string with the attribute name
177  */
178 static const char *stun_attr2str(int msg)
179 {
180      const struct { enum StunAttributes value; const char *name; } attrs[] = {
181              { STUN_MAPPED_ADDRESS, "Mapped Address" },
182              { STUN_RESPONSE_ADDRESS, "Response Address" },
183              { STUN_CHANGE_ADDRESS, "Change Address" },
184              { STUN_SOURCE_ADDRESS, "Source Address" },
185              { STUN_CHANGED_ADDRESS, "Changed Address" },
186              { STUN_USERNAME, "Username" },
187              { STUN_PASSWORD, "Password" },
188              { STUN_MESSAGE_INTEGRITY, "Message Integrity" },
189              { STUN_ERROR_CODE, "Error Code" },
190              { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },
191              { STUN_REFLECTED_FROM, "Reflected From" },
192              { STUN_REALM, "Realm" },
193              { STUN_NONCE, "Nonce" },
194              { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },
195              { STUN_MS_VERSION, "MS Version" },
196              { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },
197              { STUN_SOFTWARE, "Software" },
198              { STUN_ALTERNATE_SERVER, "Alternate Server" },
199              { STUN_FINGERPRINT, "Fingerprint" },
200              { 0, NULL }
201      };
202      int i;
203
204      for (i = 0; attrs[i].name; i++) {
205           if (attrs[i].value == msg)
206                return attrs[i].name;
207      }
208      return "Unknown Attribute";
209 }
210
211
212 /**
213  * Fill the stun_header with a random request_id
214  *
215  * @param state, STUN attribute type
216  * @param attr , the actual attribute
217  *
218  * @param req, stun header to be filled
219  */
220 static int stun_process_attr(struct StunState *state, struct stun_attr *attr)
221 {
222      LOG (GNUNET_ERROR_TYPE_INFO,
223           "Found STUN Attribute %s (%04x), length %d\n",
224           stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
225
226      switch (ntohs(attr->attr)) {
227           case STUN_MAPPED_ADDRESS:
228           case STUN_XOR_MAPPED_ADDRESS:
229           case STUN_MS_XOR_MAPPED_ADDRESS:
230                break;
231           default:
232                LOG (GNUNET_ERROR_TYPE_INFO,
233                     "Ignoring STUN Attribute %s (%04x), length %d\n",
234                     stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
235
236      }
237      return 0;
238 }
239
240
241
242 /**
243  * Fill the stun_header with a random request_id
244  *
245  * @param req, stun header to be filled
246  */
247 static void
248 generate_request_id(struct stun_header *req)
249 {
250      int x;
251      req->magic = htonl(STUN_MAGIC_COOKIE);
252      for (x = 0; x < 3; x++)
253           req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
254                                                     UINT32_MAX);
255 }
256
257
258 /**
259  * Extract the STUN_MAPPED_ADDRESS from the stun response.
260  * This is used as a callback for stun_handle_response
261  * when called from stun_request.
262  *
263  * @param st, pointer where we will set the type
264  * @param attr , received stun attribute
265  * @param arg , pointer to a sockaddr_in where we will set the reported IP and port
266  * @param magic , Magic cookie
267  *
268  * @return 0 on sucess, other value otherwise
269  */
270 static int
271 stun_get_mapped(struct StunState *st, struct stun_attr *attr,struct sockaddr_in *arg, unsigned int magic)
272 {
273     struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
274     struct sockaddr_in *sa = (struct sockaddr_in *)arg;
275     unsigned short type = ntohs(attr->attr);
276
277     switch (type) {
278         case STUN_MAPPED_ADDRESS:
279             if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
280                 st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
281                 return 1;
282             magic = 0;
283             break;
284         case STUN_MS_XOR_MAPPED_ADDRESS:
285             if (st->attr == STUN_XOR_MAPPED_ADDRESS)
286                 return 1;
287             break;
288         case STUN_XOR_MAPPED_ADDRESS:
289             break;
290         default:
291             return 1;
292     }
293     if (ntohs(attr->len) < 8 && returned_addr->family != 1) {
294         return 1;
295     }
296
297     st->attr = type;
298     sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
299     sa->sin_addr.s_addr = returned_addr->addr ^ magic;
300     return 0;
301 }
302
303
304 /**
305  * Handle an incoming STUN message, Do some basic sanity checks on packet size and content,
306  * try to extract a bit of information, and possibly reply.
307  * At the moment this only processes BIND requests, and returns
308  * the externally visible address of the request.
309  * If a callback is specified, invoke it with the attribute.
310  *
311  * @param data, the packet
312  * @param len, the length of the packet
313  * @param arg, sockaddr_in where we will set our discovered packet
314  *
315  * @return, 0 on OK, -1 if the packet is invalid ( not a stun packet)
316  */
317 int
318 GNUNET_NAT_stun_handle_packet(const uint8_t *data, size_t len,struct sockaddr_in *arg)
319 {
320      struct stun_header *hdr = (struct stun_header *)data;
321      struct stun_attr *attr;
322      struct StunState st;
323      int ret = STUN_IGNORE;
324
325      uint32_t advertised_message_size;
326      uint32_t message_magic_cookie;
327
328
329      /* On entry, 'len' is the length of the udp payload. After the
330           * initial checks it becomes the size of unprocessed options,
331           * while 'data' is advanced accordingly.
332           */
333      if (len < sizeof(struct stun_header)) {
334           LOG (GNUNET_ERROR_TYPE_INFO,
335                "STUN packet too short (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
336           GNUNET_break_op (0);
337           return -1;
338      }
339      /* Skip header as it is already in hdr */
340      len -= sizeof(struct stun_header);
341      data += sizeof(struct stun_header);
342
343      /* len as advertised in the message */
344      advertised_message_size = ntohs(hdr->msglen);
345
346      message_magic_cookie = ntohl(hdr->magic);
347      /* Compare if the cookie match */
348      if(STUN_MAGIC_COOKIE != message_magic_cookie){
349           LOG (GNUNET_ERROR_TYPE_INFO,
350                "Invalid magic cookie \n");
351           GNUNET_break_op (0);
352           return -1;
353      }
354
355
356      LOG (GNUNET_ERROR_TYPE_INFO, "STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), advertised_message_size);
357
358
359      if (advertised_message_size > len) {
360           LOG (GNUNET_ERROR_TYPE_INFO, "Scrambled STUN packet length (got %d, expecting %d)\n", advertised_message_size, (int)len);
361           GNUNET_break_op (0);
362          return -1;
363      } else {
364           len = advertised_message_size;
365      }
366      /* Zero the struct */
367      memset(&st,0, sizeof(st));
368
369      while (len > 0) {
370           if (len < sizeof(struct stun_attr)) {
371                LOG (GNUNET_ERROR_TYPE_INFO, "Attribute too short (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
372                GNUNET_break_op (0);
373                break;
374           }
375           attr = (struct stun_attr *)data;
376
377           /* compute total attribute length */
378           advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
379
380           /* Check if we still have space in our buffer */
381           if (advertised_message_size > len ) {
382                LOG (GNUNET_ERROR_TYPE_INFO, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", advertised_message_size, (int)len);
383                GNUNET_break_op (0);
384                break;
385           }
386
387
388          stun_get_mapped(&st, attr, arg, hdr->magic);
389
390           if (stun_process_attr(&st, attr)) {
391                LOG (GNUNET_ERROR_TYPE_INFO, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
392                break;
393           }
394           /* Clear attribute id: in case previous entry was a string,
395                    * this will act as the terminator for the string.
396                    */
397           attr->attr = 0;
398           data += advertised_message_size;
399           len -= advertised_message_size;
400      }
401
402      return ret;
403 }
404
405
406
407 /**
408  * Try to establish a connection given the specified address.
409  *
410  * @param cls our `struct GNUNET_NAT_StunRequestHandle *`
411  * @param addr address to try, NULL for "last call"
412  * @param addrlen length of @a addr
413  */
414 static void
415 stun_dns_callback (void *cls,
416                            const struct sockaddr *addr,
417                            socklen_t addrlen) {
418
419
420      struct GNUNET_NAT_StunRequestHandle *request = cls;
421
422      struct stun_header *req;
423      uint8_t reqdata[1024];
424      int reqlen;
425      struct sockaddr_in server;
426
427      if(NULL == request) {
428           LOG (GNUNET_ERROR_TYPE_INFO, "Empty request\n");
429           /* FIXME clean up ? */
430           return;
431      }
432
433      if (NULL == addr) {
434           request->dns_active = NULL;
435           LOG (GNUNET_ERROR_TYPE_INFO, "Error resolving host %s\n", request->stun_server);
436           /* FIXME clean up? */
437           return;
438      }
439
440
441      memset(&server,0, sizeof(server));
442      server.sin_family = AF_INET;
443      server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
444      server.sin_port = htons(request->stun_port);
445
446
447      /*Craft the simplest possible STUN packet. A request binding*/
448      req = (struct stun_header *)reqdata;
449      generate_request_id(req);
450      reqlen = 0;
451      req->msgtype = 0;
452      req->msglen = 0;
453      req->msglen = htons(reqlen);
454      req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));
455
456      /* Send the packet */
457      if (-1 == GNUNET_NETWORK_socket_sendto (request->sock, req, ntohs(req->msglen) + sizeof(*req),
458                                              (const struct sockaddr *) &server, sizeof (server)))
459      {
460           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Fail to sendto");
461      }
462
463 }
464
465
466 /**
467  * Make Generic STUN request and
468  * Send a generic stun request to the server specified using the specified socket.
469  * possibly waiting for a reply and filling the 'reply' field with
470  * the externally visible address.
471  *c
472  * @param server, the address of the stun server
473  * @param port, port of the stun server
474  * @param sock the socket used to send the request
475  * @return GNUNET_NAT_StunRequestHandle on success, NULL on error.
476  */
477 struct GNUNET_NAT_StunRequestHandle *
478 GNUNET_NAT_stun_make_request(char * server, int port, struct GNUNET_NETWORK_Handle * sock)
479 {
480
481      struct GNUNET_NAT_StunRequestHandle *rh;
482
483      rh = GNUNET_malloc (sizeof (struct GNUNET_NAT_StunRequestHandle));
484      rh->sock = sock;
485
486      char * server_copy = GNUNET_malloc (1 + strlen (server));
487      if (server_copy) {
488         strcpy (server_copy, server);
489      }else{
490          GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Failed to allocate string");
491          /* FIXME: cleanup rh? */
492          return NULL;
493      }
494
495      rh->stun_server = server_copy;
496      rh->stun_port = port;
497      rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server, AF_INET,
498                                               GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
499                                               &stun_dns_callback, rh);
500      /* FIXME: error handling NULL==dns_active, callback function? */
501
502      return rh;
503 }