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