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