2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
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.
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.
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.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
27 * - check KX estate machine -- make sure it is never stuck!
28 * - clean up KX logic, including adding sender authentication
29 * - implement connection management (evaluate, kill old ones,
30 * search for new ones)
31 * - when managing connections, distinguish those that
32 * have (recently) had traffic from those that were
33 * never ready (or not recently)
36 #include "gnunet_util_lib.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "cadet_protocol.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
52 * How long do we wait until tearing down an idle tunnel?
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
57 * Yuck, replace by 'offsetof' expression?
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
65 * Maximum number of skipped keys we keep in memory per tunnel.
67 #define MAX_SKIPPED_KEYS 64
70 * Maximum number of keys (and thus ratchet steps) we are willing to
71 * skip before we decide this is either a bogus packet or a DoS-attempt.
73 #define MAX_KEY_GAP 256
77 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
79 struct CadetTunnelSkippedKey
84 struct CadetTunnelSkippedKey *next;
89 struct CadetTunnelSkippedKey *prev;
92 * When was this key stored (for timeout).
94 struct GNUNET_TIME_Absolute timestamp;
99 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
104 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
107 * Key number for a given HK.
114 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
116 struct CadetTunnelAxolotl
119 * A (double linked) list of stored message keys and associated header keys
120 * for "skipped" messages, i.e. messages that have not been
121 * received despite the reception of more recent messages, (head).
123 struct CadetTunnelSkippedKey *skipped_head;
126 * Skipped messages' keys DLL, tail.
128 struct CadetTunnelSkippedKey *skipped_tail;
131 * 32-byte root key which gets updated by DH ratchet.
133 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
136 * 32-byte header key (send).
138 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141 * 32-byte header key (recv)
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146 * 32-byte next header key (send).
148 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
151 * 32-byte next header key (recv).
153 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
156 * 32-byte chain keys (used for forward-secrecy updating, send).
158 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
161 * 32-byte chain keys (used for forward-secrecy updating, recv).
163 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
166 * ECDH for key exchange (A0 / B0).
168 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
171 * ECDH Ratchet key (send).
173 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
176 * ECDH Ratchet key (recv).
178 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
181 * When does this ratchet expire and a new one is triggered.
183 struct GNUNET_TIME_Absolute ratchet_expiration;
186 * Number of elements in @a skipped_head <-> @a skipped_tail.
188 unsigned int skipped;
191 * Message number (reset to 0 with each new ratchet, next message to send).
196 * Message number (reset to 0 with each new ratchet, next message to recv).
201 * Previous message numbers (# of msgs sent under prev ratchet)
206 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
211 * Number of messages recieved since our last ratchet advance.
212 * - If this counter = 0, we cannot send a new ratchet key in next msg.
213 * - If this counter > 0, we can (but don't yet have to) send a new key.
215 unsigned int ratchet_allowed;
218 * Number of messages recieved since our last ratchet advance.
219 * - If this counter = 0, we cannot send a new ratchet key in next msg.
220 * - If this counter > 0, we can (but don't yet have to) send a new key.
222 unsigned int ratchet_counter;
228 * Struct used to save messages in a non-ready tunnel to send once connected.
230 struct CadetTunnelQueueEntry
233 * We are entries in a DLL
235 struct CadetTunnelQueueEntry *next;
238 * We are entries in a DLL
240 struct CadetTunnelQueueEntry *prev;
243 * Tunnel these messages belong in.
245 struct CadetTunnel *t;
248 * Continuation to call once sent (on the channel layer).
250 GNUNET_SCHEDULER_TaskCallback cont;
253 * Closure for @c cont.
258 * Envelope of message to send follows.
260 struct GNUNET_MQ_Envelope *env;
263 * Where to put the connection identifier into the payload
264 * of the message in @e env once we have it?
266 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
271 * Struct containing all information regarding a tunnel to a peer.
276 * Destination of the tunnel.
278 struct CadetPeer *destination;
281 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282 * ephemeral key changes.
284 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
287 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
289 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
292 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
294 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
299 struct CadetTunnelAxolotl ax;
302 * Task scheduled if there are no more channels using the tunnel.
304 struct GNUNET_SCHEDULER_Task *destroy_task;
307 * Task to trim connections if too many are present.
309 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
312 * Task to trigger KX.
314 struct GNUNET_SCHEDULER_Task *kx_task;
317 * Tokenizer for decrypted messages.
319 struct GNUNET_MessageStreamTokenizer *mst;
322 * Dispatcher for decrypted messages only (do NOT use for sending!).
324 struct GNUNET_MQ_Handle *mq;
327 * DLL of connections that are actively used to reach the destination peer.
329 struct CadetTConnection *connection_head;
332 * DLL of connections that are actively used to reach the destination peer.
334 struct CadetTConnection *connection_tail;
337 * Channels inside this tunnel. Maps
338 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
340 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
343 * Channel ID for the next created channel in this tunnel.
345 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
348 * Queued messages, to transmit once tunnel gets connected.
350 struct CadetTunnelQueueEntry *tq_head;
353 * Queued messages, to transmit once tunnel gets connected.
355 struct CadetTunnelQueueEntry *tq_tail;
359 * Ephemeral message in the queue (to avoid queueing more than one).
361 struct CadetConnectionQueue *ephm_hKILL;
364 * Pong message in the queue.
366 struct CadetConnectionQueue *pong_hKILL;
369 * How long do we wait until we retry the KX?
371 struct GNUNET_TIME_Relative kx_retry_delay;
374 * When do we try the next KX?
376 struct GNUNET_TIME_Absolute next_kx_attempt;
379 * Number of connections in the @e connection_head DLL.
381 unsigned int num_connections;
384 * Number of entries in the @e tq_head DLL.
389 * State of the tunnel encryption.
391 enum CadetTunnelEState estate;
397 * Get the static string for the peer this tunnel is directed.
401 * @return Static string the destination peer's ID.
404 GCT_2s (const struct CadetTunnel *t)
409 return "Tunnel(NULL)";
410 GNUNET_snprintf (buf,
413 GNUNET_i2s (GCP_get_id (t->destination)));
419 * Get string description for tunnel encryption state.
421 * @param es Tunnel state.
423 * @return String representation.
426 estate2s (enum CadetTunnelEState es)
432 case CADET_TUNNEL_KEY_UNINITIALIZED:
433 return "CADET_TUNNEL_KEY_UNINITIALIZED";
434 case CADET_TUNNEL_KEY_SENT:
435 return "CADET_TUNNEL_KEY_SENT";
436 case CADET_TUNNEL_KEY_PING:
437 return "CADET_TUNNEL_KEY_PING";
438 case CADET_TUNNEL_KEY_OK:
439 return "CADET_TUNNEL_KEY_OK";
440 case CADET_TUNNEL_KEY_REKEY:
441 return "CADET_TUNNEL_KEY_REKEY";
443 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
450 * Return the peer to which this tunnel goes.
453 * @return the destination of the tunnel
456 GCT_get_destination (struct CadetTunnel *t)
458 return t->destination;
463 * Count channels of a tunnel.
465 * @param t Tunnel on which to count.
467 * @return Number of channels.
470 GCT_count_channels (struct CadetTunnel *t)
472 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
477 * Lookup a channel by its @a ctn.
479 * @param t tunnel to look in
480 * @param ctn number of channel to find
481 * @return NULL if channel does not exist
483 struct CadetChannel *
484 lookup_channel (struct CadetTunnel *t,
485 struct GNUNET_CADET_ChannelTunnelNumber ctn)
487 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
493 * Count all created connections of a tunnel. Not necessarily ready connections!
495 * @param t Tunnel on which to count.
497 * @return Number of connections created, either being established or ready.
500 GCT_count_any_connections (struct CadetTunnel *t)
502 return t->num_connections;
507 * Find first connection that is ready in the list of
508 * our connections. Picks ready connections round-robin.
510 * @param t tunnel to search
511 * @return NULL if we have no connection that is ready
513 static struct CadetTConnection *
514 get_ready_connection (struct CadetTunnel *t)
516 for (struct CadetTConnection *pos = t->connection_head;
519 if (GNUNET_YES == pos->is_ready)
521 if (pos != t->connection_tail)
523 /* move 'pos' to the end, so we try other ready connections
524 first next time (round-robin, modulo availability) */
525 GNUNET_CONTAINER_DLL_remove (t->connection_head,
528 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
539 * Get the encryption state of a tunnel.
543 * @return Tunnel's encryption state.
545 enum CadetTunnelEState
546 GCT_get_estate (struct CadetTunnel *t)
553 * Create a new Axolotl ephemeral (ratchet) key.
558 new_ephemeral (struct CadetTunnel *t)
560 GNUNET_free_non_null (t->ax.DHRs);
561 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
567 * Called when either we have a new connection, or a new message in the
568 * queue, or some existing connection has transmission capacity. Looks
569 * at our message queue and if there is a message, picks a connection
572 * @param t tunnel to process messages on
575 trigger_transmissions (struct CadetTunnel *t);
578 /* ************************************** start core crypto ***************************** */
584 * @param plaintext Content to HMAC.
585 * @param size Size of @c plaintext.
586 * @param iv Initialization vector for the message.
587 * @param key Key to use.
588 * @param hmac[out] Destination to store the HMAC.
591 t_hmac (const void *plaintext,
594 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
595 struct GNUNET_ShortHashCode *hmac)
597 static const char ctx[] = "cadet authentication key";
598 struct GNUNET_CRYPTO_AuthKey auth_key;
599 struct GNUNET_HashCode hash;
601 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
607 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
608 GNUNET_CRYPTO_hmac (&auth_key,
621 * @param key Key to use.
622 * @param hash[out] Resulting HMAC.
623 * @param source Source key material (data to HMAC).
624 * @param len Length of @a source.
627 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
628 struct GNUNET_HashCode *hash,
632 static const char ctx[] = "axolotl HMAC-HASH";
633 struct GNUNET_CRYPTO_AuthKey auth_key;
635 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
639 GNUNET_CRYPTO_hmac (&auth_key,
647 * Derive a symmetric encryption key from an HMAC-HASH.
649 * @param key Key to use for the HMAC.
650 * @param[out] out Key to generate.
651 * @param source Source key material (data to HMAC).
652 * @param len Length of @a source.
655 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
656 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
660 static const char ctx[] = "axolotl derive key";
661 struct GNUNET_HashCode h;
667 GNUNET_CRYPTO_kdf (out, sizeof (*out),
675 * Encrypt data with the axolotl tunnel key.
677 * @param t Tunnel whose key to use.
678 * @param dst Destination with @a size bytes for the encrypted data.
679 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
680 * @param size Size of the buffers at @a src and @a dst
683 t_ax_encrypt (struct CadetTunnel *t,
688 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
689 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
690 struct CadetTunnelAxolotl *ax;
694 ax->ratchet_counter++;
695 if ( (GNUNET_YES == ax->ratchet_allowed) &&
696 ( (ratchet_messages <= ax->ratchet_counter) ||
697 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
699 ax->ratchet_flag = GNUNET_YES;
701 if (GNUNET_YES == ax->ratchet_flag)
703 /* Advance ratchet */
704 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
705 struct GNUNET_HashCode dh;
706 struct GNUNET_HashCode hmac;
707 static const char ctx[] = "axolotl ratchet";
712 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
713 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
716 t_ax_hmac_hash (&ax->RK,
720 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
722 &hmac, sizeof (hmac),
730 ax->ratchet_flag = GNUNET_NO;
731 ax->ratchet_allowed = GNUNET_NO;
732 ax->ratchet_counter = 0;
733 ax->ratchet_expiration
734 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
738 t_hmac_derive_key (&ax->CKs,
742 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
747 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
752 GNUNET_assert (size == out_size);
753 t_hmac_derive_key (&ax->CKs,
761 * Decrypt data with the axolotl tunnel key.
763 * @param t Tunnel whose key to use.
764 * @param dst Destination for the decrypted data, must contain @a size bytes.
765 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
766 * @param size Size of the @a src and @a dst buffers
769 t_ax_decrypt (struct CadetTunnel *t,
774 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
775 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
776 struct CadetTunnelAxolotl *ax;
780 t_hmac_derive_key (&ax->CKr,
784 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
788 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
789 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
794 GNUNET_assert (out_size == size);
795 t_hmac_derive_key (&ax->CKr,
803 * Encrypt header with the axolotl header key.
805 * @param t Tunnel whose key to use.
806 * @param msg Message whose header to encrypt.
809 t_h_encrypt (struct CadetTunnel *t,
810 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
812 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
813 struct CadetTunnelAxolotl *ax;
817 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
821 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
826 GNUNET_assert (AX_HEADER_SIZE == out_size);
831 * Decrypt header with the current axolotl header key.
833 * @param t Tunnel whose current ax HK to use.
834 * @param src Message whose header to decrypt.
835 * @param dst Where to decrypt header to.
838 t_h_decrypt (struct CadetTunnel *t,
839 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
840 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
842 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
843 struct CadetTunnelAxolotl *ax;
847 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
851 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
856 GNUNET_assert (AX_HEADER_SIZE == out_size);
861 * Delete a key from the list of skipped keys.
863 * @param t Tunnel to delete from.
864 * @param key Key to delete.
867 delete_skipped_key (struct CadetTunnel *t,
868 struct CadetTunnelSkippedKey *key)
870 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
879 * Decrypt and verify data with the appropriate tunnel key and verify that the
880 * data has not been altered since it was sent by the remote peer.
882 * @param t Tunnel whose key to use.
883 * @param dst Destination for the plaintext.
884 * @param src Source of the message. Can overlap with @c dst.
885 * @param size Size of the message.
886 * @return Size of the decrypted data, -1 if an error was encountered.
889 try_old_ax_keys (struct CadetTunnel *t,
891 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
894 struct CadetTunnelSkippedKey *key;
895 struct GNUNET_ShortHashCode *hmac;
896 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
897 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
898 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
904 LOG (GNUNET_ERROR_TYPE_DEBUG,
905 "Trying skipped keys\n");
906 hmac = &plaintext_header.hmac;
907 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
909 /* Find a correct Header Key */
911 for (key = t->ax.skipped_head; NULL != key; key = key->next)
914 AX_HEADER_SIZE + esize,
918 if (0 == memcmp (hmac,
929 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
930 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
931 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
932 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
935 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
939 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
943 &plaintext_header.Ns);
944 GNUNET_assert (AX_HEADER_SIZE == res);
946 /* Find the correct message key */
947 N = ntohl (plaintext_header.Ns);
948 while ( (NULL != key) &&
951 if ( (NULL == key) ||
952 (0 != memcmp (&key->HK,
954 sizeof (*valid_HK))) )
957 /* Decrypt payload */
958 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
963 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
968 delete_skipped_key (t,
975 * Delete a key from the list of skipped keys.
977 * @param t Tunnel to delete from.
978 * @param HKr Header Key to use.
981 store_skipped_key (struct CadetTunnel *t,
982 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
984 struct CadetTunnelSkippedKey *key;
986 key = GNUNET_new (struct CadetTunnelSkippedKey);
987 key->timestamp = GNUNET_TIME_absolute_get ();
990 t_hmac_derive_key (&t->ax.CKr,
994 t_hmac_derive_key (&t->ax.CKr,
998 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1007 * Stage skipped AX keys and calculate the message key.
1008 * Stores each HK and MK for skipped messages.
1010 * @param t Tunnel where to stage the keys.
1011 * @param HKr Header key.
1012 * @param Np Received meesage number.
1013 * @return #GNUNET_OK if keys were stored.
1014 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1017 store_ax_keys (struct CadetTunnel *t,
1018 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1023 gap = Np - t->ax.Nr;
1024 LOG (GNUNET_ERROR_TYPE_DEBUG,
1025 "Storing skipped keys [%u, %u)\n",
1028 if (MAX_KEY_GAP < gap)
1030 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1031 /* TODO: start new key exchange on return */
1032 GNUNET_break_op (0);
1033 LOG (GNUNET_ERROR_TYPE_WARNING,
1034 "Got message %u, expected %u+\n",
1037 return GNUNET_SYSERR;
1041 /* Delayed message: don't store keys, flag to try old keys. */
1042 return GNUNET_SYSERR;
1045 while (t->ax.Nr < Np)
1046 store_skipped_key (t,
1049 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1050 delete_skipped_key (t,
1051 t->ax.skipped_tail);
1057 * Decrypt and verify data with the appropriate tunnel key and verify that the
1058 * data has not been altered since it was sent by the remote peer.
1060 * @param t Tunnel whose key to use.
1061 * @param dst Destination for the plaintext.
1062 * @param src Source of the message. Can overlap with @c dst.
1063 * @param size Size of the message.
1064 * @return Size of the decrypted data, -1 if an error was encountered.
1067 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1069 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1072 struct CadetTunnelAxolotl *ax;
1073 struct GNUNET_ShortHashCode msg_hmac;
1074 struct GNUNET_HashCode hmac;
1075 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1078 size_t esize; /* Size of encryped payload */
1080 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1083 /* Try current HK */
1085 AX_HEADER_SIZE + esize,
1088 if (0 != memcmp (&msg_hmac,
1092 static const char ctx[] = "axolotl ratchet";
1093 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1094 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1095 struct GNUNET_HashCode dh;
1096 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1100 AX_HEADER_SIZE + esize,
1104 if (0 != memcmp (&msg_hmac,
1108 /* Try the skipped keys, if that fails, we're out of luck. */
1109 return try_old_ax_keys (t,
1119 Np = ntohl (plaintext_header.Ns);
1120 PNp = ntohl (plaintext_header.PNs);
1121 DHRp = &plaintext_header.DHRs;
1126 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1127 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1130 t_ax_hmac_hash (&ax->RK,
1133 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1135 &hmac, sizeof (hmac),
1138 /* Commit "purported" keys */
1144 ax->ratchet_allowed = GNUNET_YES;
1151 Np = ntohl (plaintext_header.Ns);
1152 PNp = ntohl (plaintext_header.PNs);
1154 if ( (Np != ax->Nr) &&
1155 (GNUNET_OK != store_ax_keys (t,
1159 /* Try the skipped keys, if that fails, we're out of luck. */
1160 return try_old_ax_keys (t,
1176 * Our tunnel became ready for the first time, notify channels
1177 * that have been waiting.
1179 * @param cls our tunnel, not used
1180 * @param key unique ID of the channel, not used
1181 * @param value the `struct CadetChannel` to notify
1182 * @return #GNUNET_OK (continue to iterate)
1185 notify_tunnel_up_cb (void *cls,
1189 struct CadetChannel *ch = value;
1191 GCCH_tunnel_up (ch);
1197 * Change the tunnel encryption state.
1198 * If the encryption state changes to OK, stop the rekey task.
1200 * @param t Tunnel whose encryption state to change, or NULL.
1201 * @param state New encryption state.
1204 GCT_change_estate (struct CadetTunnel *t,
1205 enum CadetTunnelEState state)
1207 enum CadetTunnelEState old = t->estate;
1210 LOG (GNUNET_ERROR_TYPE_DEBUG,
1211 "Tunnel %s estate changed from %d to %d\n",
1216 if ( (CADET_TUNNEL_KEY_OK != old) &&
1217 (CADET_TUNNEL_KEY_OK == t->estate) )
1219 if (NULL != t->kx_task)
1221 GNUNET_SCHEDULER_cancel (t->kx_task);
1224 if (CADET_TUNNEL_KEY_REKEY != old)
1226 /* notify all channels that have been waiting */
1227 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1228 ¬ify_tunnel_up_cb,
1232 /* FIXME: schedule rekey task! */
1238 * Send a KX message.
1240 * FIXME: does not take care of sender-authentication yet!
1242 * @param t Tunnel on which to send it.
1243 * @param force_reply Force the other peer to reply with a KX message.
1246 send_kx (struct CadetTunnel *t,
1249 struct CadetTunnelAxolotl *ax = &t->ax;
1250 struct CadetTConnection *ct;
1251 struct CadetConnection *cc;
1252 struct GNUNET_MQ_Envelope *env;
1253 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1254 enum GNUNET_CADET_KX_Flags flags;
1256 ct = get_ready_connection (t);
1259 LOG (GNUNET_ERROR_TYPE_DEBUG,
1260 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1265 LOG (GNUNET_ERROR_TYPE_DEBUG,
1266 "Sending KX on tunnel %s using connection %s\n",
1270 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1271 env = GNUNET_MQ_msg (msg,
1272 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1273 flags = GNUNET_CADET_KX_FLAG_NONE;
1274 if (GNUNET_YES == force_reply)
1275 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1276 msg->flags = htonl (flags);
1277 msg->cid = *GCC_get_id (cc);
1278 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1279 &msg->ephemeral_key);
1280 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1282 ct->is_ready = GNUNET_NO;
1285 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1286 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1287 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1288 GCT_change_estate (t,
1289 CADET_TUNNEL_KEY_SENT);
1294 * Handle KX message.
1296 * FIXME: sender-authentication in KX is missing!
1298 * @param ct connection/tunnel combo that received encrypted message
1299 * @param msg the key exchange message
1302 GCT_handle_kx (struct CadetTConnection *ct,
1303 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1305 struct CadetTunnel *t = ct->t;
1306 struct CadetTunnelAxolotl *ax = &t->ax;
1307 struct GNUNET_HashCode key_material[3];
1308 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1309 const char salt[] = "CADET Axolotl salt";
1310 const struct GNUNET_PeerIdentity *pid;
1313 pid = GCP_get_id (t->destination);
1314 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1316 am_I_alice = GNUNET_YES;
1317 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1319 am_I_alice = GNUNET_NO;
1322 GNUNET_break_op (0);
1326 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1328 if (NULL != t->kx_task)
1330 GNUNET_SCHEDULER_cancel (t->kx_task);
1337 if (0 == memcmp (&ax->DHRr,
1339 sizeof (msg->ratchet_key)))
1341 LOG (GNUNET_ERROR_TYPE_DEBUG,
1342 " known ratchet key, exit\n");
1346 ax->DHRr = msg->ratchet_key;
1349 if (GNUNET_YES == am_I_alice)
1351 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1352 &msg->ephemeral_key, /* B0 */
1357 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1358 &pid->public_key, /* A */
1363 if (GNUNET_YES == am_I_alice)
1365 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1366 &pid->public_key, /* B */
1371 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1372 &msg->ephemeral_key, /* B0 */
1379 /* (This is the triple-DH, we could probably safely skip this,
1380 as A0/B0 are already in the key material.) */
1381 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1382 &msg->ephemeral_key, /* B0 or A0 */
1386 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1387 salt, sizeof (salt),
1388 &key_material, sizeof (key_material),
1391 if (0 == memcmp (&ax->RK,
1395 LOG (GNUNET_ERROR_TYPE_INFO,
1396 " known handshake key, exit\n");
1399 LOG (GNUNET_ERROR_TYPE_DEBUG,
1400 "Handling KX message for tunnel %s\n",
1404 if (GNUNET_YES == am_I_alice)
1410 ax->ratchet_flag = GNUNET_YES;
1418 ax->ratchet_flag = GNUNET_NO;
1419 ax->ratchet_allowed = GNUNET_NO;
1420 ax->ratchet_counter = 0;
1421 ax->ratchet_expiration
1422 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1431 case CADET_TUNNEL_KEY_UNINITIALIZED:
1432 GCT_change_estate (t,
1433 CADET_TUNNEL_KEY_PING);
1435 case CADET_TUNNEL_KEY_SENT:
1436 /* Got a response to us sending our key; now
1437 we can start transmitting! */
1438 GCT_change_estate (t,
1439 CADET_TUNNEL_KEY_OK);
1440 trigger_transmissions (t);
1442 case CADET_TUNNEL_KEY_PING:
1443 /* Got a key yet again; need encrypted payload to advance */
1445 case CADET_TUNNEL_KEY_OK:
1446 /* Did not expect a key, but so what. */
1448 case CADET_TUNNEL_KEY_REKEY:
1449 /* Got a key yet again; need encrypted payload to advance */
1455 /* ************************************** end core crypto ***************************** */
1459 * Compute the next free channel tunnel number for this tunnel.
1461 * @param t the tunnel
1462 * @return unused number that can uniquely identify a channel in the tunnel
1464 static struct GNUNET_CADET_ChannelTunnelNumber
1465 get_next_free_ctn (struct CadetTunnel *t)
1467 struct GNUNET_CADET_ChannelTunnelNumber ret;
1470 /* FIXME: this logic does NOT prevent both ends of the
1471 channel from picking the same CTN!
1472 Need to reserve one bit of the CTN for the
1473 direction, i.e. which side established the connection! */
1474 ctn = ntohl (t->next_ctn.cn);
1476 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1479 t->next_ctn.cn = htonl (ctn + 1);
1480 ret.cn = ntohl (ctn);
1486 * Add a channel to a tunnel, and notify channel that we are ready
1487 * for transmission if we are already up. Otherwise that notification
1488 * will be done later in #notify_tunnel_up_cb().
1492 * @return unique number identifying @a ch within @a t
1494 struct GNUNET_CADET_ChannelTunnelNumber
1495 GCT_add_channel (struct CadetTunnel *t,
1496 struct CadetChannel *ch)
1498 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1500 ctn = get_next_free_ctn (t);
1501 GNUNET_assert (GNUNET_YES ==
1502 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1505 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1506 LOG (GNUNET_ERROR_TYPE_DEBUG,
1507 "Adding channel %s to tunnel %s\n",
1510 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1511 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1512 GCCH_tunnel_up (ch);
1518 * This tunnel is no longer used, destroy it.
1520 * @param cls the idle tunnel
1523 destroy_tunnel (void *cls)
1525 struct CadetTunnel *t = cls;
1526 struct CadetTConnection *ct;
1527 struct CadetTunnelQueueEntry *tq;
1529 t->destroy_task = NULL;
1530 LOG (GNUNET_ERROR_TYPE_DEBUG,
1531 "Destroying idle tunnel %s\n",
1533 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1534 while (NULL != (ct = t->connection_head))
1536 GNUNET_assert (ct->t == t);
1537 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1540 GCC_destroy (ct->cc);
1543 while (NULL != (tq = t->tq_head))
1545 if (NULL != tq->cont)
1546 tq->cont (tq->cont_cls);
1547 GCT_send_cancel (tq);
1549 GCP_drop_tunnel (t->destination,
1551 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1552 if (NULL != t->maintain_connections_task)
1554 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1555 t->maintain_connections_task = NULL;
1557 GNUNET_MST_destroy (t->mst);
1558 GNUNET_MQ_destroy (t->mq);
1559 while (NULL != t->ax.skipped_head)
1560 delete_skipped_key (t,
1561 t->ax.skipped_head);
1562 GNUNET_assert (0 == t->ax.skipped);
1563 GNUNET_free_non_null (t->ax.kx_0);
1564 GNUNET_free_non_null (t->ax.DHRs);
1570 * Remove a channel from a tunnel.
1574 * @param ctn unique number identifying @a ch within @a t
1577 GCT_remove_channel (struct CadetTunnel *t,
1578 struct CadetChannel *ch,
1579 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1581 LOG (GNUNET_ERROR_TYPE_DEBUG,
1582 "Removing channel %s from tunnel %s\n",
1585 GNUNET_assert (GNUNET_YES ==
1586 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1590 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1592 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1600 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1602 * @param t tunnel to destroy
1605 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1608 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1609 if (NULL != t->destroy_task)
1611 GNUNET_SCHEDULER_cancel (t->destroy_task);
1612 t->destroy_task = NULL;
1619 * It's been a while, we should try to redo the KX, if we can.
1621 * @param cls the `struct CadetTunnel` to do KX for.
1624 retry_kx (void *cls)
1626 struct CadetTunnel *t = cls;
1630 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1631 (CADET_TUNNEL_KEY_SENT == t->estate) )
1638 * Send normal payload from queue in @a t via connection @a ct.
1639 * Does nothing if our payload queue is empty.
1641 * @param t tunnel to send data from
1642 * @param ct connection to use for transmission (is ready)
1645 try_send_normal_payload (struct CadetTunnel *t,
1646 struct CadetTConnection *ct)
1648 struct CadetTunnelQueueEntry *tq;
1650 GNUNET_assert (GNUNET_YES == ct->is_ready);
1654 /* no messages pending right now */
1655 LOG (GNUNET_ERROR_TYPE_DEBUG,
1656 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1661 /* ready to send message 'tq' on tunnel 'ct' */
1662 GNUNET_assert (t == tq->t);
1663 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1666 if (NULL != tq->cid)
1667 *tq->cid = *GCC_get_id (ct->cc);
1668 ct->is_ready = GNUNET_NO;
1669 LOG (GNUNET_ERROR_TYPE_DEBUG,
1670 "Sending payload of tunnel %s on connection %s\n",
1673 GCC_transmit (ct->cc,
1675 if (NULL != tq->cont)
1676 tq->cont (tq->cont_cls);
1682 * A connection is @a is_ready for transmission. Looks at our message
1683 * queue and if there is a message, sends it out via the connection.
1685 * @param cls the `struct CadetTConnection` that is @a is_ready
1686 * @param is_ready #GNUNET_YES if connection are now ready,
1687 * #GNUNET_NO if connection are no longer ready
1690 connection_ready_cb (void *cls,
1693 struct CadetTConnection *ct = cls;
1694 struct CadetTunnel *t = ct->t;
1696 if (GNUNET_NO == is_ready)
1698 LOG (GNUNET_ERROR_TYPE_DEBUG,
1699 "Connection %s no longer ready for tunnel %s\n",
1702 ct->is_ready = GNUNET_NO;
1705 ct->is_ready = GNUNET_YES;
1706 LOG (GNUNET_ERROR_TYPE_DEBUG,
1707 "Connection %s now ready for tunnel %s in state %s\n",
1710 estate2s (t->estate));
1713 case CADET_TUNNEL_KEY_UNINITIALIZED:
1717 case CADET_TUNNEL_KEY_SENT:
1718 case CADET_TUNNEL_KEY_PING:
1719 /* opportunity to #retry_kx() starts now, schedule job */
1720 if (NULL == t->kx_task)
1723 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1728 case CADET_TUNNEL_KEY_OK:
1729 try_send_normal_payload (t,
1732 case CADET_TUNNEL_KEY_REKEY:
1735 t->estate = CADET_TUNNEL_KEY_OK;
1742 * Called when either we have a new connection, or a new message in the
1743 * queue, or some existing connection has transmission capacity. Looks
1744 * at our message queue and if there is a message, picks a connection
1747 * @param t tunnel to process messages on
1750 trigger_transmissions (struct CadetTunnel *t)
1752 struct CadetTConnection *ct;
1754 if (NULL == t->tq_head)
1755 return; /* no messages pending right now */
1756 ct = get_ready_connection (t);
1758 return; /* no connections ready */
1759 try_send_normal_payload (t,
1765 * Consider using the path @a p for the tunnel @a t.
1766 * The tunnel destination is at offset @a off in path @a p.
1768 * @param cls our tunnel
1769 * @param path a path to our destination
1770 * @param off offset of the destination on path @a path
1771 * @return #GNUNET_YES (should keep iterating)
1774 consider_path_cb (void *cls,
1775 struct CadetPeerPath *path,
1778 struct CadetTunnel *t = cls;
1779 unsigned int min_length = UINT_MAX;
1780 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1781 struct CadetTConnection *ct;
1783 /* Check if we care about the new path. */
1784 for (ct = t->connection_head;
1788 struct CadetPeerPath *ps;
1790 ps = GCC_get_path (ct->cc);
1793 LOG (GNUNET_ERROR_TYPE_DEBUG,
1794 "Ignoring duplicate path %s for tunnel %s.\n",
1797 return GNUNET_YES; /* duplicate */
1799 min_length = GNUNET_MIN (min_length,
1800 GCPP_get_length (ps));
1801 max_desire = GNUNET_MAX (max_desire,
1802 GCPP_get_desirability (ps));
1805 /* FIXME: not sure we should really just count
1806 'num_connections' here, as they may all have
1807 consistently failed to connect. */
1809 /* We iterate by increasing path length; if we have enough paths and
1810 this one is more than twice as long than what we are currently
1811 using, then ignore all of these super-long ones! */
1812 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1813 (min_length * 2 < off) )
1815 LOG (GNUNET_ERROR_TYPE_DEBUG,
1816 "Ignoring paths of length %u, they are way too long.\n",
1820 /* If we have enough paths and this one looks no better, ignore it. */
1821 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1822 (min_length < GCPP_get_length (path)) &&
1823 (max_desire > GCPP_get_desirability (path)) )
1825 LOG (GNUNET_ERROR_TYPE_DEBUG,
1826 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1827 GCPP_get_length (path),
1828 (unsigned long long) GCPP_get_desirability (path),
1829 GCP_2s (t->destination));
1833 /* Path is interesting (better by some metric, or we don't have
1834 enough paths yet). */
1835 ct = GNUNET_new (struct CadetTConnection);
1836 ct->created = GNUNET_TIME_absolute_get ();
1838 ct->cc = GCC_create (t->destination,
1841 &connection_ready_cb,
1843 /* FIXME: schedule job to kill connection (and path?) if it takes
1844 too long to get ready! (And track performance data on how long
1845 other connections took with the tunnel!)
1846 => Note: to be done within 'connection'-logic! */
1847 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1850 t->num_connections++;
1851 LOG (GNUNET_ERROR_TYPE_DEBUG,
1852 "Found interesting path %s for tunnel %s, created connection %s\n",
1861 * Function called to maintain the connections underlying our tunnel.
1862 * Tries to maintain (incl. tear down) connections for the tunnel, and
1863 * if there is a significant change, may trigger transmissions.
1865 * Basically, needs to check if there are connections that perform
1866 * badly, and if so eventually kill them and trigger a replacement.
1867 * The strategy is to open one more connection than
1868 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1869 * least-performing one, and then inquire for new ones.
1871 * @param cls the `struct CadetTunnel`
1874 maintain_connections_cb (void *cls)
1876 struct CadetTunnel *t = cls;
1878 t->maintain_connections_task = NULL;
1879 LOG (GNUNET_ERROR_TYPE_DEBUG,
1880 "Performing connection maintenance for tunnel %s.\n",
1883 (void) GCP_iterate_paths (t->destination,
1887 GNUNET_break (0); // FIXME: implement!
1892 * Consider using the path @a p for the tunnel @a t.
1893 * The tunnel destination is at offset @a off in path @a p.
1895 * @param cls our tunnel
1896 * @param path a path to our destination
1897 * @param off offset of the destination on path @a path
1900 GCT_consider_path (struct CadetTunnel *t,
1901 struct CadetPeerPath *p,
1904 (void) consider_path_cb (t,
1913 * @param cls the `struct CadetTunnel` for which we decrypted the message
1914 * @param msg the message we received on the tunnel
1917 handle_plaintext_keepalive (void *cls,
1918 const struct GNUNET_MessageHeader *msg)
1920 struct CadetTunnel *t = cls;
1922 GNUNET_break (0); // FIXME
1927 * Check that @a msg is well-formed.
1929 * @param cls the `struct CadetTunnel` for which we decrypted the message
1930 * @param msg the message we received on the tunnel
1931 * @return #GNUNET_OK (any variable-size payload goes)
1934 check_plaintext_data (void *cls,
1935 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1942 * We received payload data for a channel. Locate the channel
1943 * and process the data, or return an error if the channel is unknown.
1945 * @param cls the `struct CadetTunnel` for which we decrypted the message
1946 * @param msg the message we received on the tunnel
1949 handle_plaintext_data (void *cls,
1950 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1952 struct CadetTunnel *t = cls;
1953 struct CadetChannel *ch;
1955 ch = lookup_channel (t,
1959 /* We don't know about such a channel, might have been destroyed on our
1960 end in the meantime, or never existed. Send back a DESTROY. */
1961 LOG (GNUNET_ERROR_TYPE_DEBUG,
1962 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
1963 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
1964 ntohl (msg->ctn.cn));
1965 GCT_send_channel_destroy (t,
1969 GCCH_handle_channel_plaintext_data (ch,
1975 * We received an acknowledgement for data we sent on a channel.
1976 * Locate the channel and process it, or return an error if the
1977 * channel is unknown.
1979 * @param cls the `struct CadetTunnel` for which we decrypted the message
1980 * @param ack the message we received on the tunnel
1983 handle_plaintext_data_ack (void *cls,
1984 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1986 struct CadetTunnel *t = cls;
1987 struct CadetChannel *ch;
1989 ch = lookup_channel (t,
1993 /* We don't know about such a channel, might have been destroyed on our
1994 end in the meantime, or never existed. Send back a DESTROY. */
1995 LOG (GNUNET_ERROR_TYPE_DEBUG,
1996 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
1997 ntohl (ack->ctn.cn));
1998 GCT_send_channel_destroy (t,
2002 GCCH_handle_channel_plaintext_data_ack (ch,
2008 * We have received a request to open a channel to a port from
2009 * another peer. Creates the incoming channel.
2011 * @param cls the `struct CadetTunnel` for which we decrypted the message
2012 * @param cc the message we received on the tunnel
2015 handle_plaintext_channel_open (void *cls,
2016 const struct GNUNET_CADET_ChannelOpenMessage *cc)
2018 struct CadetTunnel *t = cls;
2019 struct CadetChannel *ch;
2020 struct GNUNET_CADET_ChannelTunnelNumber ctn;
2022 LOG (GNUNET_ERROR_TYPE_DEBUG,
2023 "Receicved channel OPEN on port %s from peer %s\n",
2024 GNUNET_h2s (&cc->port),
2025 GCP_2s (GCT_get_destination (t)));
2026 ctn = get_next_free_ctn (t);
2027 ch = GCCH_channel_incoming_new (t,
2031 GNUNET_assert (GNUNET_OK ==
2032 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2035 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2040 * Send a DESTROY message via the tunnel.
2042 * @param t the tunnel to transmit over
2043 * @param ctn ID of the channel to destroy
2046 GCT_send_channel_destroy (struct CadetTunnel *t,
2047 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2049 struct GNUNET_CADET_ChannelManageMessage msg;
2051 LOG (GNUNET_ERROR_TYPE_DEBUG,
2052 "Sending DESTORY message for channel ID %u\n",
2054 msg.header.size = htons (sizeof (msg));
2055 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2056 msg.reserved = htonl (0);
2066 * We have received confirmation from the target peer that the
2067 * given channel could be established (the port is open).
2070 * @param cls the `struct CadetTunnel` for which we decrypted the message
2071 * @param cm the message we received on the tunnel
2074 handle_plaintext_channel_open_ack (void *cls,
2075 const struct GNUNET_CADET_ChannelManageMessage *cm)
2077 struct CadetTunnel *t = cls;
2078 struct CadetChannel *ch;
2080 ch = lookup_channel (t,
2084 /* We don't know about such a channel, might have been destroyed on our
2085 end in the meantime, or never existed. Send back a DESTROY. */
2086 LOG (GNUNET_ERROR_TYPE_DEBUG,
2087 "Received channel OPEN_ACK for unknown channel, sending DESTROY\n",
2089 GCT_send_channel_destroy (t,
2093 GCCH_handle_channel_open_ack (ch);
2098 * We received a message saying that a channel should be destroyed.
2099 * Pass it on to the correct channel.
2101 * @param cls the `struct CadetTunnel` for which we decrypted the message
2102 * @param cm the message we received on the tunnel
2105 handle_plaintext_channel_destroy (void *cls,
2106 const struct GNUNET_CADET_ChannelManageMessage *cm)
2108 struct CadetTunnel *t = cls;
2109 struct CadetChannel *ch;
2111 ch = lookup_channel (t,
2115 /* We don't know about such a channel, might have been destroyed on our
2116 end in the meantime, or never existed. */
2117 LOG (GNUNET_ERROR_TYPE_DEBUG,
2118 "Received channel DESTORY for unknown channel. Ignoring.\n",
2122 GCCH_handle_remote_destroy (ch);
2127 * Handles a message we decrypted, by injecting it into
2128 * our message queue (which will do the dispatching).
2130 * @param cls the `struct CadetTunnel` that got the message
2131 * @param msg the message
2132 * @return #GNUNET_OK (continue to process)
2135 handle_decrypted (void *cls,
2136 const struct GNUNET_MessageHeader *msg)
2138 struct CadetTunnel *t = cls;
2140 GNUNET_MQ_inject_message (t->mq,
2147 * Function called if we had an error processing
2148 * an incoming decrypted message.
2150 * @param cls the `struct CadetTunnel`
2151 * @param error error code
2154 decrypted_error_cb (void *cls,
2155 enum GNUNET_MQ_Error error)
2157 GNUNET_break_op (0);
2162 * Create a tunnel to @a destionation. Must only be called
2163 * from within #GCP_get_tunnel().
2165 * @param destination where to create the tunnel to
2166 * @return new tunnel to @a destination
2168 struct CadetTunnel *
2169 GCT_create_tunnel (struct CadetPeer *destination)
2171 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2172 struct GNUNET_MQ_MessageHandler handlers[] = {
2173 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2174 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2175 struct GNUNET_MessageHeader,
2177 GNUNET_MQ_hd_var_size (plaintext_data,
2178 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2179 struct GNUNET_CADET_ChannelAppDataMessage,
2181 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2182 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2183 struct GNUNET_CADET_ChannelDataAckMessage,
2185 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2186 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2187 struct GNUNET_CADET_ChannelOpenMessage,
2189 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2190 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2191 struct GNUNET_CADET_ChannelManageMessage,
2193 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2194 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2195 struct GNUNET_CADET_ChannelManageMessage,
2197 GNUNET_MQ_handler_end ()
2201 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2202 t->destination = destination;
2203 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2204 t->maintain_connections_task
2205 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2207 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2212 &decrypted_error_cb,
2214 t->mst = GNUNET_MST_create (&handle_decrypted,
2221 * Add a @a connection to the @a tunnel.
2224 * @param cid connection identifer to use for the connection
2225 * @param path path to use for the connection
2228 GCT_add_inbound_connection (struct CadetTunnel *t,
2229 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2230 struct CadetPeerPath *path)
2232 struct CadetTConnection *ct;
2234 ct = GNUNET_new (struct CadetTConnection);
2235 ct->created = GNUNET_TIME_absolute_get ();
2237 ct->cc = GCC_create_inbound (t->destination,
2241 &connection_ready_cb,
2243 /* FIXME: schedule job to kill connection (and path?) if it takes
2244 too long to get ready! (And track performance data on how long
2245 other connections took with the tunnel!)
2246 => Note: to be done within 'connection'-logic! */
2247 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2250 t->num_connections++;
2251 LOG (GNUNET_ERROR_TYPE_DEBUG,
2252 "Tunnel %s has new connection %s\n",
2259 * Handle encrypted message.
2261 * @param ct connection/tunnel combo that received encrypted message
2262 * @param msg the encrypted message to decrypt
2265 GCT_handle_encrypted (struct CadetTConnection *ct,
2266 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2268 struct CadetTunnel *t = ct->t;
2269 uint16_t size = ntohs (msg->header.size);
2270 char cbuf [size] GNUNET_ALIGN;
2271 ssize_t decrypted_size;
2273 LOG (GNUNET_ERROR_TYPE_DEBUG,
2274 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2276 (unsigned int) size,
2281 case CADET_TUNNEL_KEY_UNINITIALIZED:
2282 /* We did not even SEND our KX, how can the other peer
2283 send us encrypted data? */
2284 GNUNET_break_op (0);
2286 case CADET_TUNNEL_KEY_SENT:
2287 /* We did not get the KX of the other peer, but that
2288 might have been lost. Ask for KX again. */
2289 GNUNET_STATISTICS_update (stats,
2290 "# received encrypted without KX",
2293 if (NULL != t->kx_task)
2294 GNUNET_SCHEDULER_cancel (t->kx_task);
2295 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2298 case CADET_TUNNEL_KEY_PING:
2299 /* Great, first payload, we might graduate to OK */
2300 case CADET_TUNNEL_KEY_OK:
2301 case CADET_TUNNEL_KEY_REKEY:
2305 GNUNET_STATISTICS_update (stats,
2306 "# received encrypted",
2309 decrypted_size = t_ax_decrypt_and_validate (t,
2314 if (-1 == decrypted_size)
2316 GNUNET_break_op (0);
2317 LOG (GNUNET_ERROR_TYPE_WARNING,
2318 "Tunnel %s failed to decrypt and validate encrypted data\n",
2320 GNUNET_STATISTICS_update (stats,
2321 "# unable to decrypt",
2326 if (CADET_TUNNEL_KEY_PING == t->estate)
2328 GCT_change_estate (t,
2329 CADET_TUNNEL_KEY_OK);
2330 trigger_transmissions (t);
2332 /* The MST will ultimately call #handle_decrypted() on each message. */
2333 GNUNET_break_op (GNUNET_OK ==
2334 GNUNET_MST_from_buffer (t->mst,
2343 * Sends an already built message on a tunnel, encrypting it and
2344 * choosing the best connection if not provided.
2346 * @param message Message to send. Function modifies it.
2347 * @param t Tunnel on which this message is transmitted.
2348 * @param cont Continuation to call once message is really sent.
2349 * @param cont_cls Closure for @c cont.
2350 * @return Handle to cancel message. NULL if @c cont is NULL.
2352 struct CadetTunnelQueueEntry *
2353 GCT_send (struct CadetTunnel *t,
2354 const struct GNUNET_MessageHeader *message,
2355 GNUNET_SCHEDULER_TaskCallback cont,
2358 struct CadetTunnelQueueEntry *tq;
2359 uint16_t payload_size;
2360 struct GNUNET_MQ_Envelope *env;
2361 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2363 payload_size = ntohs (message->size);
2364 LOG (GNUNET_ERROR_TYPE_DEBUG,
2365 "Encrypting %u bytes of for tunnel %s\n",
2366 (unsigned int) payload_size,
2368 env = GNUNET_MQ_msg_extra (ax_msg,
2370 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2375 ax_msg->Ns = htonl (t->ax.Ns++);
2376 ax_msg->PNs = htonl (t->ax.PNs);
2377 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2381 t_hmac (&ax_msg->Ns,
2382 AX_HEADER_SIZE + payload_size,
2387 tq = GNUNET_malloc (sizeof (*tq));
2390 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2392 tq->cont_cls = cont_cls;
2393 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2396 trigger_transmissions (t);
2402 * Cancel a previously sent message while it's in the queue.
2404 * ONLY can be called before the continuation given to the send
2405 * function is called. Once the continuation is called, the message is
2406 * no longer in the queue!
2408 * @param tq Handle to the queue entry to cancel.
2411 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2413 struct CadetTunnel *t = tq->t;
2415 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2418 GNUNET_MQ_discard (tq->env);
2424 * Iterate over all connections of a tunnel.
2426 * @param t Tunnel whose connections to iterate.
2427 * @param iter Iterator.
2428 * @param iter_cls Closure for @c iter.
2431 GCT_iterate_connections (struct CadetTunnel *t,
2432 GCT_ConnectionIterator iter,
2435 for (struct CadetTConnection *ct = t->connection_head;
2444 * Closure for #iterate_channels_cb.
2451 GCT_ChannelIterator iter;
2454 * Closure for @e iter.
2461 * Helper function for #GCT_iterate_channels.
2463 * @param cls the `struct ChanIterCls`
2465 * @param value a `struct CadetChannel`
2466 * @return #GNUNET_OK
2469 iterate_channels_cb (void *cls,
2473 struct ChanIterCls *ctx = cls;
2474 struct CadetChannel *ch = value;
2476 ctx->iter (ctx->iter_cls,
2483 * Iterate over all channels of a tunnel.
2485 * @param t Tunnel whose channels to iterate.
2486 * @param iter Iterator.
2487 * @param iter_cls Closure for @c iter.
2490 GCT_iterate_channels (struct CadetTunnel *t,
2491 GCT_ChannelIterator iter,
2494 struct ChanIterCls ctx;
2497 ctx.iter_cls = iter_cls;
2498 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2499 &iterate_channels_cb,
2506 * Call #GCCH_debug() on a channel.
2508 * @param cls points to the log level to use
2510 * @param value the `struct CadetChannel` to dump
2511 * @return #GNUNET_OK (continue iteration)
2514 debug_channel (void *cls,
2518 const enum GNUNET_ErrorType *level = cls;
2519 struct CadetChannel *ch = value;
2521 GCCH_debug (ch, *level);
2526 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2530 * Log all possible info about the tunnel state.
2532 * @param t Tunnel to debug.
2533 * @param level Debug level to use.
2536 GCT_debug (const struct CadetTunnel *t,
2537 enum GNUNET_ErrorType level)
2539 struct CadetTConnection *iter_c;
2542 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2544 __FILE__, __FUNCTION__, __LINE__);
2549 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2551 estate2s (t->estate),
2553 t->num_connections);
2554 #if DUMP_KEYS_TO_STDERR
2555 ax_debug (t->ax, level);
2559 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2563 "TTT connections:\n");
2564 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2565 GCC_debug (iter_c->cc,
2569 "TTT TUNNEL END\n");
2573 /* end of gnunet-service-cadet-new_tunnels.c */