d7b4929b2c972634fa8e3cc3ace2a4960e0a516d
[oweals/gnunet.git] / src / transport / gnunet-service-transport_validation.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011 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 transport/gnunet-service-transport_validation.c
23  * @brief address validation subsystem
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-transport_validation.h"
28 #include "gnunet-service-transport_plugins.h"
29 #include "gnunet-service-transport_hello.h"
30 #include "gnunet-service-transport_blacklist.h"
31 #include "gnunet-service-transport.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_ats_service.h"
34 #include "gnunet_peerinfo_service.h"
35 #include "gnunet_signatures.h"
36
37 // TODO: observe latency between PING/PONG and give information to ATS!
38
39 /**
40  * How long is a PONG signature valid?  We'll recycle a signature until
41  * 1/4 of this time is remaining.  PONGs should expire so that if our
42  * external addresses change an adversary cannot replay them indefinitely.
43  * OTOH, we don't want to spend too much time generating PONG signatures,
44  * so they must have some lifetime to reduce our CPU usage.
45  */
46 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
47
48 /**
49  * After how long do we expire an address in a HELLO that we just
50  * validated?  This value is also used for our own addresses when we
51  * create a HELLO.
52  */
53 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
54
55 /**
56  * How long before an existing address expires should we again try to
57  * validate it?  Must be (significantly) smaller than
58  * HELLO_ADDRESS_EXPIRATION.
59  */
60 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
61
62 /**
63  * Size of the validation map hashmap.
64  */
65 #define VALIDATION_MAP_SIZE 256
66
67 /**
68  * Priority to use for PINGs
69  */
70 #define PING_PRIORITY 2
71
72 /**
73  * Priority to use for PONGs
74  */
75 #define PONG_PRIORITY 4
76
77
78 /**
79  * Message used to ask a peer to validate receipt (to check an address
80  * from a HELLO).  Followed by the address we are trying to validate,
81  * or an empty address if we are just sending a PING to confirm that a
82  * connection which the receiver (of the PING) initiated is still valid.
83  */
84 struct TransportPingMessage
85 {
86
87   /**
88    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
89    */
90   struct GNUNET_MessageHeader header;
91
92   /**
93    * Challenge code (to ensure fresh reply).
94    */
95   uint32_t challenge GNUNET_PACKED;
96
97   /**
98    * Who is the intended recipient?
99    */
100   struct GNUNET_PeerIdentity target;
101
102 };
103
104
105 /**
106  * Message used to validate a HELLO.  The challenge is included in the
107  * confirmation to make matching of replies to requests possible.  The
108  * signature signs our public key, an expiration time and our address.<p>
109  *
110  * This message is followed by our transport address that the PING tried
111  * to confirm (if we liked it).  The address can be empty (zero bytes)
112  * if the PING had not address either (and we received the request via
113  * a connection that we initiated).
114  */
115 struct TransportPongMessage
116 {
117
118   /**
119    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
120    */
121   struct GNUNET_MessageHeader header;
122
123   /**
124    * Challenge code from PING (showing freshness).  Not part of what
125    * is signed so that we can re-use signatures.
126    */
127   uint32_t challenge GNUNET_PACKED;
128
129   /**
130    * Signature.
131    */
132   struct GNUNET_CRYPTO_RsaSignature signature;
133
134   /**
135    * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
136    * plausible address for the signing peer.
137    */
138   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
139
140   /**
141    * When does this signature expire?
142    */
143   struct GNUNET_TIME_AbsoluteNBO expiration;
144
145   /**
146    * Size of address appended to this message (part of what is
147    * being signed, hence not redundant).
148    */
149   uint32_t addrlen GNUNET_PACKED;
150
151 };
152
153
154 /**
155  * Information about an address under validation
156  */
157 struct ValidationEntry
158 {
159
160   /**
161    * Name of the transport.
162    */
163   char *transport_name;
164
165   /**
166    * The address, actually a pointer to the end
167    * of this struct.  Do not free!
168    */
169   const void *addr;
170
171   /**
172    * Handle to the blacklist check (if we're currently in it).
173    */
174   struct GST_BlacklistCheck *bc;
175
176   /**
177    * Public key of the peer.
178    */
179   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
180
181   /**
182    * The identity of the peer.
183    */
184   struct GNUNET_PeerIdentity pid;
185
186   /**
187    * ID of task that will clean up this entry if nothing happens.
188    */
189   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
190
191   /**
192    * At what time did we send the latest validation request?
193    */
194   struct GNUNET_TIME_Absolute send_time;
195
196   /**
197    * Until when is this address valid?
198    * ZERO if it is not currently considered valid.
199    */
200   struct GNUNET_TIME_Absolute valid_until;
201
202   /**
203    * How long until we can try to validate this address again?
204    * FOREVER if the address is for an unsupported plugin (from PEERINFO)
205    * ZERO if the address is considered valid (no validation needed)
206    * otherwise a time in the future if we're currently denying re-validation
207    */
208   struct GNUNET_TIME_Absolute validation_block;
209
210   /**
211    * Challenge number we used.
212    */
213   uint32_t challenge;
214
215   /**
216    * Length of addr.
217    */
218   size_t addrlen;
219
220   /**
221    * When passing the address in 'add_valid_peer_address', did we
222    * copy the address to the HELLO yet?
223    */
224   int copied;
225
226 };
227
228
229 /**
230  * Context of currently active requests to peerinfo
231  * for validation of HELLOs.
232  */
233 struct CheckHelloValidatedContext
234 {
235
236   /**
237    * This is a doubly-linked list.
238    */
239   struct CheckHelloValidatedContext *next;
240
241   /**
242    * This is a doubly-linked list.
243    */
244   struct CheckHelloValidatedContext *prev;
245
246   /**
247    * Hello that we are validating.
248    */
249   const struct GNUNET_HELLO_Message *hello;
250
251 };
252
253
254 /**
255  * Head of linked list of HELLOs awaiting validation.
256  */
257 static struct CheckHelloValidatedContext *chvc_head;
258
259 /**
260  * Tail of linked list of HELLOs awaiting validation
261  */
262 static struct CheckHelloValidatedContext *chvc_tail;
263
264 /**
265  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
266  * of the given peer that we are currently validating, have validated
267  * or are blocked from re-validation for a while).
268  */
269 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
270
271 /**
272  * Context for peerinfo iteration.
273  */
274 static struct GNUNET_PEERINFO_NotifyContext *pnc;
275
276
277 /**
278  * Context for the validation entry match function.
279  */
280 struct ValidationEntryMatchContext
281 {
282   /**
283    * Where to store the result?
284    */
285   struct ValidationEntry *ve;
286
287   /**
288    * Transport name we're looking for.
289    */
290   const char *transport_name;
291
292   /**
293    * Address we're interested in.
294    */
295   const char *addr;
296
297   /**
298    * Number of bytes in 'addr'.
299    */
300   size_t addrlen;
301 };
302
303
304 /**
305  * Iterate over validation entries until a matching one is found.
306  *
307  * @param cls the 'struct ValidationEntryMatchContext'
308  * @param key peer identity (unused)
309  * @param value a 'struct ValidationEntry' to match
310  * @return GNUNET_YES if the entry does not match,
311  *         GNUNET_NO if the entry does match
312  */
313 static int
314 validation_entry_match (void *cls, const GNUNET_HashCode * key, void *value)
315 {
316   struct ValidationEntryMatchContext *vemc = cls;
317   struct ValidationEntry *ve = value;
318
319   if ((ve->addrlen == vemc->addrlen) &&
320       (0 == memcmp (ve->addr, vemc->addr, ve->addrlen)) &&
321       (0 == strcmp (ve->transport_name, vemc->transport_name)))
322   {
323     vemc->ve = ve;
324     return GNUNET_NO;
325   }
326   return GNUNET_YES;
327 }
328
329
330 /**
331  * Find a ValidationEntry entry for the given neighbour that matches
332  * the given address and transport.  If none exists, create one (but
333  * without starting any validation).
334  *
335  * @param public_key public key of the peer, NULL for unknown
336  * @param neighbour which peer we care about
337  * @param tname name of the transport plugin
338  * @param addr binary address
339  * @param addrlen length of addr
340  * @return validation entry matching the given specifications, NULL
341  *         if we don't have an existing entry and no public key was given
342  */
343 static struct ValidationEntry *
344 find_validation_entry (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
345                        *public_key, const struct GNUNET_PeerIdentity *neighbour,
346                        const char *tname, const char *addr, size_t addrlen)
347 {
348   struct ValidationEntryMatchContext vemc;
349   struct ValidationEntry *ve;
350
351   vemc.ve = NULL;
352   vemc.transport_name = tname;
353   vemc.addr = addr;
354   vemc.addrlen = addrlen;
355   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
356                                               &neighbour->hashPubKey,
357                                               &validation_entry_match, &vemc);
358   if (NULL != (ve = vemc.ve))
359     return ve;
360   if (public_key == NULL)
361     return NULL;
362   ve = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
363   ve->transport_name = GNUNET_strdup (tname);
364   ve->addr = (void *) &ve[1];
365   ve->public_key = *public_key;
366   ve->pid = *neighbour;
367   ve->challenge =
368       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
369   memcpy (&ve[1], addr, addrlen);
370   ve->addrlen = addrlen;
371   GNUNET_CONTAINER_multihashmap_put (validation_map, &neighbour->hashPubKey, ve,
372                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
373   return ve;
374 }
375
376
377 /**
378  * Iterator which adds the given address to the set of validated
379  * addresses.
380  *
381  * @param cls original HELLO message
382  * @param tname name of the transport
383  * @param expiration expiration time
384  * @param addr the address
385  * @param addrlen length of the address
386  * @return GNUNET_OK (keep the address)
387  */
388 static int
389 add_valid_address (void *cls, const char *tname,
390                    struct GNUNET_TIME_Absolute expiration, const void *addr,
391                    uint16_t addrlen)
392 {
393   const struct GNUNET_HELLO_Message *hello = cls;
394   struct ValidationEntry *ve;
395   struct GNUNET_PeerIdentity pid;
396   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
397
398   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
399     return GNUNET_OK;           /* expired */
400   if ((GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) ||
401       (GNUNET_OK != GNUNET_HELLO_get_key (hello, &public_key)))
402   {
403     GNUNET_break (0);
404     return GNUNET_OK;           /* invalid HELLO !? */
405   }
406   ve = find_validation_entry (&public_key, &pid, tname, addr, addrlen);
407   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until, expiration);
408   GNUNET_ATS_address_update (GST_ats, &pid, tname, addr, addrlen, NULL, NULL,
409                              0);
410   return GNUNET_OK;
411 }
412
413
414 /**
415  * Function called for any HELLO known to PEERINFO.
416  *
417  * @param cls unused
418  * @param peer id of the peer, NULL for last call
419  * @param hello hello message for the peer (can be NULL)
420  * @param err_msg error message
421  */
422 static void
423 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
424                         const struct GNUNET_HELLO_Message *hello,
425                         const char *err_msg)
426 {
427   GNUNET_assert (NULL != peer);
428   if (NULL == hello)
429     return;
430   GNUNET_assert (NULL ==
431                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
432                                                  &add_valid_address,
433                                                  (void *) hello));
434 }
435
436
437 /**
438  * Start the validation subsystem.
439  */
440 void
441 GST_validation_start ()
442 {
443   validation_map = GNUNET_CONTAINER_multihashmap_create (VALIDATION_MAP_SIZE);
444   pnc = GNUNET_PEERINFO_notify (GST_cfg, &process_peerinfo_hello, NULL);
445 }
446
447
448 /**
449  * Iterate over validation entries and free them.
450  *
451  * @param cls (unused)
452  * @param key peer identity (unused)
453  * @param value a 'struct ValidationEntry' to clean up
454  * @return GNUNET_YES (continue to iterate)
455  */
456 static int
457 cleanup_validation_entry (void *cls, const GNUNET_HashCode * key, void *value)
458 {
459   struct ValidationEntry *ve = value;
460
461   if (NULL != ve->bc)
462   {
463     GST_blacklist_test_cancel (ve->bc);
464     ve->bc = NULL;
465   }
466   GNUNET_break (GNUNET_OK ==
467                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
468                                                       &ve->pid.hashPubKey, ve));
469   GNUNET_free (ve->transport_name);
470   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
471   {
472     GNUNET_SCHEDULER_cancel (ve->timeout_task);
473     ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
474   }
475   GNUNET_free (ve);
476   return GNUNET_OK;
477 }
478
479
480 /**
481  * Stop the validation subsystem.
482  */
483 void
484 GST_validation_stop ()
485 {
486   struct CheckHelloValidatedContext *chvc;
487
488   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
489                                          &cleanup_validation_entry, NULL);
490   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
491   validation_map = NULL;
492   while (NULL != (chvc = chvc_head))
493   {
494     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
495     GNUNET_free (chvc);
496   }
497   GNUNET_PEERINFO_notify_cancel (pnc);
498 }
499
500
501 /**
502  * Address validation cleanup task (record no longer needed).
503  *
504  * @param cls the 'struct ValidationEntry'
505  * @param tc scheduler context (unused)
506  */
507 static void
508 timeout_hello_validation (void *cls,
509                           const struct GNUNET_SCHEDULER_TaskContext *tc)
510 {
511   struct ValidationEntry *ve = cls;
512
513   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
514   GNUNET_STATISTICS_update (GST_stats,
515                             gettext_noop ("# address records discarded"), 1,
516                             GNUNET_NO);
517   cleanup_validation_entry (NULL, &ve->pid.hashPubKey, ve);
518 }
519
520
521 /**
522  * Send the given PONG to the given address.
523  *
524  * @param cls the PONG message
525  * @param public_key public key for the peer, never NULL
526  * @param target peer this change is about, never NULL
527  * @param valid_until is ZERO if we never validated the address,
528  *                    otherwise a time up to when we consider it (or was) valid
529  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
530  *                          is ZERO if the address is considered valid (no validation needed)
531  *                          otherwise a time in the future if we're currently denying re-validation
532  * @param plugin_name name of the plugin
533  * @param plugin_address binary address
534  * @param plugin_address_len length of address
535  */
536 static void
537 multicast_pong (void *cls,
538                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
539                 *public_key, const struct GNUNET_PeerIdentity *target,
540                 struct GNUNET_TIME_Absolute valid_until,
541                 struct GNUNET_TIME_Absolute validation_block,
542                 const char *plugin_name, const void *plugin_address,
543                 size_t plugin_address_len)
544 {
545   struct TransportPongMessage *pong = cls;
546   struct GNUNET_TRANSPORT_PluginFunctions *papi;
547
548   papi = GST_plugins_find (plugin_name);
549   if (papi == NULL)
550     return;
551   (void) papi->send (papi->cls, target, (const char *) pong,
552                      ntohs (pong->header.size), PONG_PRIORITY,
553                      HELLO_REVALIDATION_START_TIME, NULL, plugin_address,
554                      plugin_address_len, GNUNET_YES, NULL, NULL);
555 }
556
557
558 /**
559  * We've received a PING.  If appropriate, generate a PONG.
560  *
561  * @param sender peer sending the PING
562  * @param hdr the PING
563  * @param session session we got the PING from
564  * @param plugin_name name of plugin that received the PING
565  * @param sender_address address of the sender as known to the plugin, NULL
566  *                       if we did not initiate the connection
567  * @param sender_address_len number of bytes in sender_address
568  */
569 void
570 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
571                             const struct GNUNET_MessageHeader *hdr,
572                             const char *plugin_name, struct Session *session,
573                             const void *sender_address,
574                             size_t sender_address_len)
575 {
576   const struct TransportPingMessage *ping;
577   struct TransportPongMessage *pong;
578   struct GNUNET_TRANSPORT_PluginFunctions *papi;
579   struct GNUNET_CRYPTO_RsaSignature *sig_cache;
580   struct GNUNET_TIME_Absolute *sig_cache_exp;
581   const char *addr;
582   const char *addrend;
583   size_t alen;
584   size_t slen;
585   ssize_t ret;
586
587   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
588   {
589     GNUNET_break_op (0);
590     return;
591   }
592   ping = (const struct TransportPingMessage *) hdr;
593   if (0 !=
594       memcmp (&ping->target, &GST_my_identity,
595               sizeof (struct GNUNET_PeerIdentity)))
596   {
597     GNUNET_STATISTICS_update (GST_stats,
598                               gettext_noop
599                               ("# PING message for different peer received"), 1,
600                               GNUNET_NO);
601     return;
602   }
603   GNUNET_STATISTICS_update (GST_stats,
604                             gettext_noop ("# PING messages received"), 1,
605                             GNUNET_NO);
606   addr = (const char *) &ping[1];
607   alen = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
608   /* peer wants to confirm that this is one of our addresses, this is what is
609    * used for address validation */
610
611   sig_cache = NULL;
612   sig_cache_exp = NULL;
613
614   if (0 < alen)
615   {
616     addrend = memchr (addr, '\0', alen);
617     if (NULL == addrend)
618     {
619       GNUNET_break_op (0);
620       return;
621     }
622     addrend++;
623     slen = strlen (addr) + 1;
624     alen -= slen;
625
626     if (GNUNET_YES !=
627         GST_hello_test_address (addr, addrend, alen, &sig_cache,
628                                 &sig_cache_exp))
629     {
630       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
631                   _
632                   ("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
633                   GST_plugins_a2s (addr, addrend, alen));
634       return;
635     }
636   }
637   else
638   {
639     addrend = NULL;             /* make gcc happy */
640     slen = 0;
641     static struct GNUNET_CRYPTO_RsaSignature no_address_signature;
642     static struct GNUNET_TIME_Absolute no_address_signature_expiration;
643
644     sig_cache = &no_address_signature;
645     sig_cache_exp = &no_address_signature_expiration;
646   }
647
648   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
649   pong->header.size =
650       htons (sizeof (struct TransportPongMessage) + alen + slen);
651   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
652   pong->purpose.size =
653       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
654              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
655              alen + slen);
656   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
657   pong->challenge = ping->challenge;
658   pong->addrlen = htonl (alen + slen);
659   memcpy (&pong[1], addr, slen);
660   memcpy (&((char *) &pong[1])[slen], addrend, alen);
661   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value <
662       PONG_SIGNATURE_LIFETIME.rel_value / 4)
663   {
664     /* create / update cached sig */
665 #if DEBUG_TRANSPORT
666     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
667                 "Creating PONG signature to indicate ownership.\n");
668 #endif
669     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
670     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
671     GNUNET_assert (GNUNET_OK ==
672                    GNUNET_CRYPTO_rsa_sign (GST_my_private_key, &pong->purpose,
673                                            sig_cache));
674   }
675   else
676   {
677     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
678   }
679   pong->signature = *sig_cache;
680
681   /* first see if the session we got this PING from can be used to transmit
682    * a response reliably */
683   papi = GST_plugins_find (plugin_name);
684   if (papi == NULL)
685     ret = -1;
686   else
687     ret =
688         papi->send (papi->cls, sender, (const char *) pong,
689                     ntohs (pong->header.size), PONG_PRIORITY,
690                     HELLO_REVALIDATION_START_TIME, session, sender_address,
691                     sender_address_len, GNUNET_SYSERR, NULL, NULL);
692   if (ret != -1)
693   {
694     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
695                 "Transmitted PONG to `%s' via reliable mechanism\n",
696                 GNUNET_i2s (sender));
697     /* done! */
698     GNUNET_STATISTICS_update (GST_stats,
699                               gettext_noop
700                               ("# PONGs unicast via reliable transport"), 1,
701                               GNUNET_NO);
702     GNUNET_free (pong);
703     return;
704   }
705
706   /* no reliable method found, try transmission via all known addresses */
707   GNUNET_STATISTICS_update (GST_stats,
708                             gettext_noop
709                             ("# PONGs multicast to all available addresses"), 1,
710                             GNUNET_NO);
711   GST_validation_get_addresses (sender, &multicast_pong, pong);
712   GNUNET_free (pong);
713 }
714
715
716 /**
717  * Context for the 'validate_address' function
718  */
719 struct ValidateAddressContext
720 {
721   /**
722    * Hash of the public key of the peer whose address is being validated.
723    */
724   struct GNUNET_PeerIdentity pid;
725
726   /**
727    * Public key of the peer whose address is being validated.
728    */
729   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
730 };
731
732
733 /**
734  * Function called with the result from blacklisting.
735  * Send a PING to the other peer if a communication is allowed.
736  *
737  * @param cls ou r'struct ValidationEntry'
738  * @param pid identity of the other peer
739  * @param result GNUNET_OK if the connection is allowed, GNUNET_NO if not
740  */
741 static void
742 transmit_ping_if_allowed (void *cls, const struct GNUNET_PeerIdentity *pid,
743                           int result)
744 {
745   struct ValidationEntry *ve = cls;
746   struct TransportPingMessage ping;
747   struct GNUNET_TRANSPORT_PluginFunctions *papi;
748   const struct GNUNET_MessageHeader *hello;
749   ssize_t ret;
750   size_t tsize;
751   size_t slen;
752   uint16_t hsize;
753
754   ve->bc = NULL;
755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting plain PING to `%s' %s\n",
756               GNUNET_i2s (pid), GST_plugins_a2s (ve->transport_name, ve->addr,
757                                                  ve->addrlen));
758
759   slen = strlen (ve->transport_name) + 1;
760   hello = GST_hello_get ();
761   hsize = ntohs (hello->size);
762   tsize = sizeof (struct TransportPingMessage) + ve->addrlen + slen + hsize;
763
764   ping.header.size =
765       htons (sizeof (struct TransportPingMessage) + ve->addrlen + slen);
766   ping.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
767   ping.challenge = htonl (ve->challenge);
768   ping.target = *pid;
769
770   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
771   {
772     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
773                 _
774                 ("Not transmitting `%s' with `%s', message too big (%u bytes!). This should not happen.\n"),
775                 "HELLO", "PING", (unsigned int) tsize);
776     /* message too big (!?), get rid of HELLO */
777     hsize = 0;
778     tsize = sizeof (struct TransportPingMessage) + ve->addrlen + slen + hsize;
779   }
780   {
781     char message_buf[tsize];
782
783     /* build message with structure:
784      *  [HELLO][TransportPingMessage][Transport name][Address] */
785     memcpy (message_buf, hello, hsize);
786     memcpy (&message_buf[hsize], &ping, sizeof (struct TransportPingMessage));
787     memcpy (&message_buf[sizeof (struct TransportPingMessage) + hsize],
788             ve->transport_name, slen);
789     memcpy (&message_buf[sizeof (struct TransportPingMessage) + slen + hsize],
790             ve->addr, ve->addrlen);
791     papi = GST_plugins_find (ve->transport_name);
792     if (papi == NULL)
793       ret = -1;
794     else
795     {
796       GNUNET_assert (papi->send != NULL);
797       ret =
798           papi->send (papi->cls, pid, message_buf, tsize, PING_PRIORITY,
799                       HELLO_REVALIDATION_START_TIME, NULL /* no session */ ,
800                       ve->addr, ve->addrlen, GNUNET_YES, NULL, NULL);
801     }
802   }
803   if (-1 != ret)
804   {
805     ve->send_time = GNUNET_TIME_absolute_get ();
806     GNUNET_STATISTICS_update (GST_stats,
807                               gettext_noop
808                               ("# PING without HELLO messages sent"), 1,
809                               GNUNET_NO);
810   }
811 }
812
813
814 /**
815  * Iterator callback to go over all addresses and try to validate them
816  * (unless blocked or already validated).
817  *
818  * @param cls pointer to a 'struct ValidateAddressContext'
819  * @param tname name of the transport
820  * @param expiration expiration time
821  * @param addr the address
822  * @param addrlen length of the address
823  * @return GNUNET_OK (keep the address)
824  */
825 static int
826 validate_address (void *cls, const char *tname,
827                   struct GNUNET_TIME_Absolute expiration, const void *addr,
828                   uint16_t addrlen)
829 {
830   const struct ValidateAddressContext *vac = cls;
831   const struct GNUNET_PeerIdentity *pid = &vac->pid;
832   struct ValidationEntry *ve;
833   struct GST_BlacklistCheck *bc;
834
835   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
836     return GNUNET_OK;           /* expired */
837   ve = find_validation_entry (&vac->public_key, pid, tname, addr, addrlen);
838   if (GNUNET_TIME_absolute_get_remaining (ve->validation_block).rel_value > 0)
839     return GNUNET_OK;           /* blocked */
840   if ((GNUNET_SCHEDULER_NO_TASK != ve->timeout_task) &&
841       (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value > 0))
842     return GNUNET_OK;           /* revalidation task already scheduled & still  valid */
843   ve->validation_block =
844       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME);
845   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
846     GNUNET_SCHEDULER_cancel (ve->timeout_task);
847   ve->timeout_task =
848       GNUNET_SCHEDULER_add_delayed (HELLO_REVALIDATION_START_TIME,
849                                     &timeout_hello_validation, ve);
850   bc = GST_blacklist_test_allowed (pid, tname, &transmit_ping_if_allowed, ve);
851   if (NULL != bc)
852     ve->bc = bc;
853   return GNUNET_OK;
854 }
855
856
857 /**
858  * Do address validation again to keep address valid.
859  *
860  * @param cls the 'struct ValidationEntry'
861  * @param tc scheduler context (unused)
862  */
863 static void
864 revalidate_address (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
865 {
866   struct ValidationEntry *ve = cls;
867   struct GNUNET_TIME_Relative delay;
868   struct ValidateAddressContext vac;
869
870   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
871   delay = GNUNET_TIME_absolute_get_remaining (ve->validation_block);
872   if (delay.rel_value > 0)
873   {
874     /* should wait a bit longer */
875     ve->timeout_task =
876         GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
877     return;
878   }
879   GNUNET_STATISTICS_update (GST_stats,
880                             gettext_noop ("# address revalidations started"), 1,
881                             GNUNET_NO);
882   vac.pid = ve->pid;
883   vac.public_key = ve->public_key;
884   validate_address (&vac, ve->transport_name, ve->valid_until, ve->addr,
885                     (uint16_t) ve->addrlen);
886 }
887
888
889 /**
890  * Add the validated peer address to the HELLO.
891  *
892  * @param cls the 'struct ValidationEntry' with the validated address
893  * @param max space in buf
894  * @param buf where to add the address
895  * @return number of bytes written, 0 to signal the
896  *         end of the iteration.
897  */
898 static size_t
899 add_valid_peer_address (void *cls, size_t max, void *buf)
900 {
901   struct ValidationEntry *ve = cls;
902
903   if (GNUNET_YES == ve->copied)
904     return 0;                   /* terminate */
905   ve->copied = GNUNET_YES;
906   return GNUNET_HELLO_add_address (ve->transport_name, ve->valid_until,
907                                    ve->addr, ve->addrlen, buf, max);
908 }
909
910
911 /**
912  * We've received a PONG.  Check if it matches a pending PING and
913  * mark the respective address as confirmed.
914  *
915  * @param sender peer sending the PONG
916  * @param hdr the PONG
917  */
918 void
919 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
920                             const struct GNUNET_MessageHeader *hdr)
921 {
922   const struct TransportPongMessage *pong;
923   struct ValidationEntry *ve;
924   const char *tname;
925   const char *addr;
926   size_t addrlen;
927   size_t slen;
928   size_t size;
929   uint32_t rdelay;
930   struct GNUNET_TIME_Relative delay;
931   struct GNUNET_HELLO_Message *hello;
932
933   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
934   {
935     GNUNET_break_op (0);
936     return;
937   }
938   GNUNET_STATISTICS_update (GST_stats,
939                             gettext_noop ("# PONG messages received"), 1,
940                             GNUNET_NO);
941
942   pong = (const struct TransportPongMessage *) hdr;
943   tname = (const char *) &pong[1];
944   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
945   addr = memchr (tname, '\0', size);
946   if (NULL == addr)
947   {
948     GNUNET_break_op (0);
949     return;
950   }
951   addr++;
952   slen = strlen (tname) + 1;
953   addrlen = size - slen;
954
955   ve = find_validation_entry (NULL, sender, tname, addr, addrlen);
956
957   if (NULL == ve)
958   {
959     GNUNET_STATISTICS_update (GST_stats,
960                               gettext_noop
961                               ("# PONGs dropped, no matching pending validation"),
962                               1, GNUNET_NO);
963     return;
964   }
965   /* now check that PONG is well-formed */
966   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
967   {
968     GNUNET_break_op (0);
969     return;
970   }
971
972   if (GNUNET_TIME_absolute_get_remaining
973       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
974   {
975     GNUNET_STATISTICS_update (GST_stats,
976                               gettext_noop
977                               ("# PONGs dropped, signature expired"), 1,
978                               GNUNET_NO);
979     return;
980   }
981   if (GNUNET_OK !=
982       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
983                                 &pong->purpose, &pong->signature,
984                                 &ve->public_key))
985   {
986     GNUNET_break_op (0);
987     return;
988   }
989 #if DEBUG_TRANSPORT
990   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
991               "Address validated for peer `%s' with plugin `%s': `%s'\n",
992               GNUNET_i2s (sender), tname, GST_plugins_a2s (tname, addr,
993                                                            addrlen));
994 #endif
995
996   /* validity achieved, remember it! */
997   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
998   {
999     struct GNUNET_ATS_Information ats;
1000
1001     ats.type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1002     ats.value =
1003         htonl ((uint32_t)
1004                GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value);
1005     GNUNET_ATS_address_update (GST_ats, &ve->pid, ve->transport_name, ve->addr,
1006                                ve->addrlen, NULL, &ats, 1);
1007   }
1008
1009   /* build HELLO to store in PEERINFO */
1010   ve->copied = GNUNET_NO;
1011   hello = GNUNET_HELLO_create (&ve->public_key, &add_valid_peer_address, ve);
1012   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello);
1013   GNUNET_free (hello);
1014
1015   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
1016     GNUNET_SCHEDULER_cancel (ve->timeout_task);
1017
1018   /* randomly delay by up to 1h to avoid   synchronous validations */
1019   rdelay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 60 * 60);
1020   delay =
1021       GNUNET_TIME_relative_add (HELLO_REVALIDATION_START_TIME,
1022                                 GNUNET_TIME_relative_multiply
1023                                 (GNUNET_TIME_UNIT_SECONDS, rdelay));
1024   ve->timeout_task =
1025       GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
1026 }
1027
1028
1029 /**
1030  * We've received a HELLO, check which addresses are new and trigger
1031  * validation.
1032  *
1033  * @param hello the HELLO we received
1034  */
1035 void
1036 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1037 {
1038   const struct GNUNET_HELLO_Message *hm =
1039       (const struct GNUNET_HELLO_Message *) hello;
1040   struct ValidateAddressContext vac;
1041   struct GNUNET_HELLO_Message *h;
1042
1043   if ((GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1044       (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1045   {
1046     /* malformed HELLO */
1047     GNUNET_break (0);
1048     return;
1049   }
1050   if (0 ==
1051       memcmp (&GST_my_identity, &vac.pid, sizeof (struct GNUNET_PeerIdentity)))
1052     return;
1053   /* Add peer identity without addresses to peerinfo service */
1054   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL);
1055   GNUNET_PEERINFO_add_peer (GST_peerinfo, h);
1056 #if VERBOSE_VALIDATION
1057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1058               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1059               GNUNET_i2s (&vac.pid));
1060 #endif
1061   GNUNET_free (h);
1062
1063   GNUNET_assert (NULL ==
1064                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1065                                                  &validate_address, &vac));
1066 }
1067
1068
1069 /**
1070  * Closure for 'iterate_addresses'
1071  */
1072 struct IteratorContext
1073 {
1074   /**
1075    * Function to call on each address.
1076    */
1077   GST_ValidationAddressCallback cb;
1078
1079   /**
1080    * Closure for 'cb'.
1081    */
1082   void *cb_cls;
1083
1084 };
1085
1086
1087 /**
1088  * Call the callback in the closure for each validation entry.
1089  *
1090  * @param cls the 'struct GST_ValidationIteratorContext'
1091  * @param key the peer's identity
1092  * @param value the 'struct ValidationEntry'
1093  * @return GNUNET_OK (continue to iterate)
1094  */
1095 static int
1096 iterate_addresses (void *cls, const GNUNET_HashCode * key, void *value)
1097 {
1098   struct IteratorContext *ic = cls;
1099   struct ValidationEntry *ve = value;
1100
1101   ic->cb (ic->cb_cls, &ve->public_key, &ve->pid, ve->valid_until,
1102           ve->validation_block, ve->transport_name, ve->addr, ve->addrlen);
1103   return GNUNET_OK;
1104 }
1105
1106
1107 /**
1108  * Call the given function for each address for the given target.
1109  * Can either give a snapshot (synchronous API) or be continuous.
1110  *
1111  * @param target peer information is requested for
1112  * @param cb function to call; will not be called after this function returns
1113  * @param cb_cls closure for 'cb'
1114  */
1115 void
1116 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1117                               GST_ValidationAddressCallback cb, void *cb_cls)
1118 {
1119   struct IteratorContext ic;
1120
1121   ic.cb = cb;
1122   ic.cb_cls = cb_cls;
1123   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1124                                               &target->hashPubKey,
1125                                               &iterate_addresses, &ic);
1126 }
1127
1128
1129 /* end of file gnunet-service-transport_validation.c */