introduce concept of unverified_kx, as a step towards having KX_AUTH implemented...
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
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  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - KX:
28  *   + clean up KX logic, including adding sender authentication
29  *   + implement rekeying
30  *   + check KX estate machine -- make sure it is never stuck!
31  * - connection management
32  *   + properly (evaluate, kill old ones, search for new ones)
33  *   + when managing connections, distinguish those that
34  *     have (recently) had traffic from those that were
35  *     never ready (or not recently)
36  */
37 #include "platform.h"
38 #include "gnunet_util_lib.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_signatures.h"
41 #include "gnunet-service-cadet-new.h"
42 #include "cadet_protocol.h"
43 #include "gnunet-service-cadet-new_channel.h"
44 #include "gnunet-service-cadet-new_connection.h"
45 #include "gnunet-service-cadet-new_tunnels.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
48
49
50 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
51
52 /**
53  * How often do we try to decrypt payload with unverified key
54  * material?  Used to limit CPU increase upon receiving bogus
55  * KX.
56  */
57 #define MAX_UNVERIFIED_ATTEMPTS 16
58
59 /**
60  * How long do we wait until tearing down an idle tunnel?
61  */
62 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
63
64 /**
65  * Maximum number of skipped keys we keep in memory per tunnel.
66  */
67 #define MAX_SKIPPED_KEYS 64
68
69 /**
70  * Maximum number of keys (and thus ratchet steps) we are willing to
71  * skip before we decide this is either a bogus packet or a DoS-attempt.
72  */
73 #define MAX_KEY_GAP 256
74
75
76 /**
77  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
78  */
79 struct CadetTunnelSkippedKey
80 {
81   /**
82    * DLL next.
83    */
84   struct CadetTunnelSkippedKey *next;
85
86   /**
87    * DLL prev.
88    */
89   struct CadetTunnelSkippedKey *prev;
90
91   /**
92    * When was this key stored (for timeout).
93    */
94   struct GNUNET_TIME_Absolute timestamp;
95
96   /**
97    * Header key.
98    */
99   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
100
101   /**
102    * Message key.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
105
106   /**
107    * Key number for a given HK.
108    */
109   unsigned int Kn;
110 };
111
112
113 /**
114  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
115  */
116 struct CadetTunnelAxolotl
117 {
118   /**
119    * A (double linked) list of stored message keys and associated header keys
120    * for "skipped" messages, i.e. messages that have not been
121    * received despite the reception of more recent messages, (head).
122    */
123   struct CadetTunnelSkippedKey *skipped_head;
124
125   /**
126    * Skipped messages' keys DLL, tail.
127    */
128   struct CadetTunnelSkippedKey *skipped_tail;
129
130   /**
131    * 32-byte root key which gets updated by DH ratchet.
132    */
133   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
134
135   /**
136    * 32-byte header key (send).
137    */
138   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
139
140   /**
141    * 32-byte header key (recv)
142    */
143   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
144
145   /**
146    * 32-byte next header key (send).
147    */
148   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
149
150   /**
151    * 32-byte next header key (recv).
152    */
153   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
154
155   /**
156    * 32-byte chain keys (used for forward-secrecy updating, send).
157    */
158   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
159
160   /**
161    * 32-byte chain keys (used for forward-secrecy updating, recv).
162    */
163   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
164
165   /**
166    * ECDH for key exchange (A0 / B0).
167    */
168   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
169
170   /**
171    * ECDH Ratchet key (send).
172    */
173   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
174
175   /**
176    * ECDH Ratchet key (recv).
177    */
178   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
179
180   /**
181    * When does this ratchet expire and a new one is triggered.
182    */
183   struct GNUNET_TIME_Absolute ratchet_expiration;
184
185   /**
186    * Number of elements in @a skipped_head <-> @a skipped_tail.
187    */
188   unsigned int skipped;
189
190   /**
191    * Message number (reset to 0 with each new ratchet, next message to send).
192    */
193   uint32_t Ns;
194
195   /**
196    * Message number (reset to 0 with each new ratchet, next message to recv).
197    */
198   uint32_t Nr;
199
200   /**
201    * Previous message numbers (# of msgs sent under prev ratchet)
202    */
203   uint32_t PNs;
204
205   /**
206    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
207    */
208   int ratchet_flag;
209
210   /**
211    * Number of messages recieved since our last ratchet advance.
212    * - If this counter = 0, we cannot send a new ratchet key in next msg.
213    * - If this counter > 0, we can (but don't yet have to) send a new key.
214    */
215   unsigned int ratchet_allowed;
216
217   /**
218    * Number of messages recieved since our last ratchet advance.
219    * - If this counter = 0, we cannot send a new ratchet key in next msg.
220    * - If this counter > 0, we can (but don't yet have to) send a new key.
221    */
222   unsigned int ratchet_counter;
223
224 };
225
226
227 /**
228  * Struct used to save messages in a non-ready tunnel to send once connected.
229  */
230 struct CadetTunnelQueueEntry
231 {
232   /**
233    * We are entries in a DLL
234    */
235   struct CadetTunnelQueueEntry *next;
236
237   /**
238    * We are entries in a DLL
239    */
240   struct CadetTunnelQueueEntry *prev;
241
242   /**
243    * Tunnel these messages belong in.
244    */
245   struct CadetTunnel *t;
246
247   /**
248    * Continuation to call once sent (on the channel layer).
249    */
250   GNUNET_SCHEDULER_TaskCallback cont;
251
252   /**
253    * Closure for @c cont.
254    */
255   void *cont_cls;
256
257   /**
258    * Envelope of message to send follows.
259    */
260   struct GNUNET_MQ_Envelope *env;
261
262   /**
263    * Where to put the connection identifier into the payload
264    * of the message in @e env once we have it?
265    */
266   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
267 };
268
269
270 /**
271  * Struct containing all information regarding a tunnel to a peer.
272  */
273 struct CadetTunnel
274 {
275   /**
276    * Destination of the tunnel.
277    */
278   struct CadetPeer *destination;
279
280   /**
281    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282    * ephemeral key changes.
283    */
284   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
285
286   /**
287    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
288    */
289   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
290
291   /**
292    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
293    */
294   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
295
296   /**
297    * Axolotl info.
298    */
299   struct CadetTunnelAxolotl ax;
300
301   /**
302    * Unverified Axolotl info, used only if we got a fresh KX (not a
303    * KX_AUTH) while our end of the tunnel was still up.  In this case,
304    * we keep the fresh KX around but do not put it into action until
305    * we got encrypted payload that assures us of the authenticity of
306    * the KX.
307    */
308   struct CadetTunnelAxolotl *unverified_ax;
309
310   /**
311    * Task scheduled if there are no more channels using the tunnel.
312    */
313   struct GNUNET_SCHEDULER_Task *destroy_task;
314
315   /**
316    * Task to trim connections if too many are present.
317    */
318   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
319
320   /**
321    * Task to send messages from queue (if possible).
322    */
323   struct GNUNET_SCHEDULER_Task *send_task;
324
325   /**
326    * Task to trigger KX.
327    */
328   struct GNUNET_SCHEDULER_Task *kx_task;
329
330   /**
331    * Tokenizer for decrypted messages.
332    */
333   struct GNUNET_MessageStreamTokenizer *mst;
334
335   /**
336    * Dispatcher for decrypted messages only (do NOT use for sending!).
337    */
338   struct GNUNET_MQ_Handle *mq;
339
340   /**
341    * DLL of connections that are actively used to reach the destination peer.
342    */
343   struct CadetTConnection *connection_head;
344
345   /**
346    * DLL of connections that are actively used to reach the destination peer.
347    */
348   struct CadetTConnection *connection_tail;
349
350   /**
351    * Channels inside this tunnel. Maps
352    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
353    */
354   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
355
356   /**
357    * Channel ID for the next created channel in this tunnel.
358    */
359   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
360
361   /**
362    * Queued messages, to transmit once tunnel gets connected.
363    */
364   struct CadetTunnelQueueEntry *tq_head;
365
366   /**
367    * Queued messages, to transmit once tunnel gets connected.
368    */
369   struct CadetTunnelQueueEntry *tq_tail;
370
371   /**
372    * How long do we wait until we retry the KX?
373    */
374   struct GNUNET_TIME_Relative kx_retry_delay;
375
376   /**
377    * When do we try the next KX?
378    */
379   struct GNUNET_TIME_Absolute next_kx_attempt;
380
381   /**
382    * Number of connections in the @e connection_head DLL.
383    */
384   unsigned int num_connections;
385
386   /**
387    * How often have we tried and failed to decrypt a message using
388    * the unverified KX material from @e unverified_ax?  Used to
389    * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
390    */
391   unsigned int unverified_attempts;
392
393   /**
394    * Number of entries in the @e tq_head DLL.
395    */
396   unsigned int tq_len;
397
398   /**
399    * State of the tunnel encryption.
400    */
401   enum CadetTunnelEState estate;
402
403 };
404
405
406 /**
407  * Get the static string for the peer this tunnel is directed.
408  *
409  * @param t Tunnel.
410  *
411  * @return Static string the destination peer's ID.
412  */
413 const char *
414 GCT_2s (const struct CadetTunnel *t)
415 {
416   static char buf[64];
417
418   if (NULL == t)
419     return "Tunnel(NULL)";
420   GNUNET_snprintf (buf,
421                    sizeof (buf),
422                    "Tunnel %s",
423                    GNUNET_i2s (GCP_get_id (t->destination)));
424   return buf;
425 }
426
427
428 /**
429  * Get string description for tunnel encryption state.
430  *
431  * @param es Tunnel state.
432  *
433  * @return String representation.
434  */
435 static const char *
436 estate2s (enum CadetTunnelEState es)
437 {
438   static char buf[32];
439
440   switch (es)
441   {
442     case CADET_TUNNEL_KEY_UNINITIALIZED:
443       return "CADET_TUNNEL_KEY_UNINITIALIZED";
444     case CADET_TUNNEL_KEY_SENT:
445       return "CADET_TUNNEL_KEY_SENT";
446     case CADET_TUNNEL_KEY_PING:
447       return "CADET_TUNNEL_KEY_PING";
448     case CADET_TUNNEL_KEY_OK:
449       return "CADET_TUNNEL_KEY_OK";
450     case CADET_TUNNEL_KEY_REKEY:
451       return "CADET_TUNNEL_KEY_REKEY";
452     default:
453       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
454       return buf;
455   }
456 }
457
458
459 /**
460  * Return the peer to which this tunnel goes.
461  *
462  * @param t a tunnel
463  * @return the destination of the tunnel
464  */
465 struct CadetPeer *
466 GCT_get_destination (struct CadetTunnel *t)
467 {
468   return t->destination;
469 }
470
471
472 /**
473  * Count channels of a tunnel.
474  *
475  * @param t Tunnel on which to count.
476  *
477  * @return Number of channels.
478  */
479 unsigned int
480 GCT_count_channels (struct CadetTunnel *t)
481 {
482   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
483 }
484
485
486 /**
487  * Lookup a channel by its @a ctn.
488  *
489  * @param t tunnel to look in
490  * @param ctn number of channel to find
491  * @return NULL if channel does not exist
492  */
493 struct CadetChannel *
494 lookup_channel (struct CadetTunnel *t,
495                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
496 {
497   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
498                                               ntohl (ctn.cn));
499 }
500
501
502 /**
503  * Count all created connections of a tunnel. Not necessarily ready connections!
504  *
505  * @param t Tunnel on which to count.
506  *
507  * @return Number of connections created, either being established or ready.
508  */
509 unsigned int
510 GCT_count_any_connections (struct CadetTunnel *t)
511 {
512   return t->num_connections;
513 }
514
515
516 /**
517  * Find first connection that is ready in the list of
518  * our connections.  Picks ready connections round-robin.
519  *
520  * @param t tunnel to search
521  * @return NULL if we have no connection that is ready
522  */
523 static struct CadetTConnection *
524 get_ready_connection (struct CadetTunnel *t)
525 {
526   for (struct CadetTConnection *pos = t->connection_head;
527        NULL != pos;
528        pos = pos->next)
529     if (GNUNET_YES == pos->is_ready)
530     {
531       if (pos != t->connection_tail)
532       {
533         /* move 'pos' to the end, so we try other ready connections
534            first next time (round-robin, modulo availability) */
535         GNUNET_CONTAINER_DLL_remove (t->connection_head,
536                                      t->connection_tail,
537                                      pos);
538         GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
539                                           t->connection_tail,
540                                           pos);
541       }
542       return pos;
543     }
544   return NULL;
545 }
546
547
548 /**
549  * Get the encryption state of a tunnel.
550  *
551  * @param t Tunnel.
552  *
553  * @return Tunnel's encryption state.
554  */
555 enum CadetTunnelEState
556 GCT_get_estate (struct CadetTunnel *t)
557 {
558   return t->estate;
559 }
560
561
562 /**
563  * Called when either we have a new connection, or a new message in the
564  * queue, or some existing connection has transmission capacity.  Looks
565  * at our message queue and if there is a message, picks a connection
566  * to send it on.
567  *
568  * @param cls the `struct CadetTunnel` to process messages on
569  */
570 static void
571 trigger_transmissions (void *cls);
572
573
574 /* ************************************** start core crypto ***************************** */
575
576
577 /**
578  * Create a new Axolotl ephemeral (ratchet) key.
579  *
580  * @param ax key material to update
581  */
582 static void
583 new_ephemeral (struct CadetTunnelAxolotl *ax)
584 {
585   GNUNET_free_non_null (ax->DHRs);
586   ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
587 }
588
589
590 /**
591  * Calculate HMAC.
592  *
593  * @param plaintext Content to HMAC.
594  * @param size Size of @c plaintext.
595  * @param iv Initialization vector for the message.
596  * @param key Key to use.
597  * @param hmac[out] Destination to store the HMAC.
598  */
599 static void
600 t_hmac (const void *plaintext,
601         size_t size,
602         uint32_t iv,
603         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
604         struct GNUNET_ShortHashCode *hmac)
605 {
606   static const char ctx[] = "cadet authentication key";
607   struct GNUNET_CRYPTO_AuthKey auth_key;
608   struct GNUNET_HashCode hash;
609
610   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
611                                  key,
612                                  &iv, sizeof (iv),
613                                  key, sizeof (*key),
614                                  ctx, sizeof (ctx),
615                                  NULL);
616   /* Two step: GNUNET_ShortHash is only 256 bits,
617      GNUNET_HashCode is 512, so we truncate. */
618   GNUNET_CRYPTO_hmac (&auth_key,
619                       plaintext,
620                       size,
621                       &hash);
622   GNUNET_memcpy (hmac,
623                  &hash,
624                  sizeof (*hmac));
625 }
626
627
628 /**
629  * Perform a HMAC.
630  *
631  * @param key Key to use.
632  * @param hash[out] Resulting HMAC.
633  * @param source Source key material (data to HMAC).
634  * @param len Length of @a source.
635  */
636 static void
637 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
638                 struct GNUNET_HashCode *hash,
639                 const void *source,
640                 unsigned int len)
641 {
642   static const char ctx[] = "axolotl HMAC-HASH";
643   struct GNUNET_CRYPTO_AuthKey auth_key;
644
645   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
646                                  key,
647                                  ctx, sizeof (ctx),
648                                  NULL);
649   GNUNET_CRYPTO_hmac (&auth_key,
650                       source,
651                       len,
652                       hash);
653 }
654
655
656 /**
657  * Derive a symmetric encryption key from an HMAC-HASH.
658  *
659  * @param key Key to use for the HMAC.
660  * @param[out] out Key to generate.
661  * @param source Source key material (data to HMAC).
662  * @param len Length of @a source.
663  */
664 static void
665 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
666                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
667                    const void *source,
668                    unsigned int len)
669 {
670   static const char ctx[] = "axolotl derive key";
671   struct GNUNET_HashCode h;
672
673   t_ax_hmac_hash (key,
674                   &h,
675                   source,
676                   len);
677   GNUNET_CRYPTO_kdf (out, sizeof (*out),
678                      ctx, sizeof (ctx),
679                      &h, sizeof (h),
680                      NULL);
681 }
682
683
684 /**
685  * Encrypt data with the axolotl tunnel key.
686  *
687  * @param ax key material to use.
688  * @param dst Destination with @a size bytes for the encrypted data.
689  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
690  * @param size Size of the buffers at @a src and @a dst
691  */
692 static void
693 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
694               void *dst,
695               const void *src,
696               size_t size)
697 {
698   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
699   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
700   size_t out_size;
701
702   ax->ratchet_counter++;
703   if ( (GNUNET_YES == ax->ratchet_allowed) &&
704        ( (ratchet_messages <= ax->ratchet_counter) ||
705          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
706   {
707     ax->ratchet_flag = GNUNET_YES;
708   }
709   if (GNUNET_YES == ax->ratchet_flag)
710   {
711     /* Advance ratchet */
712     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
713     struct GNUNET_HashCode dh;
714     struct GNUNET_HashCode hmac;
715     static const char ctx[] = "axolotl ratchet";
716
717     new_ephemeral (ax);
718     ax->HKs = ax->NHKs;
719
720     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
721     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
722                             &ax->DHRr,
723                             &dh);
724     t_ax_hmac_hash (&ax->RK,
725                     &hmac,
726                     &dh,
727                     sizeof (dh));
728     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
729                        ctx, sizeof (ctx),
730                        &hmac, sizeof (hmac),
731                        NULL);
732     ax->RK = keys[0];
733     ax->NHKs = keys[1];
734     ax->CKs = keys[2];
735
736     ax->PNs = ax->Ns;
737     ax->Ns = 0;
738     ax->ratchet_flag = GNUNET_NO;
739     ax->ratchet_allowed = GNUNET_NO;
740     ax->ratchet_counter = 0;
741     ax->ratchet_expiration
742       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
743                                   ratchet_time);
744   }
745
746   t_hmac_derive_key (&ax->CKs,
747                      &MK,
748                      "0",
749                      1);
750   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
751                                      &MK,
752                                      NULL, 0,
753                                      NULL);
754
755   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
756                                               size,
757                                               &MK,
758                                               &iv,
759                                               dst);
760   GNUNET_assert (size == out_size);
761   t_hmac_derive_key (&ax->CKs,
762                      &ax->CKs,
763                      "1",
764                      1);
765 }
766
767
768 /**
769  * Decrypt data with the axolotl tunnel key.
770  *
771  * @param ax key material to use.
772  * @param dst Destination for the decrypted data, must contain @a size bytes.
773  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
774  * @param size Size of the @a src and @a dst buffers
775  */
776 static void
777 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
778               void *dst,
779               const void *src,
780               size_t size)
781 {
782   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
783   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
784   size_t out_size;
785
786   t_hmac_derive_key (&ax->CKr,
787                      &MK,
788                      "0",
789                      1);
790   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
791                                      &MK,
792                                      NULL, 0,
793                                      NULL);
794   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
795   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
796                                               size,
797                                               &MK,
798                                               &iv,
799                                               dst);
800   GNUNET_assert (out_size == size);
801   t_hmac_derive_key (&ax->CKr,
802                      &ax->CKr,
803                      "1",
804                      1);
805 }
806
807
808 /**
809  * Encrypt header with the axolotl header key.
810  *
811  * @param ax key material to use.
812  * @param msg Message whose header to encrypt.
813  */
814 static void
815 t_h_encrypt (struct CadetTunnelAxolotl *ax,
816              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
817 {
818   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
819   size_t out_size;
820
821   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
822                                      &ax->HKs,
823                                      NULL, 0,
824                                      NULL);
825   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header.Ns,
826                                               sizeof (struct GNUNET_CADET_AxHeader),
827                                               &ax->HKs,
828                                               &iv,
829                                               &msg->ax_header.Ns);
830   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
831 }
832
833
834 /**
835  * Decrypt header with the current axolotl header key.
836  *
837  * @param ax key material to use.
838  * @param src Message whose header to decrypt.
839  * @param dst Where to decrypt header to.
840  */
841 static void
842 t_h_decrypt (struct CadetTunnelAxolotl *ax,
843              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
844              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
845 {
846   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
847   size_t out_size;
848
849   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
850                                      &ax->HKr,
851                                      NULL, 0,
852                                      NULL);
853   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
854                                               sizeof (struct GNUNET_CADET_AxHeader),
855                                               &ax->HKr,
856                                               &iv,
857                                               &dst->ax_header.Ns);
858   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
859 }
860
861
862 /**
863  * Delete a key from the list of skipped keys.
864  *
865  * @param ax key material to delete @a key from.
866  * @param key Key to delete.
867  */
868 static void
869 delete_skipped_key (struct CadetTunnelAxolotl *ax,
870                     struct CadetTunnelSkippedKey *key)
871 {
872   GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
873                                ax->skipped_tail,
874                                key);
875   GNUNET_free (key);
876   ax->skipped--;
877 }
878
879
880 /**
881  * Decrypt and verify data with the appropriate tunnel key and verify that the
882  * data has not been altered since it was sent by the remote peer.
883  *
884  * @param ax key material to use.
885  * @param dst Destination for the plaintext.
886  * @param src Source of the message. Can overlap with @c dst.
887  * @param size Size of the message.
888  * @return Size of the decrypted data, -1 if an error was encountered.
889  */
890 static ssize_t
891 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
892                  void *dst,
893                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
894                  size_t size)
895 {
896   struct CadetTunnelSkippedKey *key;
897   struct GNUNET_ShortHashCode *hmac;
898   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
899   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
900   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
901   size_t esize;
902   size_t res;
903   size_t len;
904   unsigned int N;
905
906   LOG (GNUNET_ERROR_TYPE_DEBUG,
907        "Trying skipped keys\n");
908   hmac = &plaintext_header.hmac;
909   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
910
911   /* Find a correct Header Key */
912   valid_HK = NULL;
913   for (key = ax->skipped_head; NULL != key; key = key->next)
914   {
915     t_hmac (&src->ax_header,
916             sizeof (struct GNUNET_CADET_AxHeader) + esize,
917             0,
918             &key->HK,
919             hmac);
920     if (0 == memcmp (hmac,
921                      &src->hmac,
922                      sizeof (*hmac)))
923     {
924       valid_HK = &key->HK;
925       break;
926     }
927   }
928   if (NULL == key)
929     return -1;
930
931   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
932   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
933   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
934   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
935
936   /* Decrypt header */
937   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
938                                      &key->HK,
939                                      NULL, 0,
940                                      NULL);
941   res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
942                                          sizeof (struct GNUNET_CADET_AxHeader),
943                                          &key->HK,
944                                          &iv,
945                                          &plaintext_header.ax_header.Ns);
946   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
947
948   /* Find the correct message key */
949   N = ntohl (plaintext_header.ax_header.Ns);
950   while ( (NULL != key) &&
951           (N != key->Kn) )
952     key = key->next;
953   if ( (NULL == key) ||
954        (0 != memcmp (&key->HK,
955                      valid_HK,
956                      sizeof (*valid_HK))) )
957     return -1;
958
959   /* Decrypt payload */
960   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
961                                      &key->MK,
962                                      NULL,
963                                      0,
964                                      NULL);
965   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
966                                          len,
967                                          &key->MK,
968                                          &iv,
969                                          dst);
970   delete_skipped_key (ax,
971                       key);
972   return res;
973 }
974
975
976 /**
977  * Delete a key from the list of skipped keys.
978  *
979  * @param ax key material to delete from.
980  * @param HKr Header Key to use.
981  */
982 static void
983 store_skipped_key (struct CadetTunnelAxolotl *ax,
984                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
985 {
986   struct CadetTunnelSkippedKey *key;
987
988   key = GNUNET_new (struct CadetTunnelSkippedKey);
989   key->timestamp = GNUNET_TIME_absolute_get ();
990   key->Kn = ax->Nr;
991   key->HK = ax->HKr;
992   t_hmac_derive_key (&ax->CKr,
993                      &key->MK,
994                      "0",
995                      1);
996   t_hmac_derive_key (&ax->CKr,
997                      &ax->CKr,
998                      "1",
999                      1);
1000   GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1001                                ax->skipped_tail,
1002                                key);
1003   ax->skipped++;
1004   ax->Nr++;
1005 }
1006
1007
1008 /**
1009  * Stage skipped AX keys and calculate the message key.
1010  * Stores each HK and MK for skipped messages.
1011  *
1012  * @param ax key material to use
1013  * @param HKr Header key.
1014  * @param Np Received meesage number.
1015  * @return #GNUNET_OK if keys were stored.
1016  *         #GNUNET_SYSERR if an error ocurred (Np not expected).
1017  */
1018 static int
1019 store_ax_keys (struct CadetTunnelAxolotl *ax,
1020                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1021                uint32_t Np)
1022 {
1023   int gap;
1024
1025   gap = Np - ax->Nr;
1026   LOG (GNUNET_ERROR_TYPE_DEBUG,
1027        "Storing skipped keys [%u, %u)\n",
1028        ax->Nr,
1029        Np);
1030   if (MAX_KEY_GAP < gap)
1031   {
1032     /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1033     /* TODO: start new key exchange on return */
1034     GNUNET_break_op (0);
1035     LOG (GNUNET_ERROR_TYPE_WARNING,
1036          "Got message %u, expected %u+\n",
1037          Np,
1038          ax->Nr);
1039     return GNUNET_SYSERR;
1040   }
1041   if (0 > gap)
1042   {
1043     /* Delayed message: don't store keys, flag to try old keys. */
1044     return GNUNET_SYSERR;
1045   }
1046
1047   while (ax->Nr < Np)
1048     store_skipped_key (ax,
1049                        HKr);
1050
1051   while (ax->skipped > MAX_SKIPPED_KEYS)
1052     delete_skipped_key (ax,
1053                         ax->skipped_tail);
1054   return GNUNET_OK;
1055 }
1056
1057
1058 /**
1059  * Decrypt and verify data with the appropriate tunnel key and verify that the
1060  * data has not been altered since it was sent by the remote peer.
1061  *
1062  * @param ax key material to use
1063  * @param dst Destination for the plaintext.
1064  * @param src Source of the message. Can overlap with @c dst.
1065  * @param size Size of the message.
1066  * @return Size of the decrypted data, -1 if an error was encountered.
1067  */
1068 static ssize_t
1069 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1070                            void *dst,
1071                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1072                            size_t size)
1073 {
1074   struct GNUNET_ShortHashCode msg_hmac;
1075   struct GNUNET_HashCode hmac;
1076   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1077   uint32_t Np;
1078   uint32_t PNp;
1079   size_t esize; /* Size of encryped payload */
1080
1081   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1082
1083   /* Try current HK */
1084   t_hmac (&src->ax_header,
1085           sizeof (struct GNUNET_CADET_AxHeader) + esize,
1086           0, &ax->HKr,
1087           &msg_hmac);
1088   if (0 != memcmp (&msg_hmac,
1089                    &src->hmac,
1090                    sizeof (msg_hmac)))
1091   {
1092     static const char ctx[] = "axolotl ratchet";
1093     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1094     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1095     struct GNUNET_HashCode dh;
1096     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1097
1098     /* Try Next HK */
1099     t_hmac (&src->ax_header,
1100             sizeof (struct GNUNET_CADET_AxHeader) + esize,
1101             0,
1102             &ax->NHKr,
1103             &msg_hmac);
1104     if (0 != memcmp (&msg_hmac,
1105                      &src->hmac,
1106                      sizeof (msg_hmac)))
1107     {
1108       /* Try the skipped keys, if that fails, we're out of luck. */
1109       return try_old_ax_keys (ax,
1110                               dst,
1111                               src,
1112                               size);
1113     }
1114     HK = ax->HKr;
1115     ax->HKr = ax->NHKr;
1116     t_h_decrypt (ax,
1117                  src,
1118                  &plaintext_header);
1119     Np = ntohl (plaintext_header.ax_header.Ns);
1120     PNp = ntohl (plaintext_header.ax_header.PNs);
1121     DHRp = &plaintext_header.ax_header.DHRs;
1122     store_ax_keys (ax,
1123                    &HK,
1124                    PNp);
1125
1126     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1127     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1128                             DHRp,
1129                             &dh);
1130     t_ax_hmac_hash (&ax->RK,
1131                     &hmac,
1132                     &dh, sizeof (dh));
1133     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1134                        ctx, sizeof (ctx),
1135                        &hmac, sizeof (hmac),
1136                        NULL);
1137
1138     /* Commit "purported" keys */
1139     ax->RK = keys[0];
1140     ax->NHKr = keys[1];
1141     ax->CKr = keys[2];
1142     ax->DHRr = *DHRp;
1143     ax->Nr = 0;
1144     ax->ratchet_allowed = GNUNET_YES;
1145   }
1146   else
1147   {
1148     t_h_decrypt (ax,
1149                  src,
1150                  &plaintext_header);
1151     Np = ntohl (plaintext_header.ax_header.Ns);
1152     PNp = ntohl (plaintext_header.ax_header.PNs);
1153   }
1154   if ( (Np != ax->Nr) &&
1155        (GNUNET_OK != store_ax_keys (ax,
1156                                     &ax->HKr,
1157                                     Np)) )
1158   {
1159     /* Try the skipped keys, if that fails, we're out of luck. */
1160     return try_old_ax_keys (ax,
1161                             dst,
1162                             src,
1163                             size);
1164   }
1165
1166   t_ax_decrypt (ax,
1167                 dst,
1168                 &src[1],
1169                 esize);
1170   ax->Nr = Np + 1;
1171   return esize;
1172 }
1173
1174
1175 /**
1176  * Our tunnel became ready for the first time, notify channels
1177  * that have been waiting.
1178  *
1179  * @param cls our tunnel, not used
1180  * @param key unique ID of the channel, not used
1181  * @param value the `struct CadetChannel` to notify
1182  * @return #GNUNET_OK (continue to iterate)
1183  */
1184 static int
1185 notify_tunnel_up_cb (void *cls,
1186                      uint32_t key,
1187                      void *value)
1188 {
1189   struct CadetChannel *ch = value;
1190
1191   GCCH_tunnel_up (ch);
1192   return GNUNET_OK;
1193 }
1194
1195
1196 /**
1197  * Change the tunnel encryption state.
1198  * If the encryption state changes to OK, stop the rekey task.
1199  *
1200  * @param t Tunnel whose encryption state to change, or NULL.
1201  * @param state New encryption state.
1202  */
1203 void
1204 GCT_change_estate (struct CadetTunnel *t,
1205                    enum CadetTunnelEState state)
1206 {
1207   enum CadetTunnelEState old = t->estate;
1208
1209   t->estate = state;
1210   LOG (GNUNET_ERROR_TYPE_DEBUG,
1211        "Tunnel %s estate changed from %d to %d\n",
1212        GCT_2s (t),
1213        old,
1214        state);
1215
1216   if ( (CADET_TUNNEL_KEY_OK != old) &&
1217        (CADET_TUNNEL_KEY_OK == t->estate) )
1218   {
1219     if (NULL != t->kx_task)
1220     {
1221       GNUNET_SCHEDULER_cancel (t->kx_task);
1222       t->kx_task = NULL;
1223     }
1224     if (CADET_TUNNEL_KEY_REKEY != old)
1225     {
1226       /* notify all channels that have been waiting */
1227       GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1228                                                &notify_tunnel_up_cb,
1229                                                t);
1230     }
1231
1232     /* FIXME: schedule rekey task! */
1233   }
1234 }
1235
1236
1237 /**
1238  * Send a KX message.
1239  *
1240  * FIXME: does not take care of sender-authentication yet!
1241  *
1242  * @param t Tunnel on which to send it.
1243  * @param ax axolotl key context to use
1244  * @param force_reply Force the other peer to reply with a KX message.
1245  */
1246 static void
1247 send_kx (struct CadetTunnel *t,
1248          struct CadetTunnelAxolotl *ax,
1249          int force_reply)
1250 {
1251   struct CadetTConnection *ct;
1252   struct CadetConnection *cc;
1253   struct GNUNET_MQ_Envelope *env;
1254   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1255   enum GNUNET_CADET_KX_Flags flags;
1256
1257   ct = get_ready_connection (t);
1258   if (NULL == ct)
1259   {
1260     LOG (GNUNET_ERROR_TYPE_DEBUG,
1261          "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1262          GCT_2s (t));
1263     return;
1264   }
1265   cc = ct->cc;
1266   LOG (GNUNET_ERROR_TYPE_DEBUG,
1267        "Sending KX on tunnel %s using connection %s\n",
1268        GCT_2s (t),
1269        GCC_2s (ct->cc));
1270
1271   // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1272   env = GNUNET_MQ_msg (msg,
1273                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1274   flags = GNUNET_CADET_KX_FLAG_NONE;
1275   if (GNUNET_YES == force_reply)
1276     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1277   msg->flags = htonl (flags);
1278   msg->cid = *GCC_get_id (cc);
1279   GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1280                                       &msg->ephemeral_key);
1281   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1282                                       &msg->ratchet_key);
1283   ct->is_ready = GNUNET_NO;
1284   GCC_transmit (cc,
1285                 env);
1286   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1287   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1288   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1289     GCT_change_estate (t,
1290                        CADET_TUNNEL_KEY_SENT);
1291 }
1292
1293
1294 /**
1295  * Cleanup state used by @a ax.
1296  *
1297  * @param ax state to free, but not memory of @a ax itself
1298  */
1299 static void
1300 cleanup_ax (struct CadetTunnelAxolotl *ax)
1301 {
1302   while (NULL != ax->skipped_head)
1303     delete_skipped_key (ax,
1304                         ax->skipped_head);
1305   GNUNET_assert (0 == ax->skipped);
1306   GNUNET_free_non_null (ax->kx_0);
1307   GNUNET_free_non_null (ax->DHRs);
1308 }
1309
1310
1311 /**
1312  * Handle KX message that lacks authentication (and which will thus
1313  * only be considered authenticated after we respond with our own
1314  * KX_AUTH and finally successfully decrypt payload).
1315  *
1316  * @param ct connection/tunnel combo that received encrypted message
1317  * @param msg the key exchange message
1318  */
1319 void
1320 GCT_handle_kx (struct CadetTConnection *ct,
1321                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1322 {
1323   struct CadetTunnel *t = ct->t;
1324   struct CadetTunnelAxolotl *ax;
1325   struct GNUNET_HashCode key_material[3];
1326   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1327   const char salt[] = "CADET Axolotl salt";
1328   const struct GNUNET_PeerIdentity *pid;
1329   int am_I_alice;
1330
1331   /* We only keep ONE unverified KX around, so if there is an existing one,
1332      clean it up. */
1333   if (NULL != t->unverified_ax)
1334   {
1335     LOG (GNUNET_ERROR_TYPE_DEBUG,
1336          "Dropping old unverified KX state, got a fresh one.\n",
1337          t->unverified_attempts);
1338     cleanup_ax (t->unverified_ax);
1339     memset (t->unverified_ax,
1340             0,
1341             sizeof (struct CadetTunnelAxolotl));
1342     new_ephemeral (t->unverified_ax);
1343     t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1344   }
1345   else
1346   {
1347     t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1348     new_ephemeral (t->unverified_ax);
1349     t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1350   }
1351   t->unverified_attempts = 0;
1352   ax = t->unverified_ax;
1353
1354   pid = GCP_get_id (t->destination);
1355   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1356                                            pid))
1357     am_I_alice = GNUNET_YES;
1358   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1359                                                 pid))
1360     am_I_alice = GNUNET_NO;
1361   else
1362   {
1363     GNUNET_break_op (0);
1364     return;
1365   }
1366
1367   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1368   {
1369     if (NULL != t->kx_task)
1370     {
1371       GNUNET_SCHEDULER_cancel (t->kx_task);
1372       t->kx_task = NULL;
1373     }
1374     send_kx (t,
1375              ax,
1376              GNUNET_NO);
1377   }
1378
1379   if (0 == memcmp (&ax->DHRr,
1380                    &msg->ratchet_key,
1381                    sizeof (msg->ratchet_key)))
1382   {
1383     LOG (GNUNET_ERROR_TYPE_DEBUG,
1384          " known ratchet key, exit\n");
1385     return;
1386   }
1387
1388   ax->DHRr = msg->ratchet_key;
1389
1390   /* ECDH A B0 */
1391   if (GNUNET_YES == am_I_alice)
1392   {
1393     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1394                               &msg->ephemeral_key, /* B0 */
1395                               &key_material[0]);
1396   }
1397   else
1398   {
1399     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
1400                               &pid->public_key,    /* A */
1401                               &key_material[0]);
1402   }
1403
1404   /* ECDH A0 B */
1405   if (GNUNET_YES == am_I_alice)
1406   {
1407     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
1408                               &pid->public_key,    /* B */
1409                               &key_material[1]);
1410   }
1411   else
1412   {
1413     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1414                               &msg->ephemeral_key, /* B0 */
1415                               &key_material[1]);
1416
1417
1418   }
1419
1420   /* ECDH A0 B0 */
1421   /* (This is the triple-DH, we could probably safely skip this,
1422      as A0/B0 are already in the key material.) */
1423   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
1424                           &msg->ephemeral_key,  /* B0 or A0 */
1425                           &key_material[2]);
1426
1427   /* KDF */
1428   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1429                      salt, sizeof (salt),
1430                      &key_material, sizeof (key_material),
1431                      NULL);
1432
1433   if (0 == memcmp (&ax->RK,
1434                    &keys[0],
1435                    sizeof (ax->RK)))
1436   {
1437     LOG (GNUNET_ERROR_TYPE_INFO,
1438          " known handshake key, exit\n");
1439     return;
1440   }
1441   LOG (GNUNET_ERROR_TYPE_DEBUG,
1442        "Handling KX message for tunnel %s\n",
1443        GCT_2s (t));
1444
1445   ax->RK = keys[0];
1446   if (GNUNET_YES == am_I_alice)
1447   {
1448     ax->HKr = keys[1];
1449     ax->NHKs = keys[2];
1450     ax->NHKr = keys[3];
1451     ax->CKr = keys[4];
1452     ax->ratchet_flag = GNUNET_YES;
1453   }
1454   else
1455   {
1456     ax->HKs = keys[1];
1457     ax->NHKr = keys[2];
1458     ax->NHKs = keys[3];
1459     ax->CKs = keys[4];
1460     ax->ratchet_flag = GNUNET_NO;
1461     ax->ratchet_allowed = GNUNET_NO;
1462     ax->ratchet_counter = 0;
1463     ax->ratchet_expiration
1464       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1465                                   ratchet_time);
1466   }
1467   ax->PNs = 0;
1468   ax->Nr = 0;
1469   ax->Ns = 0;
1470
1471   switch (t->estate)
1472   {
1473   case CADET_TUNNEL_KEY_UNINITIALIZED:
1474     GCT_change_estate (t,
1475                        CADET_TUNNEL_KEY_PING);
1476     break;
1477   case CADET_TUNNEL_KEY_SENT:
1478     /* Got a response to us sending our key; now
1479        we can start transmitting! */
1480     GCT_change_estate (t,
1481                        CADET_TUNNEL_KEY_OK);
1482     if (NULL != t->send_task)
1483       GNUNET_SCHEDULER_cancel (t->send_task);
1484     t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1485                                              t);
1486     break;
1487   case CADET_TUNNEL_KEY_PING:
1488     /* Got a key yet again; need encrypted payload to advance */
1489     break;
1490   case CADET_TUNNEL_KEY_OK:
1491     /* Did not expect a key, but so what. */
1492     break;
1493   case CADET_TUNNEL_KEY_REKEY:
1494     /* Got a key yet again; need encrypted payload to advance */
1495     break;
1496   }
1497 }
1498
1499
1500 /* ************************************** end core crypto ***************************** */
1501
1502
1503 /**
1504  * Compute the next free channel tunnel number for this tunnel.
1505  *
1506  * @param t the tunnel
1507  * @return unused number that can uniquely identify a channel in the tunnel
1508  */
1509 static struct GNUNET_CADET_ChannelTunnelNumber
1510 get_next_free_ctn (struct CadetTunnel *t)
1511 {
1512 #define HIGH_BIT 0x8000000
1513   struct GNUNET_CADET_ChannelTunnelNumber ret;
1514   uint32_t ctn;
1515   int cmp;
1516   uint32_t highbit;
1517
1518   cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1519                                          GCP_get_id (GCT_get_destination (t)));
1520   if (0 < cmp)
1521     highbit = HIGH_BIT;
1522   else if (0 > cmp)
1523     highbit = 0;
1524   else
1525     GNUNET_assert (0); // loopback must never go here!
1526   ctn = ntohl (t->next_ctn.cn);
1527   while (NULL !=
1528          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1529                                               ctn))
1530   {
1531     ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1532   }
1533   t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1534   ret.cn = ntohl (ctn);
1535   return ret;
1536 }
1537
1538
1539 /**
1540  * Add a channel to a tunnel, and notify channel that we are ready
1541  * for transmission if we are already up.  Otherwise that notification
1542  * will be done later in #notify_tunnel_up_cb().
1543  *
1544  * @param t Tunnel.
1545  * @param ch Channel
1546  * @return unique number identifying @a ch within @a t
1547  */
1548 struct GNUNET_CADET_ChannelTunnelNumber
1549 GCT_add_channel (struct CadetTunnel *t,
1550                  struct CadetChannel *ch)
1551 {
1552   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1553
1554   ctn = get_next_free_ctn (t);
1555   GNUNET_assert (GNUNET_YES ==
1556                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1557                                                       ntohl (ctn.cn),
1558                                                       ch,
1559                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1560   LOG (GNUNET_ERROR_TYPE_DEBUG,
1561        "Adding channel %s to tunnel %s\n",
1562        GCCH_2s (ch),
1563        GCT_2s (t));
1564   if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1565        (CADET_TUNNEL_KEY_REKEY == t->estate) )
1566     GCCH_tunnel_up (ch);
1567   return ctn;
1568 }
1569
1570
1571 /**
1572  * We lost a connection, remove it from our list and clean up
1573  * the connection object itself.
1574  *
1575  * @param ct binding of connection to tunnel of the connection that was lost.
1576  */
1577 void
1578 GCT_connection_lost (struct CadetTConnection *ct)
1579 {
1580   struct CadetTunnel *t = ct->t;
1581
1582   GNUNET_CONTAINER_DLL_remove (t->connection_head,
1583                                t->connection_tail,
1584                                ct);
1585   GNUNET_free (ct);
1586 }
1587
1588
1589 /**
1590  * This tunnel is no longer used, destroy it.
1591  *
1592  * @param cls the idle tunnel
1593  */
1594 static void
1595 destroy_tunnel (void *cls)
1596 {
1597   struct CadetTunnel *t = cls;
1598   struct CadetTConnection *ct;
1599   struct CadetTunnelQueueEntry *tq;
1600
1601   t->destroy_task = NULL;
1602   LOG (GNUNET_ERROR_TYPE_DEBUG,
1603        "Destroying idle tunnel %s\n",
1604        GCT_2s (t));
1605   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1606   while (NULL != (ct = t->connection_head))
1607   {
1608     struct CadetConnection *cc;
1609
1610     GNUNET_assert (ct->t == t);
1611     cc = ct->cc;
1612     GCT_connection_lost (ct);
1613     GCC_destroy_without_tunnel (cc);
1614   }
1615   while (NULL != (tq = t->tq_head))
1616   {
1617     if (NULL != tq->cont)
1618       tq->cont (tq->cont_cls);
1619     GCT_send_cancel (tq);
1620   }
1621   GCP_drop_tunnel (t->destination,
1622                    t);
1623   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1624   if (NULL != t->maintain_connections_task)
1625   {
1626     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1627     t->maintain_connections_task = NULL;
1628   }
1629   if (NULL != t->send_task)
1630   {
1631     GNUNET_SCHEDULER_cancel (t->send_task);
1632     t->send_task = NULL;
1633   }
1634   if (NULL != t->kx_task)
1635   {
1636     GNUNET_SCHEDULER_cancel (t->kx_task);
1637     t->kx_task = NULL;
1638   }
1639   GNUNET_MST_destroy (t->mst);
1640   GNUNET_MQ_destroy (t->mq);
1641   cleanup_ax (&t->ax);
1642   if (NULL != t->unverified_ax)
1643   {
1644     cleanup_ax (t->unverified_ax);
1645     GNUNET_free (t->unverified_ax);
1646   }
1647   GNUNET_free (t);
1648 }
1649
1650
1651 /**
1652  * Remove a channel from a tunnel.
1653  *
1654  * @param t Tunnel.
1655  * @param ch Channel
1656  * @param ctn unique number identifying @a ch within @a t
1657  */
1658 void
1659 GCT_remove_channel (struct CadetTunnel *t,
1660                     struct CadetChannel *ch,
1661                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
1662 {
1663   LOG (GNUNET_ERROR_TYPE_DEBUG,
1664        "Removing channel %s from tunnel %s\n",
1665        GCCH_2s (ch),
1666        GCT_2s (t));
1667   GNUNET_assert (GNUNET_YES ==
1668                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1669                                                          ntohl (ctn.cn),
1670                                                          ch));
1671   if (0 ==
1672       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1673   {
1674     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1675                                                     &destroy_tunnel,
1676                                                     t);
1677   }
1678 }
1679
1680
1681 /**
1682  * Destroy remaining channels during shutdown.
1683  *
1684  * @param cls the `struct CadetTunnel` of the channel
1685  * @param key key of the channel
1686  * @param value the `struct CadetChannel`
1687  * @return #GNUNET_OK (continue to iterate)
1688  */
1689 static int
1690 destroy_remaining_channels (void *cls,
1691                             uint32_t key,
1692                             void *value)
1693 {
1694   struct CadetChannel *ch = value;
1695
1696   GCCH_handle_remote_destroy (ch);
1697   return GNUNET_OK;
1698 }
1699
1700
1701 /**
1702  * Destroys the tunnel @a t now, without delay. Used during shutdown.
1703  *
1704  * @param t tunnel to destroy
1705  */
1706 void
1707 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1708 {
1709   GNUNET_assert (GNUNET_YES == shutting_down);
1710   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1711                                            &destroy_remaining_channels,
1712                                            t);
1713   GNUNET_assert (0 ==
1714                  GNUNET_CONTAINER_multihashmap32_size (t->channels));
1715   if (NULL != t->destroy_task)
1716   {
1717     GNUNET_SCHEDULER_cancel (t->destroy_task);
1718     t->destroy_task = NULL;
1719   }
1720   destroy_tunnel (t);
1721 }
1722
1723
1724 /**
1725  * It's been a while, we should try to redo the KX, if we can.
1726  *
1727  * @param cls the `struct CadetTunnel` to do KX for.
1728  */
1729 static void
1730 retry_kx (void *cls)
1731 {
1732   struct CadetTunnel *t = cls;
1733
1734   t->kx_task = NULL;
1735   send_kx (t,
1736            &t->ax,
1737            ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1738              (CADET_TUNNEL_KEY_SENT == t->estate) )
1739            ? GNUNET_YES
1740            : GNUNET_NO);
1741 }
1742
1743
1744 /**
1745  * Send normal payload from queue in @a t via connection @a ct.
1746  * Does nothing if our payload queue is empty.
1747  *
1748  * @param t tunnel to send data from
1749  * @param ct connection to use for transmission (is ready)
1750  */
1751 static void
1752 try_send_normal_payload (struct CadetTunnel *t,
1753                          struct CadetTConnection *ct)
1754 {
1755   struct CadetTunnelQueueEntry *tq;
1756
1757   GNUNET_assert (GNUNET_YES == ct->is_ready);
1758   tq = t->tq_head;
1759   if (NULL == tq)
1760   {
1761     /* no messages pending right now */
1762     LOG (GNUNET_ERROR_TYPE_DEBUG,
1763          "Not sending payload of %s on ready %s (nothing pending)\n",
1764          GCT_2s (t),
1765          GCC_2s (ct->cc));
1766     return;
1767   }
1768   /* ready to send message 'tq' on tunnel 'ct' */
1769   GNUNET_assert (t == tq->t);
1770   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1771                                t->tq_tail,
1772                                tq);
1773   if (NULL != tq->cid)
1774     *tq->cid = *GCC_get_id (ct->cc);
1775   ct->is_ready = GNUNET_NO;
1776   LOG (GNUNET_ERROR_TYPE_DEBUG,
1777        "Sending payload of %s on %s\n",
1778        GCT_2s (t),
1779        GCC_2s (ct->cc));
1780   GCC_transmit (ct->cc,
1781                 tq->env);
1782   if (NULL != tq->cont)
1783     tq->cont (tq->cont_cls);
1784   GNUNET_free (tq);
1785 }
1786
1787
1788 /**
1789  * A connection is @a is_ready for transmission.  Looks at our message
1790  * queue and if there is a message, sends it out via the connection.
1791  *
1792  * @param cls the `struct CadetTConnection` that is @a is_ready
1793  * @param is_ready #GNUNET_YES if connection are now ready,
1794  *                 #GNUNET_NO if connection are no longer ready
1795  */
1796 static void
1797 connection_ready_cb (void *cls,
1798                      int is_ready)
1799 {
1800   struct CadetTConnection *ct = cls;
1801   struct CadetTunnel *t = ct->t;
1802
1803   if (GNUNET_NO == is_ready)
1804   {
1805     LOG (GNUNET_ERROR_TYPE_DEBUG,
1806          "Connection %s no longer ready for tunnel %s\n",
1807          GCC_2s (ct->cc),
1808          GCT_2s (t));
1809     ct->is_ready = GNUNET_NO;
1810     return;
1811   }
1812   ct->is_ready = GNUNET_YES;
1813   LOG (GNUNET_ERROR_TYPE_DEBUG,
1814        "Connection %s now ready for tunnel %s in state %s\n",
1815        GCC_2s (ct->cc),
1816        GCT_2s (t),
1817        estate2s (t->estate));
1818   switch (t->estate)
1819   {
1820   case CADET_TUNNEL_KEY_UNINITIALIZED:
1821     send_kx (t,
1822              &t->ax,
1823              GNUNET_YES);
1824     break;
1825   case CADET_TUNNEL_KEY_SENT:
1826   case CADET_TUNNEL_KEY_PING:
1827     /* opportunity to #retry_kx() starts now, schedule job */
1828     if (NULL == t->kx_task)
1829     {
1830       t->kx_task
1831         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1832                                    &retry_kx,
1833                                    t);
1834     }
1835     break;
1836   case CADET_TUNNEL_KEY_OK:
1837     try_send_normal_payload (t,
1838                              ct);
1839     break;
1840   case CADET_TUNNEL_KEY_REKEY:
1841     send_kx (t,
1842              &t->ax,
1843              GNUNET_NO);
1844     t->estate = CADET_TUNNEL_KEY_OK;
1845     break;
1846   }
1847 }
1848
1849
1850 /**
1851  * Called when either we have a new connection, or a new message in the
1852  * queue, or some existing connection has transmission capacity.  Looks
1853  * at our message queue and if there is a message, picks a connection
1854  * to send it on.
1855  *
1856  * @param cls the `struct CadetTunnel` to process messages on
1857  */
1858 static void
1859 trigger_transmissions (void *cls)
1860 {
1861   struct CadetTunnel *t = cls;
1862   struct CadetTConnection *ct;
1863
1864   t->send_task = NULL;
1865   if (NULL == t->tq_head)
1866     return; /* no messages pending right now */
1867   ct = get_ready_connection (t);
1868   if (NULL == ct)
1869     return; /* no connections ready */
1870   try_send_normal_payload (t,
1871                            ct);
1872 }
1873
1874
1875 /**
1876  * Consider using the path @a p for the tunnel @a t.
1877  * The tunnel destination is at offset @a off in path @a p.
1878  *
1879  * @param cls our tunnel
1880  * @param path a path to our destination
1881  * @param off offset of the destination on path @a path
1882  * @return #GNUNET_YES (should keep iterating)
1883  */
1884 static int
1885 consider_path_cb (void *cls,
1886                   struct CadetPeerPath *path,
1887                   unsigned int off)
1888 {
1889   struct CadetTunnel *t = cls;
1890   unsigned int min_length = UINT_MAX;
1891   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1892   struct CadetTConnection *ct;
1893
1894   /* Check if we care about the new path. */
1895   for (ct = t->connection_head;
1896        NULL != ct;
1897        ct = ct->next)
1898   {
1899     struct CadetPeerPath *ps;
1900
1901     ps = GCC_get_path (ct->cc);
1902     if (ps == path)
1903     {
1904       LOG (GNUNET_ERROR_TYPE_DEBUG,
1905            "Ignoring duplicate path %s for tunnel %s.\n",
1906            GCPP_2s (path),
1907            GCT_2s (t));
1908       return GNUNET_YES; /* duplicate */
1909     }
1910     min_length = GNUNET_MIN (min_length,
1911                              GCPP_get_length (ps));
1912     max_desire = GNUNET_MAX (max_desire,
1913                              GCPP_get_desirability (ps));
1914   }
1915
1916   /* FIXME: not sure we should really just count
1917      'num_connections' here, as they may all have
1918      consistently failed to connect. */
1919
1920   /* We iterate by increasing path length; if we have enough paths and
1921      this one is more than twice as long than what we are currently
1922      using, then ignore all of these super-long ones! */
1923   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1924        (min_length * 2 < off) )
1925   {
1926     LOG (GNUNET_ERROR_TYPE_DEBUG,
1927          "Ignoring paths of length %u, they are way too long.\n",
1928          min_length * 2);
1929     return GNUNET_NO;
1930   }
1931   /* If we have enough paths and this one looks no better, ignore it. */
1932   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1933        (min_length < GCPP_get_length (path)) &&
1934        (max_desire > GCPP_get_desirability (path)) )
1935   {
1936     LOG (GNUNET_ERROR_TYPE_DEBUG,
1937          "Ignoring path (%u/%llu) to %s, got something better already.\n",
1938          GCPP_get_length (path),
1939          (unsigned long long) GCPP_get_desirability (path),
1940          GCP_2s (t->destination));
1941     return GNUNET_YES;
1942   }
1943
1944   /* Path is interesting (better by some metric, or we don't have
1945      enough paths yet). */
1946   ct = GNUNET_new (struct CadetTConnection);
1947   ct->created = GNUNET_TIME_absolute_get ();
1948   ct->t = t;
1949   ct->cc = GCC_create (t->destination,
1950                        path,
1951                        ct,
1952                        &connection_ready_cb,
1953                        ct);
1954   /* FIXME: schedule job to kill connection (and path?)  if it takes
1955      too long to get ready! (And track performance data on how long
1956      other connections took with the tunnel!)
1957      => Note: to be done within 'connection'-logic! */
1958   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1959                                t->connection_tail,
1960                                ct);
1961   t->num_connections++;
1962   LOG (GNUNET_ERROR_TYPE_DEBUG,
1963        "Found interesting path %s for tunnel %s, created connection %s\n",
1964        GCPP_2s (path),
1965        GCT_2s (t),
1966        GCC_2s (ct->cc));
1967   return GNUNET_YES;
1968 }
1969
1970
1971 /**
1972  * Function called to maintain the connections underlying our tunnel.
1973  * Tries to maintain (incl. tear down) connections for the tunnel, and
1974  * if there is a significant change, may trigger transmissions.
1975  *
1976  * Basically, needs to check if there are connections that perform
1977  * badly, and if so eventually kill them and trigger a replacement.
1978  * The strategy is to open one more connection than
1979  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1980  * least-performing one, and then inquire for new ones.
1981  *
1982  * @param cls the `struct CadetTunnel`
1983  */
1984 static void
1985 maintain_connections_cb (void *cls)
1986 {
1987   struct CadetTunnel *t = cls;
1988
1989   t->maintain_connections_task = NULL;
1990   LOG (GNUNET_ERROR_TYPE_DEBUG,
1991        "Performing connection maintenance for tunnel %s.\n",
1992        GCT_2s (t));
1993
1994   (void) GCP_iterate_paths (t->destination,
1995                             &consider_path_cb,
1996                             t);
1997
1998   GNUNET_break (0); // FIXME: implement!
1999 }
2000
2001
2002 /**
2003  * Consider using the path @a p for the tunnel @a t.
2004  * The tunnel destination is at offset @a off in path @a p.
2005  *
2006  * @param cls our tunnel
2007  * @param path a path to our destination
2008  * @param off offset of the destination on path @a path
2009  */
2010 void
2011 GCT_consider_path (struct CadetTunnel *t,
2012                    struct CadetPeerPath *p,
2013                    unsigned int off)
2014 {
2015   (void) consider_path_cb (t,
2016                            p,
2017                            off);
2018 }
2019
2020
2021 /**
2022  * We got a keepalive. Track in statistics.
2023  *
2024  * @param cls the `struct CadetTunnel` for which we decrypted the message
2025  * @param msg  the message we received on the tunnel
2026  */
2027 static void
2028 handle_plaintext_keepalive (void *cls,
2029                             const struct GNUNET_MessageHeader *msg)
2030 {
2031   struct CadetTunnel *t = cls;
2032
2033   LOG (GNUNET_ERROR_TYPE_DEBUG,
2034        "Received KEEPALIVE on tunnel %s\n",
2035        GCT_2s (t));
2036   GNUNET_STATISTICS_update (stats,
2037                             "# keepalives received",
2038                             1,
2039                             GNUNET_NO);
2040 }
2041
2042
2043 /**
2044  * Check that @a msg is well-formed.
2045  *
2046  * @param cls the `struct CadetTunnel` for which we decrypted the message
2047  * @param msg  the message we received on the tunnel
2048  * @return #GNUNET_OK (any variable-size payload goes)
2049  */
2050 static int
2051 check_plaintext_data (void *cls,
2052                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2053 {
2054   return GNUNET_OK;
2055 }
2056
2057
2058 /**
2059  * We received payload data for a channel.  Locate the channel
2060  * and process the data, or return an error if the channel is unknown.
2061  *
2062  * @param cls the `struct CadetTunnel` for which we decrypted the message
2063  * @param msg the message we received on the tunnel
2064  */
2065 static void
2066 handle_plaintext_data (void *cls,
2067                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2068 {
2069   struct CadetTunnel *t = cls;
2070   struct CadetChannel *ch;
2071
2072   ch = lookup_channel (t,
2073                        msg->ctn);
2074   if (NULL == ch)
2075   {
2076     /* We don't know about such a channel, might have been destroyed on our
2077        end in the meantime, or never existed. Send back a DESTROY. */
2078     LOG (GNUNET_ERROR_TYPE_DEBUG,
2079          "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2080          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2081          ntohl (msg->ctn.cn));
2082     GCT_send_channel_destroy (t,
2083                               msg->ctn);
2084     return;
2085   }
2086   GCCH_handle_channel_plaintext_data (ch,
2087                                       msg);
2088 }
2089
2090
2091 /**
2092  * We received an acknowledgement for data we sent on a channel.
2093  * Locate the channel and process it, or return an error if the
2094  * channel is unknown.
2095  *
2096  * @param cls the `struct CadetTunnel` for which we decrypted the message
2097  * @param ack the message we received on the tunnel
2098  */
2099 static void
2100 handle_plaintext_data_ack (void *cls,
2101                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2102 {
2103   struct CadetTunnel *t = cls;
2104   struct CadetChannel *ch;
2105
2106   ch = lookup_channel (t,
2107                        ack->ctn);
2108   if (NULL == ch)
2109   {
2110     /* We don't know about such a channel, might have been destroyed on our
2111        end in the meantime, or never existed. Send back a DESTROY. */
2112     LOG (GNUNET_ERROR_TYPE_DEBUG,
2113          "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2114          ntohl (ack->ctn.cn));
2115     GCT_send_channel_destroy (t,
2116                               ack->ctn);
2117     return;
2118   }
2119   GCCH_handle_channel_plaintext_data_ack (ch,
2120                                           ack);
2121 }
2122
2123
2124 /**
2125  * We have received a request to open a channel to a port from
2126  * another peer.  Creates the incoming channel.
2127  *
2128  * @param cls the `struct CadetTunnel` for which we decrypted the message
2129  * @param copen the message we received on the tunnel
2130  */
2131 static void
2132 handle_plaintext_channel_open (void *cls,
2133                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2134 {
2135   struct CadetTunnel *t = cls;
2136   struct CadetChannel *ch;
2137
2138   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2139                                             ntohl (copen->ctn.cn));
2140   if (NULL != ch)
2141   {
2142     LOG (GNUNET_ERROR_TYPE_DEBUG,
2143          "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2144          GNUNET_h2s (&copen->port),
2145          GCT_2s (t),
2146          GCCH_2s (ch));
2147     GCCH_handle_duplicate_open (ch);
2148     return;
2149   }
2150   LOG (GNUNET_ERROR_TYPE_DEBUG,
2151        "Receicved channel OPEN on port %s from %s\n",
2152        GNUNET_h2s (&copen->port),
2153        GCT_2s (t));
2154   ch = GCCH_channel_incoming_new (t,
2155                                   copen->ctn,
2156                                   &copen->port,
2157                                   ntohl (copen->opt));
2158   GNUNET_assert (GNUNET_OK ==
2159                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2160                                                       ntohl (copen->ctn.cn),
2161                                                       ch,
2162                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2163 }
2164
2165
2166 /**
2167  * Send a DESTROY message via the tunnel.
2168  *
2169  * @param t the tunnel to transmit over
2170  * @param ctn ID of the channel to destroy
2171  */
2172 void
2173 GCT_send_channel_destroy (struct CadetTunnel *t,
2174                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2175 {
2176   struct GNUNET_CADET_ChannelManageMessage msg;
2177
2178   LOG (GNUNET_ERROR_TYPE_DEBUG,
2179        "Sending DESTORY message for channel ID %u\n",
2180        ntohl (ctn.cn));
2181   msg.header.size = htons (sizeof (msg));
2182   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2183   msg.reserved = htonl (0);
2184   msg.ctn = ctn;
2185   GCT_send (t,
2186             &msg.header,
2187             NULL,
2188             NULL);
2189 }
2190
2191
2192 /**
2193  * We have received confirmation from the target peer that the
2194  * given channel could be established (the port is open).
2195  * Tell the client.
2196  *
2197  * @param cls the `struct CadetTunnel` for which we decrypted the message
2198  * @param cm the message we received on the tunnel
2199  */
2200 static void
2201 handle_plaintext_channel_open_ack (void *cls,
2202                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2203 {
2204   struct CadetTunnel *t = cls;
2205   struct CadetChannel *ch;
2206
2207   ch = lookup_channel (t,
2208                        cm->ctn);
2209   if (NULL == ch)
2210   {
2211     /* We don't know about such a channel, might have been destroyed on our
2212        end in the meantime, or never existed. Send back a DESTROY. */
2213     LOG (GNUNET_ERROR_TYPE_DEBUG,
2214          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2215          ntohl (cm->ctn.cn));
2216     GCT_send_channel_destroy (t,
2217                               cm->ctn);
2218     return;
2219   }
2220   LOG (GNUNET_ERROR_TYPE_DEBUG,
2221        "Received channel OPEN_ACK on channel %s from %s\n",
2222        GCCH_2s (ch),
2223        GCT_2s (t));
2224   GCCH_handle_channel_open_ack (ch);
2225 }
2226
2227
2228 /**
2229  * We received a message saying that a channel should be destroyed.
2230  * Pass it on to the correct channel.
2231  *
2232  * @param cls the `struct CadetTunnel` for which we decrypted the message
2233  * @param cm the message we received on the tunnel
2234  */
2235 static void
2236 handle_plaintext_channel_destroy (void *cls,
2237                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2238 {
2239   struct CadetTunnel *t = cls;
2240   struct CadetChannel *ch;
2241
2242   ch = lookup_channel (t,
2243                        cm->ctn);
2244   if (NULL == ch)
2245   {
2246     /* We don't know about such a channel, might have been destroyed on our
2247        end in the meantime, or never existed. */
2248     LOG (GNUNET_ERROR_TYPE_DEBUG,
2249          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2250          ntohl (cm->ctn.cn));
2251     return;
2252   }
2253   LOG (GNUNET_ERROR_TYPE_DEBUG,
2254        "Receicved channel DESTROY on %s from %s\n",
2255        GCCH_2s (ch),
2256        GCT_2s (t));
2257   GCCH_handle_remote_destroy (ch);
2258 }
2259
2260
2261 /**
2262  * Handles a message we decrypted, by injecting it into
2263  * our message queue (which will do the dispatching).
2264  *
2265  * @param cls the `struct CadetTunnel` that got the message
2266  * @param msg the message
2267  * @return #GNUNET_OK (continue to process)
2268  */
2269 static int
2270 handle_decrypted (void *cls,
2271                   const struct GNUNET_MessageHeader *msg)
2272 {
2273   struct CadetTunnel *t = cls;
2274
2275   GNUNET_MQ_inject_message (t->mq,
2276                             msg);
2277   return GNUNET_OK;
2278 }
2279
2280
2281 /**
2282  * Function called if we had an error processing
2283  * an incoming decrypted message.
2284  *
2285  * @param cls the `struct CadetTunnel`
2286  * @param error error code
2287  */
2288 static void
2289 decrypted_error_cb (void *cls,
2290                     enum GNUNET_MQ_Error error)
2291 {
2292   GNUNET_break_op (0);
2293 }
2294
2295
2296 /**
2297  * Create a tunnel to @a destionation.  Must only be called
2298  * from within #GCP_get_tunnel().
2299  *
2300  * @param destination where to create the tunnel to
2301  * @return new tunnel to @a destination
2302  */
2303 struct CadetTunnel *
2304 GCT_create_tunnel (struct CadetPeer *destination)
2305 {
2306   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2307   struct GNUNET_MQ_MessageHandler handlers[] = {
2308     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2309                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2310                              struct GNUNET_MessageHeader,
2311                              t),
2312     GNUNET_MQ_hd_var_size (plaintext_data,
2313                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2314                            struct GNUNET_CADET_ChannelAppDataMessage,
2315                            t),
2316     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2317                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2318                              struct GNUNET_CADET_ChannelDataAckMessage,
2319                              t),
2320     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2321                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2322                              struct GNUNET_CADET_ChannelOpenMessage,
2323                              t),
2324     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2325                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2326                              struct GNUNET_CADET_ChannelManageMessage,
2327                              t),
2328     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2329                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2330                              struct GNUNET_CADET_ChannelManageMessage,
2331                              t),
2332     GNUNET_MQ_handler_end ()
2333   };
2334
2335   new_ephemeral (&t->ax);
2336   t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2337   t->destination = destination;
2338   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2339   t->maintain_connections_task
2340     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2341                                 t);
2342   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2343                                          NULL,
2344                                          NULL,
2345                                          NULL,
2346                                          handlers,
2347                                          &decrypted_error_cb,
2348                                          t);
2349   t->mst = GNUNET_MST_create (&handle_decrypted,
2350                               t);
2351   return t;
2352 }
2353
2354
2355 /**
2356  * Add a @a connection to the @a tunnel.
2357  *
2358  * @param t a tunnel
2359  * @param cid connection identifer to use for the connection
2360  * @param path path to use for the connection
2361  * @return #GNUNET_OK on success,
2362  *         #GNUNET_SYSERR on failure (duplicate connection)
2363  */
2364 int
2365 GCT_add_inbound_connection (struct CadetTunnel *t,
2366                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2367                             struct CadetPeerPath *path)
2368 {
2369   struct CadetTConnection *ct;
2370
2371   ct = GNUNET_new (struct CadetTConnection);
2372   ct->created = GNUNET_TIME_absolute_get ();
2373   ct->t = t;
2374   ct->cc = GCC_create_inbound (t->destination,
2375                                path,
2376                                ct,
2377                                cid,
2378                                &connection_ready_cb,
2379                                ct);
2380   if (NULL == ct->cc)
2381   {
2382     LOG (GNUNET_ERROR_TYPE_DEBUG,
2383          "Tunnel %s refused inbound connection %s (duplicate)\n",
2384          GCT_2s (t),
2385          GCC_2s (ct->cc));
2386     GNUNET_free (ct);
2387     return GNUNET_SYSERR;
2388   }
2389   /* FIXME: schedule job to kill connection (and path?)  if it takes
2390      too long to get ready! (And track performance data on how long
2391      other connections took with the tunnel!)
2392      => Note: to be done within 'connection'-logic! */
2393   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2394                                t->connection_tail,
2395                                ct);
2396   t->num_connections++;
2397   LOG (GNUNET_ERROR_TYPE_DEBUG,
2398        "Tunnel %s has new connection %s\n",
2399        GCT_2s (t),
2400        GCC_2s (ct->cc));
2401   return GNUNET_OK;
2402 }
2403
2404
2405 /**
2406  * Handle encrypted message.
2407  *
2408  * @param ct connection/tunnel combo that received encrypted message
2409  * @param msg the encrypted message to decrypt
2410  */
2411 void
2412 GCT_handle_encrypted (struct CadetTConnection *ct,
2413                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2414 {
2415   struct CadetTunnel *t = ct->t;
2416   uint16_t size = ntohs (msg->header.size);
2417   char cbuf [size] GNUNET_ALIGN;
2418   ssize_t decrypted_size;
2419
2420   LOG (GNUNET_ERROR_TYPE_DEBUG,
2421        "Tunnel %s received %u bytes of encrypted data in state %d\n",
2422        GCT_2s (t),
2423        (unsigned int) size,
2424        t->estate);
2425
2426   switch (t->estate)
2427   {
2428   case CADET_TUNNEL_KEY_UNINITIALIZED:
2429     /* We did not even SEND our KX, how can the other peer
2430        send us encrypted data? */
2431     GNUNET_break_op (0);
2432     return;
2433   case CADET_TUNNEL_KEY_SENT:
2434     /* We did not get the KX of the other peer, but that
2435        might have been lost.  Ask for KX again. */
2436     GNUNET_STATISTICS_update (stats,
2437                               "# received encrypted without KX",
2438                               1,
2439                               GNUNET_NO);
2440     if (NULL != t->kx_task)
2441       GNUNET_SCHEDULER_cancel (t->kx_task);
2442     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2443                                            t);
2444     return;
2445   case CADET_TUNNEL_KEY_PING:
2446     /* Great, first payload, we might graduate to OK */
2447   case CADET_TUNNEL_KEY_OK:
2448   case CADET_TUNNEL_KEY_REKEY:
2449     break;
2450   }
2451
2452   GNUNET_STATISTICS_update (stats,
2453                             "# received encrypted",
2454                             1,
2455                             GNUNET_NO);
2456   decrypted_size = -1;
2457   if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
2458        (CADET_TUNNEL_KEY_REKEY == t->estate) )
2459   {
2460     /* We have well-established key material available,
2461        try that. (This is the common case.) */
2462     decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2463                                                 cbuf,
2464                                                 msg,
2465                                                 size);
2466   }
2467
2468   if ( (-1 == decrypted_size) &&
2469        (NULL != t->unverified_ax) )
2470   {
2471     /* We have un-authenticated KX material available. We should try
2472        this as a back-up option, in case the sender crashed and
2473        switched keys. */
2474     decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2475                                                 cbuf,
2476                                                 msg,
2477                                                 size);
2478     if (-1 != decrypted_size)
2479     {
2480       /* It worked! Treat this as authentication of the AX data! */
2481       cleanup_ax (&t->ax);
2482       t->ax = *t->unverified_ax;
2483       GNUNET_free (t->unverified_ax);
2484       t->unverified_ax = NULL;
2485     }
2486     if (CADET_TUNNEL_KEY_PING == t->estate)
2487     {
2488       /* First time it worked, move tunnel into production! */
2489       GCT_change_estate (t,
2490                          CADET_TUNNEL_KEY_OK);
2491       if (NULL != t->send_task)
2492         GNUNET_SCHEDULER_cancel (t->send_task);
2493       t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2494                                                t);
2495     }
2496   }
2497   if (NULL != t->unverified_ax)
2498   {
2499     /* We had unverified KX material that was useless; so increment
2500        counter and eventually move to ignore it.  Note that we even do
2501        this increment if we successfully decrypted with the old KX
2502        material and thus didn't even both with the new one.  This is
2503        the ideal case, as a malicious injection of bogus KX data
2504        basically only causes us to increment a counter a few times. */
2505     t->unverified_attempts++;
2506     LOG (GNUNET_ERROR_TYPE_DEBUG,
2507          "Failed to decrypt message with unverified KX data %u times\n",
2508          t->unverified_attempts);
2509     if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2510     {
2511       cleanup_ax (t->unverified_ax);
2512       GNUNET_free (t->unverified_ax);
2513       t->unverified_ax = NULL;
2514     }
2515   }
2516
2517   if (-1 == decrypted_size)
2518   {
2519     /* Decryption failed for good, complain. */
2520     GNUNET_break_op (0);
2521     LOG (GNUNET_ERROR_TYPE_WARNING,
2522          "Tunnel %s failed to decrypt and validate encrypted data\n",
2523          GCT_2s (t));
2524     GNUNET_STATISTICS_update (stats,
2525                               "# unable to decrypt",
2526                               1,
2527                               GNUNET_NO);
2528     return;
2529   }
2530
2531   /* The MST will ultimately call #handle_decrypted() on each message. */
2532   GNUNET_break_op (GNUNET_OK ==
2533                    GNUNET_MST_from_buffer (t->mst,
2534                                            cbuf,
2535                                            decrypted_size,
2536                                            GNUNET_YES,
2537                                            GNUNET_NO));
2538 }
2539
2540
2541 /**
2542  * Sends an already built message on a tunnel, encrypting it and
2543  * choosing the best connection if not provided.
2544  *
2545  * @param message Message to send. Function modifies it.
2546  * @param t Tunnel on which this message is transmitted.
2547  * @param cont Continuation to call once message is really sent.
2548  * @param cont_cls Closure for @c cont.
2549  * @return Handle to cancel message
2550  */
2551 struct CadetTunnelQueueEntry *
2552 GCT_send (struct CadetTunnel *t,
2553           const struct GNUNET_MessageHeader *message,
2554           GNUNET_SCHEDULER_TaskCallback cont,
2555           void *cont_cls)
2556 {
2557   struct CadetTunnelQueueEntry *tq;
2558   uint16_t payload_size;
2559   struct GNUNET_MQ_Envelope *env;
2560   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2561
2562   if ( (CADET_TUNNEL_KEY_OK != t->estate) &&
2563        (CADET_TUNNEL_KEY_REKEY != t->estate) )
2564   {
2565     GNUNET_break (0);
2566     return NULL;
2567   }
2568   payload_size = ntohs (message->size);
2569   LOG (GNUNET_ERROR_TYPE_DEBUG,
2570        "Encrypting %u bytes for tunnel %s\n",
2571        (unsigned int) payload_size,
2572        GCT_2s (t));
2573   env = GNUNET_MQ_msg_extra (ax_msg,
2574                              payload_size,
2575                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2576   t_ax_encrypt (&t->ax,
2577                 &ax_msg[1],
2578                 message,
2579                 payload_size);
2580   ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2581   ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2582   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2583                                       &ax_msg->ax_header.DHRs);
2584   t_h_encrypt (&t->ax,
2585                ax_msg);
2586   t_hmac (&ax_msg->ax_header,
2587           sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2588           0,
2589           &t->ax.HKs,
2590           &ax_msg->hmac);
2591
2592   tq = GNUNET_malloc (sizeof (*tq));
2593   tq->t = t;
2594   tq->env = env;
2595   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2596   tq->cont = cont;
2597   tq->cont_cls = cont_cls;
2598   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2599                                     t->tq_tail,
2600                                     tq);
2601   if (NULL != t->send_task)
2602     GNUNET_SCHEDULER_cancel (t->send_task);
2603   t->send_task
2604     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2605                                 t);
2606   return tq;
2607 }
2608
2609
2610 /**
2611  * Cancel a previously sent message while it's in the queue.
2612  *
2613  * ONLY can be called before the continuation given to the send
2614  * function is called. Once the continuation is called, the message is
2615  * no longer in the queue!
2616  *
2617  * @param tq Handle to the queue entry to cancel.
2618  */
2619 void
2620 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2621 {
2622   struct CadetTunnel *t = tq->t;
2623
2624   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2625                                t->tq_tail,
2626                                tq);
2627   GNUNET_MQ_discard (tq->env);
2628   GNUNET_free (tq);
2629 }
2630
2631
2632 /**
2633  * Iterate over all connections of a tunnel.
2634  *
2635  * @param t Tunnel whose connections to iterate.
2636  * @param iter Iterator.
2637  * @param iter_cls Closure for @c iter.
2638  */
2639 void
2640 GCT_iterate_connections (struct CadetTunnel *t,
2641                          GCT_ConnectionIterator iter,
2642                          void *iter_cls)
2643 {
2644   for (struct CadetTConnection *ct = t->connection_head;
2645        NULL != ct;
2646        ct = ct->next)
2647     iter (iter_cls,
2648           ct->cc);
2649 }
2650
2651
2652 /**
2653  * Closure for #iterate_channels_cb.
2654  */
2655 struct ChanIterCls
2656 {
2657   /**
2658    * Function to call.
2659    */
2660   GCT_ChannelIterator iter;
2661
2662   /**
2663    * Closure for @e iter.
2664    */
2665   void *iter_cls;
2666 };
2667
2668
2669 /**
2670  * Helper function for #GCT_iterate_channels.
2671  *
2672  * @param cls the `struct ChanIterCls`
2673  * @param key unused
2674  * @param value a `struct CadetChannel`
2675  * @return #GNUNET_OK
2676  */
2677 static int
2678 iterate_channels_cb (void *cls,
2679                      uint32_t key,
2680                      void *value)
2681 {
2682   struct ChanIterCls *ctx = cls;
2683   struct CadetChannel *ch = value;
2684
2685   ctx->iter (ctx->iter_cls,
2686              ch);
2687   return GNUNET_OK;
2688 }
2689
2690
2691 /**
2692  * Iterate over all channels of a tunnel.
2693  *
2694  * @param t Tunnel whose channels to iterate.
2695  * @param iter Iterator.
2696  * @param iter_cls Closure for @c iter.
2697  */
2698 void
2699 GCT_iterate_channels (struct CadetTunnel *t,
2700                       GCT_ChannelIterator iter,
2701                       void *iter_cls)
2702 {
2703   struct ChanIterCls ctx;
2704
2705   ctx.iter = iter;
2706   ctx.iter_cls = iter_cls;
2707   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2708                                            &iterate_channels_cb,
2709                                            &ctx);
2710
2711 }
2712
2713
2714 /**
2715  * Call #GCCH_debug() on a channel.
2716  *
2717  * @param cls points to the log level to use
2718  * @param key unused
2719  * @param value the `struct CadetChannel` to dump
2720  * @return #GNUNET_OK (continue iteration)
2721  */
2722 static int
2723 debug_channel (void *cls,
2724                uint32_t key,
2725                void *value)
2726 {
2727   const enum GNUNET_ErrorType *level = cls;
2728   struct CadetChannel *ch = value;
2729
2730   GCCH_debug (ch, *level);
2731   return GNUNET_OK;
2732 }
2733
2734
2735 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2736
2737
2738 /**
2739  * Log all possible info about the tunnel state.
2740  *
2741  * @param t Tunnel to debug.
2742  * @param level Debug level to use.
2743  */
2744 void
2745 GCT_debug (const struct CadetTunnel *t,
2746            enum GNUNET_ErrorType level)
2747 {
2748   struct CadetTConnection *iter_c;
2749   int do_log;
2750
2751   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2752                                        "cadet-tun",
2753                                        __FILE__, __FUNCTION__, __LINE__);
2754   if (0 == do_log)
2755     return;
2756
2757   LOG2 (level,
2758         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2759         GCT_2s (t),
2760         estate2s (t->estate),
2761         t->tq_len,
2762         t->num_connections);
2763   LOG2 (level,
2764         "TTT channels:\n");
2765   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2766                                            &debug_channel,
2767                                            &level);
2768   LOG2 (level,
2769         "TTT connections:\n");
2770   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2771     GCC_debug (iter_c->cc,
2772                level);
2773
2774   LOG2 (level,
2775         "TTT TUNNEL END\n");
2776 }
2777
2778
2779 /* end of gnunet-service-cadet-new_tunnels.c */