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)
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 ctn.
449 * @param t tunnel to look in
450 * @param ctn 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 ctn)
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_ctn (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 CTN!
1399 Need to reserve one bit of the CTN for the
1400 direction, i.e. which side established the connection! */
1401 ctn = ntohl (t->next_ctn.cn);
1403 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1406 t->next_ctn.cn = htonl (ctn + 1);
1407 ret.cn = ntohl (ctn);
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 ctn;
1425 ctn = get_next_free_ctn (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;
1728 GNUNET_break (0); // FIXME
1733 * Check that @a msg is well-formed.
1735 * @param cls the `struct CadetTunnel` for which we decrypted the message
1736 * @param msg the message we received on the tunnel
1737 * @return #GNUNET_OK (any variable-size payload goes)
1740 check_plaintext_data (void *cls,
1741 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1748 * We received payload data for a channel. Locate the channel
1749 * and process the data, or return an error if the channel is unknown.
1751 * @param cls the `struct CadetTunnel` for which we decrypted the message
1752 * @param msg the message we received on the tunnel
1755 handle_plaintext_data (void *cls,
1756 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1758 struct CadetTunnel *t = cls;
1759 struct CadetChannel *ch;
1761 ch = lookup_channel (t,
1765 /* We don't know about such a channel, might have been destroyed on our
1766 end in the meantime, or never existed. Send back a DESTROY. */
1767 GCT_send_channel_destroy (t,
1771 GCCH_handle_channel_plaintext_data (ch,
1777 * We received an acknowledgement for data we sent on a channel.
1778 * Locate the channel and process it, or return an error if the
1779 * channel is unknown.
1781 * @param cls the `struct CadetTunnel` for which we decrypted the message
1782 * @param ack the message we received on the tunnel
1785 handle_plaintext_data_ack (void *cls,
1786 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1788 struct CadetTunnel *t = cls;
1789 struct CadetChannel *ch;
1791 ch = lookup_channel (t,
1795 /* We don't know about such a channel, might have been destroyed on our
1796 end in the meantime, or never existed. Send back a DESTROY. */
1797 GCT_send_channel_destroy (t,
1801 GCCH_handle_channel_plaintext_data_ack (ch,
1807 * We have received a request to open a channel to a port from
1808 * another peer. Creates the incoming channel.
1810 * @param cls the `struct CadetTunnel` for which we decrypted the message
1811 * @param cc the message we received on the tunnel
1814 handle_plaintext_channel_create (void *cls,
1815 const struct GNUNET_CADET_ChannelOpenMessage *cc)
1817 struct CadetTunnel *t = cls;
1818 struct CadetChannel *ch;
1819 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1821 ctn = get_next_free_ctn (t);
1822 ch = GCCH_channel_incoming_new (t,
1826 GNUNET_assert (GNUNET_OK ==
1827 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1830 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1835 * Send a DESTROY message via the tunnel.
1837 * @param t the tunnel to transmit over
1838 * @param ctn ID of the channel to destroy
1841 GCT_send_channel_destroy (struct CadetTunnel *t,
1842 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1844 struct GNUNET_CADET_ChannelManageMessage msg;
1846 msg.header.size = htons (sizeof (msg));
1847 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1848 msg.reserved = htonl (0);
1858 * We have received confirmation from the target peer that the
1859 * given channel could be established (the port is open).
1862 * @param cls the `struct CadetTunnel` for which we decrypted the message
1863 * @param cm the message we received on the tunnel
1866 handle_plaintext_channel_ack (void *cls,
1867 const struct GNUNET_CADET_ChannelManageMessage *cm)
1869 struct CadetTunnel *t = cls;
1870 struct CadetChannel *ch;
1872 ch = lookup_channel (t,
1876 /* We don't know about such a channel, might have been destroyed on our
1877 end in the meantime, or never existed. Send back a DESTROY. */
1878 GCT_send_channel_destroy (t,
1882 GCCH_handle_channel_create_ack (ch);
1887 * We received a message saying that a channel should be destroyed.
1888 * Pass it on to the correct channel.
1890 * @param cls the `struct CadetTunnel` for which we decrypted the message
1891 * @param cm the message we received on the tunnel
1894 handle_plaintext_channel_destroy (void *cls,
1895 const struct GNUNET_CADET_ChannelManageMessage *cm)
1897 struct CadetTunnel *t = cls;
1898 struct CadetChannel *cc = lookup_channel (t,
1901 GCCH_handle_remote_destroy (cc);
1906 * Handles a message we decrypted, by injecting it into
1907 * our message queue (which will do the dispatching).
1909 * @param cls the `struct CadetTunnel` that got the message
1910 * @param msg the message
1911 * @return #GNUNET_OK (continue to process)
1914 handle_decrypted (void *cls,
1915 const struct GNUNET_MessageHeader *msg)
1917 struct CadetTunnel *t = cls;
1919 GNUNET_MQ_inject_message (t->mq,
1926 * Function called if we had an error processing
1927 * an incoming decrypted message.
1929 * @param cls the `struct CadetTunnel`
1930 * @param error error code
1933 decrypted_error_cb (void *cls,
1934 enum GNUNET_MQ_Error error)
1936 GNUNET_break_op (0);
1941 * Create a tunnel to @a destionation. Must only be called
1942 * from within #GCP_get_tunnel().
1944 * @param destination where to create the tunnel to
1945 * @return new tunnel to @a destination
1947 struct CadetTunnel *
1948 GCT_create_tunnel (struct CadetPeer *destination)
1950 struct GNUNET_MQ_MessageHandler handlers[] = {
1951 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
1952 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
1953 struct GNUNET_MessageHeader,
1955 GNUNET_MQ_hd_var_size (plaintext_data,
1956 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
1957 struct GNUNET_CADET_ChannelAppDataMessage,
1959 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
1960 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
1961 struct GNUNET_CADET_ChannelDataAckMessage,
1963 GNUNET_MQ_hd_fixed_size (plaintext_channel_create,
1964 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
1965 struct GNUNET_CADET_ChannelOpenMessage,
1967 GNUNET_MQ_hd_fixed_size (plaintext_channel_ack,
1968 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
1969 struct GNUNET_CADET_ChannelManageMessage,
1971 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
1972 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1973 struct GNUNET_CADET_ChannelManageMessage,
1975 GNUNET_MQ_handler_end ()
1977 struct CadetTunnel *t;
1979 t = GNUNET_new (struct CadetTunnel);
1980 t->destination = destination;
1981 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1982 (void) GCP_iterate_paths (destination,
1985 t->maintain_connections_task
1986 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1988 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
1993 &decrypted_error_cb,
1995 t->mst = GNUNET_MST_create (&handle_decrypted,
2002 * Remove a channel from a tunnel.
2006 * @param gid unique number identifying @a ch within @a t
2009 GCT_remove_channel (struct CadetTunnel *t,
2010 struct CadetChannel *ch,
2011 struct GNUNET_CADET_ChannelTunnelNumber gid)
2013 GNUNET_assert (GNUNET_YES ==
2014 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2018 GNUNET_CONTAINER_multihashmap32_size (t->channels))
2020 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2028 * Add a @a connection to the @a tunnel.
2031 * @param cid connection identifer to use for the connection
2032 * @param path path to use for the connection
2035 GCT_add_inbound_connection (struct CadetTunnel *t,
2036 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2037 struct CadetPeerPath *path)
2039 struct CadetTConnection *ct;
2041 ct = GNUNET_new (struct CadetTConnection);
2042 ct->created = GNUNET_TIME_absolute_get ();
2044 ct->cc = GCC_create_inbound (t->destination,
2048 &connection_ready_cb,
2050 /* FIXME: schedule job to kill connection (and path?) if it takes
2051 too long to get ready! (And track performance data on how long
2052 other connections took with the tunnel!)
2053 => Note: to be done within 'connection'-logic! */
2054 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2057 t->num_connections++;
2062 * Handle encrypted message.
2064 * @param ct connection/tunnel combo that received encrypted message
2065 * @param msg the encrypted message to decrypt
2068 GCT_handle_encrypted (struct CadetTConnection *ct,
2069 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2071 struct CadetTunnel *t = ct->t;
2072 uint16_t size = ntohs (msg->header.size);
2073 char cbuf [size] GNUNET_ALIGN;
2074 ssize_t decrypted_size;
2078 case CADET_TUNNEL_KEY_UNINITIALIZED:
2079 /* We did not even SEND our KX, how can the other peer
2080 send us encrypted data? */
2081 GNUNET_break_op (0);
2083 case CADET_TUNNEL_KEY_SENT:
2084 /* We did not get the KX of the other peer, but that
2085 might have been lost. Ask for KX again. */
2086 GNUNET_STATISTICS_update (stats,
2087 "# received encrypted without KX",
2090 if (NULL != t->kx_task)
2091 GNUNET_SCHEDULER_cancel (t->kx_task);
2092 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2095 case CADET_TUNNEL_KEY_PING:
2096 /* Great, first payload, we might graduate to OK */
2097 case CADET_TUNNEL_KEY_OK:
2098 case CADET_TUNNEL_KEY_REKEY:
2102 GNUNET_STATISTICS_update (stats,
2103 "# received encrypted",
2106 decrypted_size = t_ax_decrypt_and_validate (t,
2111 if (-1 == decrypted_size)
2113 GNUNET_STATISTICS_update (stats,
2114 "# unable to decrypt",
2117 if (CADET_TUNNEL_KEY_PING <= t->estate)
2119 GNUNET_break_op (0);
2120 LOG (GNUNET_ERROR_TYPE_WARNING,
2121 "Failed to decrypt message on tunnel %s\n",
2126 if (CADET_TUNNEL_KEY_PING == t->estate)
2128 GCT_change_estate (t,
2129 CADET_TUNNEL_KEY_OK);
2130 trigger_transmissions (t);
2132 /* The MST will ultimately call #handle_decrypted() on each message. */
2133 GNUNET_break_op (GNUNET_OK ==
2134 GNUNET_MST_from_buffer (t->mst,
2143 * Sends an already built message on a tunnel, encrypting it and
2144 * choosing the best connection if not provided.
2146 * @param message Message to send. Function modifies it.
2147 * @param t Tunnel on which this message is transmitted.
2148 * @param cont Continuation to call once message is really sent.
2149 * @param cont_cls Closure for @c cont.
2150 * @return Handle to cancel message. NULL if @c cont is NULL.
2152 struct CadetTunnelQueueEntry *
2153 GCT_send (struct CadetTunnel *t,
2154 const struct GNUNET_MessageHeader *message,
2155 GNUNET_SCHEDULER_TaskCallback cont,
2158 struct CadetTunnelQueueEntry *tq;
2159 uint16_t payload_size;
2160 struct GNUNET_MQ_Envelope *env;
2161 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2163 payload_size = ntohs (message->size);
2164 env = GNUNET_MQ_msg_extra (ax_msg,
2166 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2171 ax_msg->Ns = htonl (t->ax.Ns++);
2172 ax_msg->PNs = htonl (t->ax.PNs);
2173 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2177 t_hmac (&ax_msg->Ns,
2178 AX_HEADER_SIZE + payload_size,
2183 tq = GNUNET_malloc (sizeof (*tq));
2186 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2188 tq->cont_cls = cont_cls;
2189 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2192 trigger_transmissions (t);
2198 * Cancel a previously sent message while it's in the queue.
2200 * ONLY can be called before the continuation given to the send
2201 * function is called. Once the continuation is called, the message is
2202 * no longer in the queue!
2204 * @param q Handle to the queue entry to cancel.
2207 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
2209 struct CadetTunnel *t = q->t;
2211 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2219 * Iterate over all connections of a tunnel.
2221 * @param t Tunnel whose connections to iterate.
2222 * @param iter Iterator.
2223 * @param iter_cls Closure for @c iter.
2226 GCT_iterate_connections (struct CadetTunnel *t,
2227 GCT_ConnectionIterator iter,
2230 for (struct CadetTConnection *ct = t->connection_head;
2239 * Closure for #iterate_channels_cb.
2246 GCT_ChannelIterator iter;
2249 * Closure for @e iter.
2256 * Helper function for #GCT_iterate_channels.
2258 * @param cls the `struct ChanIterCls`
2260 * @param value a `struct CadetChannel`
2261 * @return #GNUNET_OK
2264 iterate_channels_cb (void *cls,
2268 struct ChanIterCls *ctx = cls;
2269 struct CadetChannel *ch = value;
2271 ctx->iter (ctx->iter_cls,
2278 * Iterate over all channels of a tunnel.
2280 * @param t Tunnel whose channels to iterate.
2281 * @param iter Iterator.
2282 * @param iter_cls Closure for @c iter.
2285 GCT_iterate_channels (struct CadetTunnel *t,
2286 GCT_ChannelIterator iter,
2289 struct ChanIterCls ctx;
2292 ctx.iter_cls = iter_cls;
2293 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2294 &iterate_channels_cb,
2301 * Call #GCCH_debug() on a channel.
2303 * @param cls points to the log level to use
2305 * @param value the `struct CadetChannel` to dump
2306 * @return #GNUNET_OK (continue iteration)
2309 debug_channel (void *cls,
2313 const enum GNUNET_ErrorType *level = cls;
2314 struct CadetChannel *ch = value;
2316 GCCH_debug (ch, *level);
2322 * Get string description for tunnel encryption state.
2324 * @param es Tunnel state.
2326 * @return String representation.
2329 estate2s (enum CadetTunnelEState es)
2331 static char buf[32];
2335 case CADET_TUNNEL_KEY_UNINITIALIZED:
2336 return "CADET_TUNNEL_KEY_UNINITIALIZED";
2337 case CADET_TUNNEL_KEY_SENT:
2338 return "CADET_TUNNEL_KEY_SENT";
2339 case CADET_TUNNEL_KEY_PING:
2340 return "CADET_TUNNEL_KEY_PING";
2341 case CADET_TUNNEL_KEY_OK:
2342 return "CADET_TUNNEL_KEY_OK";
2343 case CADET_TUNNEL_KEY_REKEY:
2344 return "CADET_TUNNEL_KEY_REKEY";
2346 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
2352 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2356 * Log all possible info about the tunnel state.
2358 * @param t Tunnel to debug.
2359 * @param level Debug level to use.
2362 GCT_debug (const struct CadetTunnel *t,
2363 enum GNUNET_ErrorType level)
2365 struct CadetTConnection *iter_c;
2368 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2370 __FILE__, __FUNCTION__, __LINE__);
2375 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2377 estate2s (t->estate),
2379 t->num_connections);
2380 #if DUMP_KEYS_TO_STDERR
2381 ax_debug (t->ax, level);
2385 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2389 "TTT connections:\n");
2390 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2391 GCC_debug (iter_c->cc,
2395 "TTT TUNNEL END\n");
2399 /* end of gnunet-service-cadet-new_tunnels.c */