Only start the hijack if the vpn is running
[oweals/gnunet.git] / src / vpn / gnunet-service-dns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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 vpn/gnunet-service-dns.c
23  * @author Philipp Toelke
24  */
25 #include "platform.h"
26 #include "gnunet_getopt_lib.h"
27 #include "gnunet_service_lib.h"
28 #include "gnunet_network_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet-service-dns-p.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet-vpn-packet.h"
33 #include "gnunet-vpn-pretty-print.h"
34 #include "gnunet_container_lib.h"
35 #include "gnunet-dns-parser.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_block_lib.h"
38 #include "block_dns.h"
39 #include "gnunet_crypto_lib.h"
40 #include "gnunet_signatures.h"
41
42 /**
43  * The scheduler to use throughout the service
44  */
45 static struct GNUNET_SCHEDULER_Handle *sched;
46
47 /**
48  * The UDP-Socket through which DNS-Resolves will be sent if they are not to be
49  * sent through gnunet. The port of this socket will not be hijacked.
50  */
51 static struct GNUNET_NETWORK_Handle *dnsout;
52
53 /**
54  * The port bound to the socket dnsout
55  */
56 static unsigned short dnsoutport;
57
58 /**
59  * A handle to the DHT-Service
60  */
61 static struct GNUNET_DHT_Handle *dht;
62
63 /**
64  * The configuration to use
65  */
66 static const struct GNUNET_CONFIGURATION_Handle *cfg;
67
68 /**
69  * A list of DNS-Responses that have to be sent to the requesting client
70  */
71 static struct answer_packet_list *head;
72
73 /**
74  * The tail of the list of DNS-responses
75  */
76 static struct answer_packet_list *tail;
77
78 /**
79  * A structure containing a mapping from network-byte-ordered DNS-id to
80  * some information needed to handle this query
81  *
82  * It currently allocates at least
83  * (1 + machine-width + 32 + 32 + 16 + machine-width + 8) * 65536 bit
84  * = 1.7 MiB on 64 bit.
85  * = 1.2 MiB on 32 bit.
86  */
87 static struct {
88     unsigned valid:1;
89     struct GNUNET_SERVER_Client* client;
90     unsigned local_ip:32;
91     unsigned remote_ip:32;
92     unsigned local_port:16;
93     char* name;
94     unsigned namelen:8;
95 } query_states[65536];
96
97 /**
98  * A struct used to give more than one value as
99  * closure to receive_dht
100  */
101 struct receive_dht_cls {
102     unsigned short id;
103     struct GNUNET_DHT_GetHandle* handle;
104 };
105
106 /**
107  * Hijack all outgoing DNS-Traffic but for traffic leaving "our" port.
108  */
109 static void
110 hijack(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
111     char port_s[6];
112
113     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Hijacking, port is %d\n", dnsoutport);
114     snprintf(port_s, 6, "%d", dnsoutport);
115     GNUNET_OS_process_close (GNUNET_OS_start_process(NULL,
116                                                      NULL,
117                                                      "gnunet-helper-hijack-dns",
118                                                      "gnunet-hijack-dns",
119                                                      port_s,
120                                                      NULL));
121 }
122
123 /**
124  * Delete the hijacking-routes
125  */
126 static void
127 unhijack(unsigned short port) {
128     char port_s[6];
129
130     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "unHijacking, port is %d\n", port);
131     snprintf(port_s, 6, "%d", port);
132     GNUNET_OS_start_process(NULL,
133                             NULL,
134                             "gnunet-helper-hijack-dns",
135                             "gnunet-hijack-dns",
136                             "-d",
137                             port_s,
138                             NULL);
139 }
140
141 /**
142  * Send the DNS-Response to the client. Gets called via the notify_transmit_ready-
143  * system.
144  */
145 static size_t
146 send_answer(void* cls, size_t size, void* buf) {
147     struct answer_packet_list* query = head;
148     size_t len = ntohs(query->pkt.hdr.size);
149
150     GNUNET_assert(len <= size);
151
152     memcpy(buf, &query->pkt.hdr, len);
153
154     GNUNET_CONTAINER_DLL_remove (head, tail, query);
155
156     GNUNET_free(query);
157
158     /* When more data is to be sent, reschedule */
159     if (head != NULL)
160       GNUNET_SERVER_notify_transmit_ready(cls,
161                                           ntohs(head->pkt.hdr.size),
162                                           GNUNET_TIME_UNIT_FOREVER_REL,
163                                           &send_answer,
164                                           cls);
165
166     return len;
167 }
168
169 /**
170  * Receive a block from the dht.
171  */
172 static void
173 receive_dht(void *cls,
174             struct GNUNET_TIME_Absolute exp,
175             const GNUNET_HashCode *key,
176             const struct GNUNET_PeerIdentity *const *get_path,
177             const struct GNUNET_PeerIdentity *const *put_path,
178             enum GNUNET_BLOCK_Type type,
179             size_t size,
180             const void *data) {
181
182     unsigned short id = ((struct receive_dht_cls*)cls)->id;
183     struct GNUNET_DHT_GetHandle* handle = ((struct receive_dht_cls*)cls)->handle;
184     GNUNET_free(cls);
185
186     GNUNET_assert(type == GNUNET_BLOCK_TYPE_DNS);
187
188     /* If no query with this id is pending, ignore the block */
189     if (query_states[id].valid != GNUNET_YES) return;
190     query_states[id].valid = GNUNET_NO;
191
192     const struct GNUNET_DNS_Record* rec = data;
193     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
194                "Got block of size %d, peer: %08x, desc: %08x\n",
195                size,
196                *((unsigned int*)&rec->peer),
197                *((unsigned int*)&rec->service_descriptor));
198
199     size_t len = sizeof(struct answer_packet) - 1 \
200                  + sizeof(struct dns_static) \
201                  + query_states[id].namelen \
202                  + sizeof(struct dns_query_line) \
203                  + 2 /* To hold the pointer (as defined in RFC1035) to the name */ \
204                  + sizeof(struct dns_record_line) - 1 \
205                  + 16; /* To hold the IPv6-Address */
206
207     struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
208     memset(answer, 0, len + 2*sizeof(struct answer_packet_list*));
209
210     answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
211     answer->pkt.hdr.size = htons(len);
212     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_SERVICE;
213
214     GNUNET_CRYPTO_hash(&rec->peer,
215                        sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
216                        &answer->pkt.peer);
217
218     memcpy(&answer->pkt.service_descriptor,
219            &rec->service_descriptor,
220            sizeof(GNUNET_HashCode));
221     memcpy(&answer->pkt.service_type,
222            &rec->service_type,
223            sizeof(answer->pkt.service_type));
224     memcpy(&answer->pkt.ports, &rec->ports, sizeof(answer->pkt.ports));
225
226     answer->pkt.from = query_states[id].remote_ip;
227
228     answer->pkt.to = query_states[id].local_ip;
229     answer->pkt.dst_port = query_states[id].local_port;
230
231     struct dns_pkt *dpkt = (struct dns_pkt*)answer->pkt.data;
232
233     dpkt->s.id = id;
234     dpkt->s.aa = 1;
235     dpkt->s.qr = 1;
236     dpkt->s.ra = 1;
237     dpkt->s.qdcount = htons(1);
238     dpkt->s.ancount = htons(1);
239
240     memcpy(dpkt->data, query_states[id].name, query_states[id].namelen);
241     GNUNET_free(query_states[id].name);
242
243
244     struct dns_query_line* dque = (struct dns_query_line*)(dpkt->data+(query_states[id].namelen));
245     dque->type = htons(28); /* AAAA */
246     dque->class = htons(1); /* IN */
247
248     char* anname = (char*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line));
249     memcpy(anname, (char[]){0xc0, 0x0c}, 2);
250
251     struct dns_record_line *drec_data = (struct dns_record_line*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line)+2);
252     drec_data->type = htons(28); /* AAAA */
253     drec_data->class = htons(1); /* IN */
254     drec_data->ttl = htonl(3600); /* FIXME: read from block */
255     drec_data->data_len = htons(16);
256
257     /* Calculate at which offset in the packet the IPv6-Address belongs, it is
258      * filled in by the daemon-vpn */
259     answer->pkt.addroffset = htons((unsigned short)((unsigned long)(&drec_data->data)-(unsigned long)(&answer->pkt)));
260
261     GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
262
263     GNUNET_SERVER_notify_transmit_ready(query_states[id].client,
264                                         len,
265                                         GNUNET_TIME_UNIT_FOREVER_REL,
266                                         &send_answer,
267                                         query_states[id].client);
268
269     GNUNET_DHT_get_stop(handle);
270 }
271
272 /**
273  * This receives a GNUNET_MESSAGE_TYPE_REHIJACK and rehijacks the DNS
274  */
275 static void
276 rehijack(void *cls,
277          struct GNUNET_SERVER_Client *client,
278          const struct GNUNET_MessageHeader *message) {
279     unhijack(dnsoutport);
280     GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
281
282     GNUNET_SERVER_receive_done(client, GNUNET_OK);
283 }
284
285 /**
286  * This receives the dns-payload from the daemon-vpn and sends it on over the udp-socket
287  */
288 static void
289 receive_query(void *cls,
290               struct GNUNET_SERVER_Client *client,
291               const struct GNUNET_MessageHeader *message) {
292     struct query_packet* pkt = (struct query_packet*)message;
293     struct dns_pkt* dns = (struct dns_pkt*)pkt->data;
294     struct dns_pkt_parsed* pdns = parse_dns_packet(dns);
295
296     query_states[dns->s.id].valid = GNUNET_YES;
297     query_states[dns->s.id].client = client;
298     query_states[dns->s.id].local_ip = pkt->orig_from;
299     query_states[dns->s.id].local_port = pkt->src_port;
300     query_states[dns->s.id].remote_ip = pkt->orig_to;
301     query_states[dns->s.id].namelen = strlen((char*)dns->data) + 1;
302     query_states[dns->s.id].name = GNUNET_malloc(query_states[dns->s.id].namelen);
303     memcpy(query_states[dns->s.id].name, dns->data, query_states[dns->s.id].namelen);
304
305     if (pdns->queries[0]->namelen > 9 &&
306         0 == strncmp(pdns->queries[0]->name+(pdns->queries[0]->namelen - 9), ".gnunet.", 9))
307       {
308         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Query for .gnunet!\n");
309         GNUNET_HashCode key;
310         GNUNET_CRYPTO_hash(pdns->queries[0]->name, pdns->queries[0]->namelen, &key);
311
312         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
313                    "Getting with key %08x, len is %d\n",
314                    *((unsigned int*)&key),
315                    pdns->queries[0]->namelen);
316
317         struct receive_dht_cls* cls = GNUNET_malloc(sizeof(struct receive_dht_cls));
318         cls->id = dns->s.id;
319
320         cls->handle = GNUNET_DHT_get_start(dht,
321                                            GNUNET_TIME_UNIT_MINUTES,
322                                            GNUNET_BLOCK_TYPE_DNS,
323                                            &key,
324                                            GNUNET_DHT_RO_NONE,
325                                            NULL,
326                                            0,
327                                            NULL,
328                                            0,
329                                            receive_dht,
330                                            cls);
331
332         goto out;
333       }
334
335     /* The query should be sent to the network */
336
337     struct sockaddr_in dest;
338     memset(&dest, 0, sizeof dest);
339     dest.sin_port = htons(53);
340     dest.sin_addr.s_addr = pkt->orig_to;
341
342     GNUNET_NETWORK_socket_sendto(dnsout,
343                                  dns,
344                                  ntohs(pkt->hdr.size) - sizeof(struct query_packet) + 1,
345                                  (struct sockaddr*) &dest,
346                                  sizeof dest);
347
348 out:
349     free_parsed_dns_packet(pdns);
350     pdns = NULL;
351     GNUNET_SERVER_receive_done(client, GNUNET_OK);
352 }
353
354 /**
355  * Read a response-packet of the UDP-Socket
356  */
357 static void
358 read_response (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
359     unsigned char buf[65536];
360     struct dns_pkt* dns = (struct dns_pkt*)buf;
361
362     if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
363       return;
364
365     struct sockaddr_in addr;
366     memset(&addr, 0, sizeof addr);
367     unsigned int addrlen = sizeof addr;
368
369     int r;
370     r = GNUNET_NETWORK_socket_recvfrom(dnsout,
371                                        buf,
372                                        65536,
373                                        (struct sockaddr*)&addr,
374                                        &addrlen);
375
376     /* if (r < 0) FIXME */
377
378     if (query_states[dns->s.id].valid == GNUNET_YES) {
379         query_states[dns->s.id].valid = GNUNET_NO;
380
381         size_t len = sizeof(struct answer_packet) + r - 1; /* 1 for the unsigned char data[1]; */
382         struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
383         answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
384         answer->pkt.hdr.size = htons(len);
385         answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_IP;
386         answer->pkt.from = addr.sin_addr.s_addr;
387         answer->pkt.to = query_states[dns->s.id].local_ip;
388         answer->pkt.dst_port = query_states[dns->s.id].local_port;
389         memcpy(answer->pkt.data, buf, r);
390
391         GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
392
393         GNUNET_SERVER_notify_transmit_ready(query_states[dns->s.id].client,
394                                             len,
395                                             GNUNET_TIME_UNIT_FOREVER_REL,
396                                             &send_answer,
397                                             query_states[dns->s.id].client);
398     }
399
400     GNUNET_SCHEDULER_add_read_net(sched,
401                                   GNUNET_TIME_UNIT_FOREVER_REL,
402                                   dnsout,
403                                   &read_response,
404                                   NULL);
405 }
406
407
408 /**
409  * Task run during shutdown.
410  *
411  * @param cls unused
412  * @param tc unused
413  */
414 static void
415 cleanup_task (void *cls,
416               const struct GNUNET_SCHEDULER_TaskContext *tc)
417 {
418   unhijack(dnsoutport);
419   GNUNET_DHT_disconnect(dht);
420 }
421
422 /**
423  * Publish a DNS-record in the DHT. This is up to now just for testing.
424  */
425 static void
426 publish_name (void *cls,
427               const struct GNUNET_SCHEDULER_TaskContext *tc) {
428     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
429       return;
430
431     char* name = "philipptoelke.gnunet.";
432     size_t size = sizeof(struct GNUNET_DNS_Record);
433     struct GNUNET_DNS_Record data;
434     memset(&data, 0, size);
435
436     data.purpose.size = htonl(size - sizeof(struct GNUNET_CRYPTO_RsaSignature));
437     data.purpose.purpose = GNUNET_SIGNATURE_PURPOSE_DNS_RECORD;
438
439     GNUNET_CRYPTO_hash(name, strlen(name)+1, &data.service_descriptor);
440
441     char* keyfile;
442     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, "GNUNETD",
443                                                              "HOSTKEY", &keyfile))
444       {
445         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "could not read keyfile-value\n");
446         if (keyfile != NULL) GNUNET_free(keyfile);
447         return;
448       }
449
450     struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file(keyfile);
451     GNUNET_free(keyfile);
452
453     GNUNET_CRYPTO_rsa_key_get_public(my_private_key, &data.peer);
454
455     data.expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS);
456
457   /* Sign the block */
458     if (GNUNET_OK != GNUNET_CRYPTO_rsa_sign(my_private_key,
459                                             &data.purpose,
460                                             &data.signature))
461       {
462         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "could not sign DNS_Record\n");
463         return;
464       }
465     GNUNET_CRYPTO_rsa_key_free(my_private_key);
466
467     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
468                "Putting with key %08x\n",
469                *((unsigned int*)&data.service_descriptor));
470
471     GNUNET_DHT_put(dht,
472                    &data.service_descriptor,
473                    GNUNET_DHT_RO_NONE,
474                    GNUNET_BLOCK_TYPE_DNS,
475                    size,
476                    (char*)&data,
477                    GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS),
478                    GNUNET_TIME_UNIT_MINUTES,
479                    NULL,
480                    NULL);
481
482     GNUNET_SCHEDULER_add_delayed (sched,
483                                   GNUNET_TIME_UNIT_HOURS,
484                                   publish_name,
485                                   NULL);
486 }
487
488 /**
489  * @param cls closure
490  * @param sched scheduler to use
491  * @param server the initialized server
492  * @param cfg configuration to use
493  */
494 static void
495 run (void *cls,
496      struct GNUNET_SCHEDULER_Handle *sched_,
497      struct GNUNET_SERVER_Handle *server,
498      const struct GNUNET_CONFIGURATION_Handle *cfg_)
499 {
500   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
501       /* callback, cls, type, size */
502         {&receive_query, NULL, GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS, 0},
503         {&rehijack, NULL, GNUNET_MESSAGE_TYPE_REHIJACK, sizeof(struct GNUNET_MessageHeader)},
504         {NULL, NULL, 0, 0}
505   };
506
507   cfg = cfg_;
508   sched = sched_;
509
510   unsigned int i;
511   for (i = 0; i < 65536; i++) {
512       query_states[i].valid = GNUNET_NO;
513   }
514
515   dht = GNUNET_DHT_connect(sched, cfg, 1024);
516
517   struct sockaddr_in addr;
518
519   dnsout = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
520   if (dnsout == NULL)
521     return;
522   memset(&addr, 0, sizeof(struct sockaddr_in));
523
524   int err = GNUNET_NETWORK_socket_bind (dnsout,
525                                         (struct sockaddr*)&addr,
526                                         sizeof(struct sockaddr_in));
527
528   if (err != GNUNET_YES) {
529       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not bind a port, exiting\n");
530       return;
531   }
532
533   /* Read the port we bound to */
534   socklen_t addrlen = sizeof(struct sockaddr_in);
535   err = getsockname(GNUNET_NETWORK_get_fd(dnsout),
536                     (struct sockaddr*) &addr,
537                     &addrlen);
538
539   dnsoutport = htons(addr.sin_port);
540
541   GNUNET_SCHEDULER_add_now (sched, publish_name, NULL);
542
543   GNUNET_SCHEDULER_add_read_net(sched, GNUNET_TIME_UNIT_FOREVER_REL, dnsout, &read_response, NULL);
544
545   GNUNET_SERVER_add_handlers (server, handlers);
546   GNUNET_SCHEDULER_add_delayed (sched,
547                                 GNUNET_TIME_UNIT_FOREVER_REL,
548                                 &cleanup_task,
549                                 cls);
550 }
551
552 /**
553  * The main function for the dns service.
554  *
555  * @param argc number of arguments from the command line
556  * @param argv command line arguments
557  * @return 0 ok, 1 on error
558  */
559 int
560 main (int argc, char *const *argv)
561 {
562   return (GNUNET_OK ==
563           GNUNET_SERVICE_run (argc,
564                               argv,
565                               "dns",
566                               GNUNET_SERVICE_OPTION_NONE,
567                               &run, NULL)) ? 0 : 1;
568 }