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_chid;
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)
411 GNUNET_snprintf (buf,
414 GCP_2s (t->destination));
420 * Return the peer to which this tunnel goes.
423 * @return the destination of the tunnel
426 GCT_get_destination (struct CadetTunnel *t)
428 return t->destination;
433 * Count channels of a tunnel.
435 * @param t Tunnel on which to count.
437 * @return Number of channels.
440 GCT_count_channels (struct CadetTunnel *t)
442 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
447 * Lookup a channel by its @a chid.
449 * @param t tunnel to look in
450 * @param chid number of channel to find
451 * @return NULL if channel does not exist
453 struct CadetChannel *
454 lookup_channel (struct CadetTunnel *t,
455 struct GNUNET_CADET_ChannelTunnelNumber chid)
457 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
463 * Count all created connections of a tunnel. Not necessarily ready connections!
465 * @param t Tunnel on which to count.
467 * @return Number of connections created, either being established or ready.
470 GCT_count_any_connections (struct CadetTunnel *t)
472 return t->num_connections;
477 * Find first connection that is ready in the list of
478 * our connections. Picks ready connections round-robin.
480 * @param t tunnel to search
481 * @return NULL if we have no connection that is ready
483 static struct CadetTConnection *
484 get_ready_connection (struct CadetTunnel *t)
486 for (struct CadetTConnection *pos = t->connection_head;
489 if (GNUNET_YES == pos->is_ready)
491 if (pos != t->connection_tail)
493 /* move 'pos' to the end, so we try other ready connections
494 first next time (round-robin, modulo availability) */
495 GNUNET_CONTAINER_DLL_remove (t->connection_head,
498 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
509 * Get the encryption state of a tunnel.
513 * @return Tunnel's encryption state.
515 enum CadetTunnelEState
516 GCT_get_estate (struct CadetTunnel *t)
523 * Create a new Axolotl ephemeral (ratchet) key.
528 new_ephemeral (struct CadetTunnel *t)
530 GNUNET_free_non_null (t->ax.DHRs);
531 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
537 * Called when either we have a new connection, or a new message in the
538 * queue, or some existing connection has transmission capacity. Looks
539 * at our message queue and if there is a message, picks a connection
542 * @param t tunnel to process messages on
545 trigger_transmissions (struct CadetTunnel *t);
548 /* ************************************** start core crypto ***************************** */
554 * @param plaintext Content to HMAC.
555 * @param size Size of @c plaintext.
556 * @param iv Initialization vector for the message.
557 * @param key Key to use.
558 * @param hmac[out] Destination to store the HMAC.
561 t_hmac (const void *plaintext,
564 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
565 struct GNUNET_ShortHashCode *hmac)
567 static const char ctx[] = "cadet authentication key";
568 struct GNUNET_CRYPTO_AuthKey auth_key;
569 struct GNUNET_HashCode hash;
571 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
577 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
578 GNUNET_CRYPTO_hmac (&auth_key,
591 * @param key Key to use.
592 * @param hash[out] Resulting HMAC.
593 * @param source Source key material (data to HMAC).
594 * @param len Length of @a source.
597 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
598 struct GNUNET_HashCode *hash,
602 static const char ctx[] = "axolotl HMAC-HASH";
603 struct GNUNET_CRYPTO_AuthKey auth_key;
605 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
609 GNUNET_CRYPTO_hmac (&auth_key,
617 * Derive a symmetric encryption key from an HMAC-HASH.
619 * @param key Key to use for the HMAC.
620 * @param[out] out Key to generate.
621 * @param source Source key material (data to HMAC).
622 * @param len Length of @a source.
625 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
626 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
630 static const char ctx[] = "axolotl derive key";
631 struct GNUNET_HashCode h;
637 GNUNET_CRYPTO_kdf (out, sizeof (*out),
645 * Encrypt data with the axolotl tunnel key.
647 * @param t Tunnel whose key to use.
648 * @param dst Destination with @a size bytes for the encrypted data.
649 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
650 * @param size Size of the buffers at @a src and @a dst
653 t_ax_encrypt (struct CadetTunnel *t,
658 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
659 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
660 struct CadetTunnelAxolotl *ax;
664 ax->ratchet_counter++;
665 if ( (GNUNET_YES == ax->ratchet_allowed) &&
666 ( (ratchet_messages <= ax->ratchet_counter) ||
667 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
669 ax->ratchet_flag = GNUNET_YES;
671 if (GNUNET_YES == ax->ratchet_flag)
673 /* Advance ratchet */
674 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
675 struct GNUNET_HashCode dh;
676 struct GNUNET_HashCode hmac;
677 static const char ctx[] = "axolotl ratchet";
682 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
683 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
686 t_ax_hmac_hash (&ax->RK,
690 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
692 &hmac, sizeof (hmac),
700 ax->ratchet_flag = GNUNET_NO;
701 ax->ratchet_allowed = GNUNET_NO;
702 ax->ratchet_counter = 0;
703 ax->ratchet_expiration
704 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
708 t_hmac_derive_key (&ax->CKs,
712 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
717 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
722 GNUNET_assert (size == out_size);
723 t_hmac_derive_key (&ax->CKs,
731 * Decrypt data with the axolotl tunnel key.
733 * @param t Tunnel whose key to use.
734 * @param dst Destination for the decrypted data, must contain @a size bytes.
735 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
736 * @param size Size of the @a src and @a dst buffers
739 t_ax_decrypt (struct CadetTunnel *t,
744 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
745 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
746 struct CadetTunnelAxolotl *ax;
750 t_hmac_derive_key (&ax->CKr,
754 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
758 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
759 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
764 GNUNET_assert (out_size == size);
765 t_hmac_derive_key (&ax->CKr,
773 * Encrypt header with the axolotl header key.
775 * @param t Tunnel whose key to use.
776 * @param msg Message whose header to encrypt.
779 t_h_encrypt (struct CadetTunnel *t,
780 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
782 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
783 struct CadetTunnelAxolotl *ax;
787 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
791 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
796 GNUNET_assert (AX_HEADER_SIZE == out_size);
801 * Decrypt header with the current axolotl header key.
803 * @param t Tunnel whose current ax HK to use.
804 * @param src Message whose header to decrypt.
805 * @param dst Where to decrypt header to.
808 t_h_decrypt (struct CadetTunnel *t,
809 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
810 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
812 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
813 struct CadetTunnelAxolotl *ax;
817 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
821 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
826 GNUNET_assert (AX_HEADER_SIZE == out_size);
831 * Delete a key from the list of skipped keys.
833 * @param t Tunnel to delete from.
834 * @param key Key to delete.
837 delete_skipped_key (struct CadetTunnel *t,
838 struct CadetTunnelSkippedKey *key)
840 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
849 * Decrypt and verify data with the appropriate tunnel key and verify that the
850 * data has not been altered since it was sent by the remote peer.
852 * @param t Tunnel whose key to use.
853 * @param dst Destination for the plaintext.
854 * @param src Source of the message. Can overlap with @c dst.
855 * @param size Size of the message.
856 * @return Size of the decrypted data, -1 if an error was encountered.
859 try_old_ax_keys (struct CadetTunnel *t,
861 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
864 struct CadetTunnelSkippedKey *key;
865 struct GNUNET_ShortHashCode *hmac;
866 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
867 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
868 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
874 LOG (GNUNET_ERROR_TYPE_DEBUG,
875 "Trying skipped keys\n");
876 hmac = &plaintext_header.hmac;
877 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
879 /* Find a correct Header Key */
881 for (key = t->ax.skipped_head; NULL != key; key = key->next)
884 AX_HEADER_SIZE + esize,
888 if (0 == memcmp (hmac,
899 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
900 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
901 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
902 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
905 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
909 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
913 &plaintext_header.Ns);
914 GNUNET_assert (AX_HEADER_SIZE == res);
916 /* Find the correct message key */
917 N = ntohl (plaintext_header.Ns);
918 while ( (NULL != key) &&
921 if ( (NULL == key) ||
922 (0 != memcmp (&key->HK,
924 sizeof (*valid_HK))) )
927 /* Decrypt payload */
928 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
933 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
938 delete_skipped_key (t,
945 * Delete a key from the list of skipped keys.
947 * @param t Tunnel to delete from.
948 * @param HKr Header Key to use.
951 store_skipped_key (struct CadetTunnel *t,
952 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
954 struct CadetTunnelSkippedKey *key;
956 key = GNUNET_new (struct CadetTunnelSkippedKey);
957 key->timestamp = GNUNET_TIME_absolute_get ();
960 t_hmac_derive_key (&t->ax.CKr,
964 t_hmac_derive_key (&t->ax.CKr,
968 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
977 * Stage skipped AX keys and calculate the message key.
978 * Stores each HK and MK for skipped messages.
980 * @param t Tunnel where to stage the keys.
981 * @param HKr Header key.
982 * @param Np Received meesage number.
983 * @return #GNUNET_OK if keys were stored.
984 * #GNUNET_SYSERR if an error ocurred (Np not expected).
987 store_ax_keys (struct CadetTunnel *t,
988 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
994 LOG (GNUNET_ERROR_TYPE_DEBUG,
995 "Storing skipped keys [%u, %u)\n",
998 if (MAX_KEY_GAP < gap)
1000 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1001 /* TODO: start new key exchange on return */
1002 GNUNET_break_op (0);
1003 LOG (GNUNET_ERROR_TYPE_WARNING,
1004 "Got message %u, expected %u+\n",
1007 return GNUNET_SYSERR;
1011 /* Delayed message: don't store keys, flag to try old keys. */
1012 return GNUNET_SYSERR;
1015 while (t->ax.Nr < Np)
1016 store_skipped_key (t,
1019 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1020 delete_skipped_key (t,
1021 t->ax.skipped_tail);
1027 * Decrypt and verify data with the appropriate tunnel key and verify that the
1028 * data has not been altered since it was sent by the remote peer.
1030 * @param t Tunnel whose key to use.
1031 * @param dst Destination for the plaintext.
1032 * @param src Source of the message. Can overlap with @c dst.
1033 * @param size Size of the message.
1034 * @return Size of the decrypted data, -1 if an error was encountered.
1037 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1039 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1042 struct CadetTunnelAxolotl *ax;
1043 struct GNUNET_ShortHashCode msg_hmac;
1044 struct GNUNET_HashCode hmac;
1045 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1048 size_t esize; /* Size of encryped payload */
1050 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1053 /* Try current HK */
1055 AX_HEADER_SIZE + esize,
1058 if (0 != memcmp (&msg_hmac,
1062 static const char ctx[] = "axolotl ratchet";
1063 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1064 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1065 struct GNUNET_HashCode dh;
1066 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1070 AX_HEADER_SIZE + esize,
1074 if (0 != memcmp (&msg_hmac,
1078 /* Try the skipped keys, if that fails, we're out of luck. */
1079 return try_old_ax_keys (t,
1089 Np = ntohl (plaintext_header.Ns);
1090 PNp = ntohl (plaintext_header.PNs);
1091 DHRp = &plaintext_header.DHRs;
1096 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1097 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1100 t_ax_hmac_hash (&ax->RK,
1103 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1105 &hmac, sizeof (hmac),
1108 /* Commit "purported" keys */
1114 ax->ratchet_allowed = GNUNET_YES;
1121 Np = ntohl (plaintext_header.Ns);
1122 PNp = ntohl (plaintext_header.PNs);
1124 if ( (Np != ax->Nr) &&
1125 (GNUNET_OK != store_ax_keys (t,
1129 /* Try the skipped keys, if that fails, we're out of luck. */
1130 return try_old_ax_keys (t,
1146 * Change the tunnel encryption state.
1147 * If the encryption state changes to OK, stop the rekey task.
1149 * @param t Tunnel whose encryption state to change, or NULL.
1150 * @param state New encryption state.
1153 GCT_change_estate (struct CadetTunnel *t,
1154 enum CadetTunnelEState state)
1156 enum CadetTunnelEState old = t->estate;
1159 LOG (GNUNET_ERROR_TYPE_DEBUG,
1160 "Tunnel %s estate changed from %d to %d\n",
1165 if ( (CADET_TUNNEL_KEY_OK != old) &&
1166 (CADET_TUNNEL_KEY_OK == t->estate) )
1168 if (NULL != t->kx_task)
1170 GNUNET_SCHEDULER_cancel (t->kx_task);
1173 /* FIXME: schedule rekey task! */
1179 * Send a KX message.
1181 * FIXME: does not take care of sender-authentication yet!
1183 * @param t Tunnel on which to send it.
1184 * @param force_reply Force the other peer to reply with a KX message.
1187 send_kx (struct CadetTunnel *t,
1190 struct CadetTunnelAxolotl *ax = &t->ax;
1191 struct CadetTConnection *ct;
1192 struct CadetConnection *cc;
1193 struct GNUNET_MQ_Envelope *env;
1194 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1195 enum GNUNET_CADET_KX_Flags flags;
1197 ct = get_ready_connection (t);
1202 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1203 env = GNUNET_MQ_msg (msg,
1204 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1205 flags = GNUNET_CADET_KX_FLAG_NONE;
1206 if (GNUNET_YES == force_reply)
1207 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1208 msg->flags = htonl (flags);
1209 msg->cid = *GCC_get_id (cc);
1210 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1211 &msg->ephemeral_key);
1212 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1216 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1217 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1218 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1219 GCT_change_estate (t,
1220 CADET_TUNNEL_KEY_SENT);
1225 * Handle KX message.
1227 * FIXME: sender-authentication in KX is missing!
1229 * @param ct connection/tunnel combo that received encrypted message
1230 * @param msg the key exchange message
1233 GCT_handle_kx (struct CadetTConnection *ct,
1234 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1236 struct CadetTunnel *t = ct->t;
1237 struct CadetTunnelAxolotl *ax = &t->ax;
1238 struct GNUNET_HashCode key_material[3];
1239 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1240 const char salt[] = "CADET Axolotl salt";
1241 const struct GNUNET_PeerIdentity *pid;
1244 pid = GCP_get_id (t->destination);
1245 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1247 am_I_alice = GNUNET_YES;
1248 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1250 am_I_alice = GNUNET_NO;
1253 GNUNET_break_op (0);
1257 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1259 if (NULL != t->kx_task)
1261 GNUNET_SCHEDULER_cancel (t->kx_task);
1268 if (0 == memcmp (&ax->DHRr,
1270 sizeof (msg->ratchet_key)))
1272 LOG (GNUNET_ERROR_TYPE_DEBUG,
1273 " known ratchet key, exit\n");
1277 ax->DHRr = msg->ratchet_key;
1280 if (GNUNET_YES == am_I_alice)
1282 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1283 &msg->ephemeral_key, /* B0 */
1288 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1289 &pid->public_key, /* A */
1294 if (GNUNET_YES == am_I_alice)
1296 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1297 &pid->public_key, /* B */
1302 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1303 &msg->ephemeral_key, /* B0 */
1310 /* (This is the triple-DH, we could probably safely skip this,
1311 as A0/B0 are already in the key material.) */
1312 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1313 &msg->ephemeral_key, /* B0 or A0 */
1317 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1318 salt, sizeof (salt),
1319 &key_material, sizeof (key_material),
1322 if (0 == memcmp (&ax->RK,
1326 LOG (GNUNET_ERROR_TYPE_INFO,
1327 " known handshake key, exit\n");
1331 if (GNUNET_YES == am_I_alice)
1337 ax->ratchet_flag = GNUNET_YES;
1345 ax->ratchet_flag = GNUNET_NO;
1346 ax->ratchet_allowed = GNUNET_NO;
1347 ax->ratchet_counter = 0;
1348 ax->ratchet_expiration
1349 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1358 case CADET_TUNNEL_KEY_UNINITIALIZED:
1359 GCT_change_estate (t,
1360 CADET_TUNNEL_KEY_PING);
1362 case CADET_TUNNEL_KEY_SENT:
1363 /* Got a response to us sending our key; now
1364 we can start transmitting! */
1365 GCT_change_estate (t,
1366 CADET_TUNNEL_KEY_OK);
1367 trigger_transmissions (t);
1369 case CADET_TUNNEL_KEY_PING:
1370 /* Got a key yet again; need encrypted payload to advance */
1372 case CADET_TUNNEL_KEY_OK:
1373 /* Did not expect a key, but so what. */
1375 case CADET_TUNNEL_KEY_REKEY:
1376 /* Got a key yet again; need encrypted payload to advance */
1382 /* ************************************** end core crypto ***************************** */
1386 * Compute the next free channel tunnel number for this tunnel.
1388 * @param t the tunnel
1389 * @return unused number that can uniquely identify a channel in the tunnel
1391 static struct GNUNET_CADET_ChannelTunnelNumber
1392 get_next_free_chid (struct CadetTunnel *t)
1394 struct GNUNET_CADET_ChannelTunnelNumber ret;
1397 /* FIXME: this logic does NOT prevent both ends of the
1398 channel from picking the same CHID!
1399 Need to reserve one bit of the CHID for the
1400 direction, i.e. which side established the connection! */
1401 chid = ntohl (t->next_chid.cn);
1403 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1406 t->next_chid.cn = htonl (chid + 1);
1407 ret.cn = ntohl (chid);
1413 * Add a channel to a tunnel.
1417 * @return unique number identifying @a ch within @a t
1419 struct GNUNET_CADET_ChannelTunnelNumber
1420 GCT_add_channel (struct CadetTunnel *t,
1421 struct CadetChannel *ch)
1423 struct GNUNET_CADET_ChannelTunnelNumber chid;
1425 chid = get_next_free_chid (t);
1426 GNUNET_assert (GNUNET_YES ==
1427 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1430 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1436 * This tunnel is no longer used, destroy it.
1438 * @param cls the idle tunnel
1441 destroy_tunnel (void *cls)
1443 struct CadetTunnel *t = cls;
1444 struct CadetTConnection *ct;
1445 struct CadetTunnelQueueEntry *tqe;
1447 t->destroy_task = NULL;
1448 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1449 while (NULL != (ct = t->connection_head))
1451 GNUNET_assert (ct->t == t);
1452 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1455 GCC_destroy (ct->cc);
1458 while (NULL != (tqe = t->tq_head))
1460 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1463 GNUNET_MQ_discard (tqe->env);
1466 GCP_drop_tunnel (t->destination,
1468 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1469 if (NULL != t->maintain_connections_task)
1471 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1472 t->maintain_connections_task = NULL;
1474 GNUNET_MST_destroy (t->mst);
1475 GNUNET_MQ_destroy (t->mq);
1481 * It's been a while, we should try to redo the KX, if we can.
1483 * @param cls the `struct CadetTunnel` to do KX for.
1486 retry_kx (void *cls)
1488 struct CadetTunnel *t = cls;
1492 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1493 (CADET_TUNNEL_KEY_SENT == t->estate) )
1500 * A connection is @a is_ready for transmission. Looks at our message
1501 * queue and if there is a message, sends it out via the connection.
1503 * @param cls the `struct CadetTConnection` that is @a is_ready
1504 * @param is_ready #GNUNET_YES if connection are now ready,
1505 * #GNUNET_NO if connection are no longer ready
1508 connection_ready_cb (void *cls,
1511 struct CadetTConnection *ct = cls;
1512 struct CadetTunnel *t = ct->t;
1513 struct CadetTunnelQueueEntry *tq = t->tq_head;
1515 if (GNUNET_NO == ct->is_ready)
1517 ct->is_ready = GNUNET_NO;
1520 ct->is_ready = GNUNET_YES;
1523 case CADET_TUNNEL_KEY_UNINITIALIZED:
1527 case CADET_TUNNEL_KEY_SENT:
1528 case CADET_TUNNEL_KEY_PING:
1529 /* opportunity to #retry_kx() starts now, schedule job */
1530 if (NULL == t->kx_task)
1533 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt),
1538 case CADET_TUNNEL_KEY_OK:
1539 /* send normal payload */
1541 return; /* no messages pending right now */
1542 /* ready to send message 'tq' on tunnel 'ct' */
1543 GNUNET_assert (t == tq->t);
1544 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1547 if (NULL != tq->cid)
1548 *tq->cid = *GCC_get_id (ct->cc);
1549 ct->is_ready = GNUNET_NO;
1550 GCC_transmit (ct->cc,
1552 if (NULL != tq->cont)
1553 tq->cont (tq->cont_cls);
1556 case CADET_TUNNEL_KEY_REKEY:
1559 t->estate = CADET_TUNNEL_KEY_OK;
1566 * Called when either we have a new connection, or a new message in the
1567 * queue, or some existing connection has transmission capacity. Looks
1568 * at our message queue and if there is a message, picks a connection
1571 * @param t tunnel to process messages on
1574 trigger_transmissions (struct CadetTunnel *t)
1576 struct CadetTConnection *ct;
1578 if (NULL == t->tq_head)
1579 return; /* no messages pending right now */
1580 ct = get_ready_connection (t);
1582 return; /* no connections ready */
1584 /* FIXME: a bit hackish to do it like this... */
1585 connection_ready_cb (ct,
1591 * Function called to maintain the connections underlying our tunnel.
1592 * Tries to maintain (incl. tear down) connections for the tunnel, and
1593 * if there is a significant change, may trigger transmissions.
1595 * Basically, needs to check if there are connections that perform
1596 * badly, and if so eventually kill them and trigger a replacement.
1597 * The strategy is to open one more connection than
1598 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1599 * least-performing one, and then inquire for new ones.
1601 * @param cls the `struct CadetTunnel`
1604 maintain_connections_cb (void *cls)
1606 struct CadetTunnel *t = cls;
1608 GNUNET_break (0); // FIXME: implement!
1613 * Consider using the path @a p for the tunnel @a t.
1614 * The tunnel destination is at offset @a off in path @a p.
1616 * @param cls our tunnel
1617 * @param path a path to our destination
1618 * @param off offset of the destination on path @a path
1619 * @return #GNUNET_YES (should keep iterating)
1622 consider_path_cb (void *cls,
1623 struct CadetPeerPath *path,
1626 struct CadetTunnel *t = cls;
1627 unsigned int min_length = UINT_MAX;
1628 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1629 struct CadetTConnection *ct;
1631 /* Check if we care about the new path. */
1632 for (ct = t->connection_head;
1636 struct CadetPeerPath *ps;
1638 ps = GCC_get_path (ct->cc);
1640 return GNUNET_YES; /* duplicate */
1641 min_length = GNUNET_MIN (min_length,
1642 GCPP_get_length (ps));
1643 max_desire = GNUNET_MAX (max_desire,
1644 GCPP_get_desirability (ps));
1647 /* FIXME: not sure we should really just count
1648 'num_connections' here, as they may all have
1649 consistently failed to connect. */
1651 /* We iterate by increasing path length; if we have enough paths and
1652 this one is more than twice as long than what we are currently
1653 using, then ignore all of these super-long ones! */
1654 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1655 (min_length * 2 < off) )
1657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1658 "Ignoring paths of length %u, they are way too long.\n",
1662 /* If we have enough paths and this one looks no better, ignore it. */
1663 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1664 (min_length < GCPP_get_length (path)) &&
1665 (max_desire > GCPP_get_desirability (path)) )
1667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1668 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1669 GCPP_get_length (path),
1670 (unsigned long long) GCPP_get_desirability (path),
1671 GCP_2s (t->destination));
1675 /* Path is interesting (better by some metric, or we don't have
1676 enough paths yet). */
1677 ct = GNUNET_new (struct CadetTConnection);
1678 ct->created = GNUNET_TIME_absolute_get ();
1680 ct->cc = GCC_create (t->destination,
1683 &connection_ready_cb,
1685 /* FIXME: schedule job to kill connection (and path?) if it takes
1686 too long to get ready! (And track performance data on how long
1687 other connections took with the tunnel!)
1688 => Note: to be done within 'connection'-logic! */
1689 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1692 t->num_connections++;
1698 * Consider using the path @a p for the tunnel @a t.
1699 * The tunnel destination is at offset @a off in path @a p.
1701 * @param cls our tunnel
1702 * @param path a path to our destination
1703 * @param off offset of the destination on path @a path
1706 GCT_consider_path (struct CadetTunnel *t,
1707 struct CadetPeerPath *p,
1710 (void) consider_path_cb (t,
1719 * @param cls the `struct CadetTunnel` for which we decrypted the message
1720 * @param msg the message we received on the tunnel
1723 handle_plaintext_keepalive (void *cls,
1724 const struct GNUNET_MessageHeader *msg)
1726 struct CadetTunnel *t = cls;
1727 GNUNET_break (0); // FIXME
1732 * Check that @a msg is well-formed.
1734 * @param cls the `struct CadetTunnel` for which we decrypted the message
1735 * @param msg the message we received on the tunnel
1736 * @return #GNUNET_OK (any variable-size payload goes)
1739 check_plaintext_data (void *cls,
1740 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1747 * We received payload data for a channel. Locate the channel
1748 * and process the data, or return an error if the channel is unknown.
1750 * @param cls the `struct CadetTunnel` for which we decrypted the message
1751 * @param msg the message we received on the tunnel
1754 handle_plaintext_data (void *cls,
1755 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1757 struct CadetTunnel *t = cls;
1758 struct CadetChannel *ch;
1760 ch = lookup_channel (t,
1764 /* We don't know about such a channel, might have been destroyed on our
1765 end in the meantime, or never existed. Send back a DESTROY. */
1766 GCT_send_channel_destroy (t,
1770 GCCH_handle_channel_plaintext_data (ch,
1776 * We received an acknowledgement for data we sent on a channel.
1777 * Locate the channel and process it, or return an error if the
1778 * channel is unknown.
1780 * @param cls the `struct CadetTunnel` for which we decrypted the message
1781 * @param ack the message we received on the tunnel
1784 handle_plaintext_data_ack (void *cls,
1785 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1787 struct CadetTunnel *t = cls;
1788 struct CadetChannel *ch;
1790 ch = lookup_channel (t,
1794 /* We don't know about such a channel, might have been destroyed on our
1795 end in the meantime, or never existed. Send back a DESTROY. */
1796 GCT_send_channel_destroy (t,
1800 GCCH_handle_channel_plaintext_data_ack (ch,
1806 * We have received a request to open a channel to a port from
1807 * another peer. Creates the incoming channel.
1809 * @param cls the `struct CadetTunnel` for which we decrypted the message
1810 * @param cc the message we received on the tunnel
1813 handle_plaintext_channel_create (void *cls,
1814 const struct GNUNET_CADET_ChannelOpenMessage *cc)
1816 struct CadetTunnel *t = cls;
1817 struct CadetChannel *ch;
1818 struct GNUNET_CADET_ChannelTunnelNumber chid;
1820 chid = get_next_free_chid (t);
1821 ch = GCCH_channel_incoming_new (t,
1825 GNUNET_assert (GNUNET_OK ==
1826 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1829 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1834 * Send a DESTROY message via the tunnel.
1836 * @param t the tunnel to transmit over
1837 * @param chid ID of the channel to destroy
1840 GCT_send_channel_destroy (struct CadetTunnel *t,
1841 struct GNUNET_CADET_ChannelTunnelNumber chid)
1843 struct GNUNET_CADET_ChannelManageMessage msg;
1845 msg.header.size = htons (sizeof (msg));
1846 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1847 msg.reserved = htonl (0);
1857 * We have received confirmation from the target peer that the
1858 * given channel could be established (the port is open).
1861 * @param cls the `struct CadetTunnel` for which we decrypted the message
1862 * @param cm the message we received on the tunnel
1865 handle_plaintext_channel_ack (void *cls,
1866 const struct GNUNET_CADET_ChannelManageMessage *cm)
1868 struct CadetTunnel *t = cls;
1869 struct CadetChannel *ch;
1871 ch = lookup_channel (t,
1875 /* We don't know about such a channel, might have been destroyed on our
1876 end in the meantime, or never existed. Send back a DESTROY. */
1877 GCT_send_channel_destroy (t,
1881 GCCH_handle_channel_create_ack (ch);
1886 * We received a message saying that a channel should be destroyed.
1887 * Pass it on to the correct channel.
1889 * @param cls the `struct CadetTunnel` for which we decrypted the message
1890 * @param cm the message we received on the tunnel
1893 handle_plaintext_channel_destroy (void *cls,
1894 const struct GNUNET_CADET_ChannelManageMessage *cm)
1896 struct CadetTunnel *t = cls;
1897 struct CadetChannel *cc = lookup_channel (t,
1900 GCCH_handle_remote_destroy (cc);
1905 * Handles a message we decrypted, by injecting it into
1906 * our message queue (which will do the dispatching).
1908 * @param cls the `struct CadetTunnel` that got the message
1909 * @param msg the message
1910 * @return #GNUNET_OK (continue to process)
1913 handle_decrypted (void *cls,
1914 const struct GNUNET_MessageHeader *msg)
1916 struct CadetTunnel *t = cls;
1918 GNUNET_MQ_inject_message (t->mq,
1925 * Function called if we had an error processing
1926 * an incoming decrypted message.
1928 * @param cls the `struct CadetTunnel`
1929 * @param error error code
1932 decrypted_error_cb (void *cls,
1933 enum GNUNET_MQ_Error error)
1935 GNUNET_break_op (0);
1940 * Create a tunnel to @a destionation. Must only be called
1941 * from within #GCP_get_tunnel().
1943 * @param destination where to create the tunnel to
1944 * @return new tunnel to @a destination
1946 struct CadetTunnel *
1947 GCT_create_tunnel (struct CadetPeer *destination)
1949 struct GNUNET_MQ_MessageHandler handlers[] = {
1950 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
1951 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
1952 struct GNUNET_MessageHeader,
1954 GNUNET_MQ_hd_var_size (plaintext_data,
1955 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
1956 struct GNUNET_CADET_ChannelAppDataMessage,
1958 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
1959 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
1960 struct GNUNET_CADET_ChannelDataAckMessage,
1962 GNUNET_MQ_hd_fixed_size (plaintext_channel_create,
1963 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
1964 struct GNUNET_CADET_ChannelOpenMessage,
1966 GNUNET_MQ_hd_fixed_size (plaintext_channel_ack,
1967 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
1968 struct GNUNET_CADET_ChannelManageMessage,
1970 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
1971 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1972 struct GNUNET_CADET_ChannelManageMessage,
1974 GNUNET_MQ_handler_end ()
1976 struct CadetTunnel *t;
1978 t = GNUNET_new (struct CadetTunnel);
1979 t->destination = destination;
1980 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1981 (void) GCP_iterate_paths (destination,
1984 t->maintain_connections_task
1985 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1987 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
1992 &decrypted_error_cb,
1994 t->mst = GNUNET_MST_create (&handle_decrypted,
2001 * Remove a channel from a tunnel.
2005 * @param gid unique number identifying @a ch within @a t
2008 GCT_remove_channel (struct CadetTunnel *t,
2009 struct CadetChannel *ch,
2010 struct GNUNET_CADET_ChannelTunnelNumber gid)
2012 GNUNET_assert (GNUNET_YES ==
2013 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2017 GNUNET_CONTAINER_multihashmap32_size (t->channels))
2019 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2027 * Add a @a connection to the @a tunnel.
2030 * @param cid connection identifer to use for the connection
2031 * @param path path to use for the connection
2034 GCT_add_inbound_connection (struct CadetTunnel *t,
2035 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2036 struct CadetPeerPath *path)
2038 struct CadetTConnection *ct;
2040 ct = GNUNET_new (struct CadetTConnection);
2041 ct->created = GNUNET_TIME_absolute_get ();
2043 ct->cc = GCC_create_inbound (t->destination,
2047 &connection_ready_cb,
2049 /* FIXME: schedule job to kill connection (and path?) if it takes
2050 too long to get ready! (And track performance data on how long
2051 other connections took with the tunnel!)
2052 => Note: to be done within 'connection'-logic! */
2053 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2056 t->num_connections++;
2061 * Handle encrypted message.
2063 * @param ct connection/tunnel combo that received encrypted message
2064 * @param msg the encrypted message to decrypt
2067 GCT_handle_encrypted (struct CadetTConnection *ct,
2068 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2070 struct CadetTunnel *t = ct->t;
2071 uint16_t size = ntohs (msg->header.size);
2072 char cbuf [size] GNUNET_ALIGN;
2073 ssize_t decrypted_size;
2077 case CADET_TUNNEL_KEY_UNINITIALIZED:
2078 /* We did not even SEND our KX, how can the other peer
2079 send us encrypted data? */
2080 GNUNET_break_op (0);
2082 case CADET_TUNNEL_KEY_SENT:
2083 /* We did not get the KX of the other peer, but that
2084 might have been lost. Ask for KX again. */
2085 GNUNET_STATISTICS_update (stats,
2086 "# received encrypted without KX",
2089 if (NULL != t->kx_task)
2090 GNUNET_SCHEDULER_cancel (t->kx_task);
2091 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2094 case CADET_TUNNEL_KEY_PING:
2095 /* Great, first payload, we might graduate to OK */
2096 case CADET_TUNNEL_KEY_OK:
2097 case CADET_TUNNEL_KEY_REKEY:
2101 GNUNET_STATISTICS_update (stats,
2102 "# received encrypted",
2105 decrypted_size = t_ax_decrypt_and_validate (t,
2110 if (-1 == decrypted_size)
2112 GNUNET_STATISTICS_update (stats,
2113 "# unable to decrypt",
2116 if (CADET_TUNNEL_KEY_PING <= t->estate)
2118 GNUNET_break_op (0);
2119 LOG (GNUNET_ERROR_TYPE_WARNING,
2120 "Failed to decrypt message on tunnel %s\n",
2125 if (CADET_TUNNEL_KEY_PING == t->estate)
2127 GCT_change_estate (t,
2128 CADET_TUNNEL_KEY_OK);
2129 trigger_transmissions (t);
2131 /* The MST will ultimately call #handle_decrypted() on each message. */
2132 GNUNET_break_op (GNUNET_OK ==
2133 GNUNET_MST_from_buffer (t->mst,
2142 * Sends an already built message on a tunnel, encrypting it and
2143 * choosing the best connection if not provided.
2145 * @param message Message to send. Function modifies it.
2146 * @param t Tunnel on which this message is transmitted.
2147 * @param cont Continuation to call once message is really sent.
2148 * @param cont_cls Closure for @c cont.
2149 * @return Handle to cancel message. NULL if @c cont is NULL.
2151 struct CadetTunnelQueueEntry *
2152 GCT_send (struct CadetTunnel *t,
2153 const struct GNUNET_MessageHeader *message,
2154 GNUNET_SCHEDULER_TaskCallback cont,
2157 struct CadetTunnelQueueEntry *tq;
2158 uint16_t payload_size;
2159 struct GNUNET_MQ_Envelope *env;
2160 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2162 payload_size = ntohs (message->size);
2163 env = GNUNET_MQ_msg_extra (ax_msg,
2165 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2170 ax_msg->Ns = htonl (t->ax.Ns++);
2171 ax_msg->PNs = htonl (t->ax.PNs);
2172 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2176 t_hmac (&ax_msg->Ns,
2177 AX_HEADER_SIZE + payload_size,
2182 tq = GNUNET_malloc (sizeof (*tq));
2185 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2187 tq->cont_cls = cont_cls;
2188 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2191 trigger_transmissions (t);
2197 * Cancel a previously sent message while it's in the queue.
2199 * ONLY can be called before the continuation given to the send
2200 * function is called. Once the continuation is called, the message is
2201 * no longer in the queue!
2203 * @param q Handle to the queue entry to cancel.
2206 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
2208 struct CadetTunnel *t = q->t;
2210 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2218 * Iterate over all connections of a tunnel.
2220 * @param t Tunnel whose connections to iterate.
2221 * @param iter Iterator.
2222 * @param iter_cls Closure for @c iter.
2225 GCT_iterate_connections (struct CadetTunnel *t,
2226 GCT_ConnectionIterator iter,
2229 for (struct CadetTConnection *ct = t->connection_head;
2238 * Closure for #iterate_channels_cb.
2245 GCT_ChannelIterator iter;
2248 * Closure for @e iter.
2255 * Helper function for #GCT_iterate_channels.
2257 * @param cls the `struct ChanIterCls`
2259 * @param value a `struct CadetChannel`
2260 * @return #GNUNET_OK
2263 iterate_channels_cb (void *cls,
2267 struct ChanIterCls *ctx = cls;
2268 struct CadetChannel *ch = value;
2270 ctx->iter (ctx->iter_cls,
2277 * Iterate over all channels of a tunnel.
2279 * @param t Tunnel whose channels to iterate.
2280 * @param iter Iterator.
2281 * @param iter_cls Closure for @c iter.
2284 GCT_iterate_channels (struct CadetTunnel *t,
2285 GCT_ChannelIterator iter,
2288 struct ChanIterCls ctx;
2291 ctx.iter_cls = iter_cls;
2292 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2293 &iterate_channels_cb,
2300 * Call #GCCH_debug() on a channel.
2302 * @param cls points to the log level to use
2304 * @param value the `struct CadetChannel` to dump
2305 * @return #GNUNET_OK (continue iteration)
2308 debug_channel (void *cls,
2312 const enum GNUNET_ErrorType *level = cls;
2313 struct CadetChannel *ch = value;
2315 GCCH_debug (ch, *level);
2321 * Get string description for tunnel encryption state.
2323 * @param es Tunnel state.
2325 * @return String representation.
2328 estate2s (enum CadetTunnelEState es)
2330 static char buf[32];
2334 case CADET_TUNNEL_KEY_UNINITIALIZED:
2335 return "CADET_TUNNEL_KEY_UNINITIALIZED";
2336 case CADET_TUNNEL_KEY_SENT:
2337 return "CADET_TUNNEL_KEY_SENT";
2338 case CADET_TUNNEL_KEY_PING:
2339 return "CADET_TUNNEL_KEY_PING";
2340 case CADET_TUNNEL_KEY_OK:
2341 return "CADET_TUNNEL_KEY_OK";
2342 case CADET_TUNNEL_KEY_REKEY:
2343 return "CADET_TUNNEL_KEY_REKEY";
2345 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
2351 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2355 * Log all possible info about the tunnel state.
2357 * @param t Tunnel to debug.
2358 * @param level Debug level to use.
2361 GCT_debug (const struct CadetTunnel *t,
2362 enum GNUNET_ErrorType level)
2364 struct CadetTConnection *iter_c;
2367 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2369 __FILE__, __FUNCTION__, __LINE__);
2374 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2376 estate2s (t->estate),
2378 t->num_connections);
2379 #if DUMP_KEYS_TO_STDERR
2380 ax_debug (t->ax, level);
2384 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2388 "TTT connections:\n");
2389 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2390 GCC_debug (iter_c->cc,
2394 "TTT TUNNEL END\n");
2398 /* end of gnunet-service-cadet-new_tunnels.c */