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 * - connection management
28 * + properly (evaluate, kill old ones, search for new ones)
29 * + when managing connections, distinguish those that
30 * have (recently) had traffic from those that were
31 * never ready (or not recently)
34 #include "gnunet_util_lib.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet-service-cadet-new.h"
38 #include "cadet_protocol.h"
39 #include "gnunet-service-cadet-new_channel.h"
40 #include "gnunet-service-cadet-new_connection.h"
41 #include "gnunet-service-cadet-new_tunnels.h"
42 #include "gnunet-service-cadet-new_peer.h"
43 #include "gnunet-service-cadet-new_paths.h"
46 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
49 * How often do we try to decrypt payload with unverified key
50 * material? Used to limit CPU increase upon receiving bogus
53 #define MAX_UNVERIFIED_ATTEMPTS 16
56 * How long do we wait until tearing down an idle tunnel?
58 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
61 * How long do we wait initially before retransmitting the KX?
62 * TODO: replace by 2 RTT if/once we have connection-level RTT data!
64 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
67 * Maximum number of skipped keys we keep in memory per tunnel.
69 #define MAX_SKIPPED_KEYS 64
72 * Maximum number of keys (and thus ratchet steps) we are willing to
73 * skip before we decide this is either a bogus packet or a DoS-attempt.
75 #define MAX_KEY_GAP 256
79 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
81 struct CadetTunnelSkippedKey
86 struct CadetTunnelSkippedKey *next;
91 struct CadetTunnelSkippedKey *prev;
94 * When was this key stored (for timeout).
96 struct GNUNET_TIME_Absolute timestamp;
101 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
106 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
109 * Key number for a given HK.
116 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
118 struct CadetTunnelAxolotl
121 * A (double linked) list of stored message keys and associated header keys
122 * for "skipped" messages, i.e. messages that have not been
123 * received despite the reception of more recent messages, (head).
125 struct CadetTunnelSkippedKey *skipped_head;
128 * Skipped messages' keys DLL, tail.
130 struct CadetTunnelSkippedKey *skipped_tail;
133 * 32-byte root key which gets updated by DH ratchet.
135 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
138 * 32-byte header key (currently used for sending).
140 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
143 * 32-byte header key (currently used for receiving)
145 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
148 * 32-byte next header key (for sending), used once the
149 * ratchet advances. We are sure that the sender has this
150 * key as well only after @e ratchet_allowed is #GNUNET_YES.
152 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
155 * 32-byte next header key (for receiving). To be tried
156 * when decrypting with @e HKr fails and thus the sender
157 * may have advanced the ratchet.
159 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
162 * 32-byte chain keys (used for forward-secrecy) for
163 * sending messages. Updated for every message.
165 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
168 * 32-byte chain keys (used for forward-secrecy) for
169 * receiving messages. Updated for every message. If
170 * messages are skipped, the respective derived MKs
171 * (and the current @HKr) are kept in the @e skipped_head DLL.
173 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
176 * ECDH for key exchange (A0 / B0). Note that for the
177 * 'unverified_ax', this member is an alias with the main
178 * 't->ax.kx_0' value, so do not free it!
180 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
183 * ECDH Ratchet key (our private key in the current DH). Note that
184 * for the 'unverified_ax', this member is an alias with the main
185 * 't->ax.kx_0' value, so do not free it!
187 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
190 * ECDH Ratchet key (other peer's public key in the current DH).
192 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
195 * Time when the current ratchet expires and a new one is triggered
196 * (if @e ratchet_allowed is #GNUNET_YES).
198 struct GNUNET_TIME_Absolute ratchet_expiration;
201 * Number of elements in @a skipped_head <-> @a skipped_tail.
203 unsigned int skipped;
206 * Message number (reset to 0 with each new ratchet, next message to send).
211 * Message number (reset to 0 with each new ratchet, next message to recv).
216 * Previous message numbers (# of msgs sent under prev ratchet)
221 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
226 * True (#GNUNET_YES) if we have received a message from the
227 * other peer that uses the keys from our last ratchet step.
228 * This implies that we are again allowed to advance the ratchet,
229 * otherwise we have to wait until the other peer sees our current
230 * ephemeral key and advances first.
232 * #GNUNET_NO if we have advanced the ratched but lack any evidence
233 * that the other peer has noticed this.
238 * Number of messages recieved since our last ratchet advance.
240 * If this counter = 0, we cannot send a new ratchet key in the next
243 * If this counter > 0, we could (but don't have to) send a new key.
245 * Once the @e ratchet_counter is larger than
246 * #ratchet_messages (or @e ratchet_expiration time has past), and
247 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
249 unsigned int ratchet_counter;
255 * Struct used to save messages in a non-ready tunnel to send once connected.
257 struct CadetTunnelQueueEntry
260 * We are entries in a DLL
262 struct CadetTunnelQueueEntry *next;
265 * We are entries in a DLL
267 struct CadetTunnelQueueEntry *prev;
270 * Tunnel these messages belong in.
272 struct CadetTunnel *t;
275 * Continuation to call once sent (on the channel layer).
277 GNUNET_SCHEDULER_TaskCallback cont;
280 * Closure for @c cont.
285 * Envelope of message to send follows.
287 struct GNUNET_MQ_Envelope *env;
290 * Where to put the connection identifier into the payload
291 * of the message in @e env once we have it?
293 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
298 * Struct containing all information regarding a tunnel to a peer.
303 * Destination of the tunnel.
305 struct CadetPeer *destination;
308 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
309 * ephemeral key changes.
311 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
314 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
316 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
319 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
321 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
326 struct CadetTunnelAxolotl ax;
329 * Unverified Axolotl info, used only if we got a fresh KX (not a
330 * KX_AUTH) while our end of the tunnel was still up. In this case,
331 * we keep the fresh KX around but do not put it into action until
332 * we got encrypted payload that assures us of the authenticity of
335 struct CadetTunnelAxolotl *unverified_ax;
338 * Task scheduled if there are no more channels using the tunnel.
340 struct GNUNET_SCHEDULER_Task *destroy_task;
343 * Task to trim connections if too many are present.
345 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
348 * Task to send messages from queue (if possible).
350 struct GNUNET_SCHEDULER_Task *send_task;
353 * Task to trigger KX.
355 struct GNUNET_SCHEDULER_Task *kx_task;
358 * Tokenizer for decrypted messages.
360 struct GNUNET_MessageStreamTokenizer *mst;
363 * Dispatcher for decrypted messages only (do NOT use for sending!).
365 struct GNUNET_MQ_Handle *mq;
368 * DLL of connections that are actively used to reach the destination peer.
370 struct CadetTConnection *connection_head;
373 * DLL of connections that are actively used to reach the destination peer.
375 struct CadetTConnection *connection_tail;
378 * Channels inside this tunnel. Maps
379 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
381 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
384 * Channel ID for the next created channel in this tunnel.
386 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
389 * Queued messages, to transmit once tunnel gets connected.
391 struct CadetTunnelQueueEntry *tq_head;
394 * Queued messages, to transmit once tunnel gets connected.
396 struct CadetTunnelQueueEntry *tq_tail;
399 * How long do we wait until we retry the KX?
401 struct GNUNET_TIME_Relative kx_retry_delay;
404 * When do we try the next KX?
406 struct GNUNET_TIME_Absolute next_kx_attempt;
409 * Number of connections in the @e connection_head DLL.
411 unsigned int num_connections;
414 * How often have we tried and failed to decrypt a message using
415 * the unverified KX material from @e unverified_ax? Used to
416 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
418 unsigned int unverified_attempts;
421 * Number of entries in the @e tq_head DLL.
426 * State of the tunnel encryption.
428 enum CadetTunnelEState estate;
431 * Force triggering KX_AUTH independent of @e estate.
433 int kx_auth_requested;
439 * Get the static string for the peer this tunnel is directed.
443 * @return Static string the destination peer's ID.
446 GCT_2s (const struct CadetTunnel *t)
451 return "Tunnel(NULL)";
452 GNUNET_snprintf (buf,
455 GNUNET_i2s (GCP_get_id (t->destination)));
461 * Get string description for tunnel encryption state.
463 * @param es Tunnel state.
465 * @return String representation.
468 estate2s (enum CadetTunnelEState es)
474 case CADET_TUNNEL_KEY_UNINITIALIZED:
475 return "CADET_TUNNEL_KEY_UNINITIALIZED";
476 case CADET_TUNNEL_KEY_AX_RECV:
477 return "CADET_TUNNEL_KEY_AX_RECV";
478 case CADET_TUNNEL_KEY_AX_SENT:
479 return "CADET_TUNNEL_KEY_AX_SENT";
480 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
481 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
482 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
483 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
484 case CADET_TUNNEL_KEY_OK:
485 return "CADET_TUNNEL_KEY_OK";
487 GNUNET_snprintf (buf,
489 "%u (UNKNOWN STATE)",
497 * Return the peer to which this tunnel goes.
500 * @return the destination of the tunnel
503 GCT_get_destination (struct CadetTunnel *t)
505 return t->destination;
510 * Count channels of a tunnel.
512 * @param t Tunnel on which to count.
514 * @return Number of channels.
517 GCT_count_channels (struct CadetTunnel *t)
519 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
524 * Lookup a channel by its @a ctn.
526 * @param t tunnel to look in
527 * @param ctn number of channel to find
528 * @return NULL if channel does not exist
530 struct CadetChannel *
531 lookup_channel (struct CadetTunnel *t,
532 struct GNUNET_CADET_ChannelTunnelNumber ctn)
534 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
540 * Count all created connections of a tunnel. Not necessarily ready connections!
542 * @param t Tunnel on which to count.
544 * @return Number of connections created, either being established or ready.
547 GCT_count_any_connections (struct CadetTunnel *t)
549 return t->num_connections;
554 * Find first connection that is ready in the list of
555 * our connections. Picks ready connections round-robin.
557 * @param t tunnel to search
558 * @return NULL if we have no connection that is ready
560 static struct CadetTConnection *
561 get_ready_connection (struct CadetTunnel *t)
563 for (struct CadetTConnection *pos = t->connection_head;
566 if (GNUNET_YES == pos->is_ready)
568 if (pos != t->connection_tail)
570 /* move 'pos' to the end, so we try other ready connections
571 first next time (round-robin, modulo availability) */
572 GNUNET_CONTAINER_DLL_remove (t->connection_head,
575 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
586 * Get the encryption state of a tunnel.
590 * @return Tunnel's encryption state.
592 enum CadetTunnelEState
593 GCT_get_estate (struct CadetTunnel *t)
600 * Called when either we have a new connection, or a new message in the
601 * queue, or some existing connection has transmission capacity. Looks
602 * at our message queue and if there is a message, picks a connection
605 * @param cls the `struct CadetTunnel` to process messages on
608 trigger_transmissions (void *cls);
611 /* ************************************** start core crypto ***************************** */
615 * Create a new Axolotl ephemeral (ratchet) key.
617 * @param ax key material to update
620 new_ephemeral (struct CadetTunnelAxolotl *ax)
622 GNUNET_free_non_null (ax->DHRs);
623 LOG (GNUNET_ERROR_TYPE_DEBUG,
624 "Creating new ephemeral ratchet key (DHRs)\n");
625 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
632 * @param plaintext Content to HMAC.
633 * @param size Size of @c plaintext.
634 * @param iv Initialization vector for the message.
635 * @param key Key to use.
636 * @param hmac[out] Destination to store the HMAC.
639 t_hmac (const void *plaintext,
642 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
643 struct GNUNET_ShortHashCode *hmac)
645 static const char ctx[] = "cadet authentication key";
646 struct GNUNET_CRYPTO_AuthKey auth_key;
647 struct GNUNET_HashCode hash;
649 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
655 /* Two step: GNUNET_ShortHash is only 256 bits,
656 GNUNET_HashCode is 512, so we truncate. */
657 GNUNET_CRYPTO_hmac (&auth_key,
670 * @param key Key to use.
671 * @param[out] hash Resulting HMAC.
672 * @param source Source key material (data to HMAC).
673 * @param len Length of @a source.
676 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
677 struct GNUNET_HashCode *hash,
681 static const char ctx[] = "axolotl HMAC-HASH";
682 struct GNUNET_CRYPTO_AuthKey auth_key;
684 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
688 GNUNET_CRYPTO_hmac (&auth_key,
696 * Derive a symmetric encryption key from an HMAC-HASH.
698 * @param key Key to use for the HMAC.
699 * @param[out] out Key to generate.
700 * @param source Source key material (data to HMAC).
701 * @param len Length of @a source.
704 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
705 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
709 static const char ctx[] = "axolotl derive key";
710 struct GNUNET_HashCode h;
716 GNUNET_CRYPTO_kdf (out, sizeof (*out),
724 * Encrypt data with the axolotl tunnel key.
726 * @param ax key material to use.
727 * @param dst Destination with @a size bytes for the encrypted data.
728 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
729 * @param size Size of the buffers at @a src and @a dst
732 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
737 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
738 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
741 ax->ratchet_counter++;
742 if ( (GNUNET_YES == ax->ratchet_allowed) &&
743 ( (ratchet_messages <= ax->ratchet_counter) ||
744 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
746 ax->ratchet_flag = GNUNET_YES;
748 if (GNUNET_YES == ax->ratchet_flag)
750 /* Advance ratchet */
751 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
752 struct GNUNET_HashCode dh;
753 struct GNUNET_HashCode hmac;
754 static const char ctx[] = "axolotl ratchet";
759 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
760 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
763 t_ax_hmac_hash (&ax->RK,
767 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
769 &hmac, sizeof (hmac),
777 ax->ratchet_flag = GNUNET_NO;
778 ax->ratchet_allowed = GNUNET_NO;
779 ax->ratchet_counter = 0;
780 ax->ratchet_expiration
781 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
785 t_hmac_derive_key (&ax->CKs,
789 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
794 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
799 GNUNET_assert (size == out_size);
800 t_hmac_derive_key (&ax->CKs,
808 * Decrypt data with the axolotl tunnel key.
810 * @param ax key material to use.
811 * @param dst Destination for the decrypted data, must contain @a size bytes.
812 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
813 * @param size Size of the @a src and @a dst buffers
816 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
821 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
822 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
825 t_hmac_derive_key (&ax->CKr,
829 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
833 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
834 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
839 GNUNET_assert (out_size == size);
840 t_hmac_derive_key (&ax->CKr,
848 * Encrypt header with the axolotl header key.
850 * @param ax key material to use.
851 * @param[in|out] msg Message whose header to encrypt.
854 t_h_encrypt (struct CadetTunnelAxolotl *ax,
855 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
857 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
860 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
864 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
865 sizeof (struct GNUNET_CADET_AxHeader),
869 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
874 * Decrypt header with the current axolotl header key.
876 * @param ax key material to use.
877 * @param src Message whose header to decrypt.
878 * @param dst Where to decrypt header to.
881 t_h_decrypt (struct CadetTunnelAxolotl *ax,
882 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
883 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
885 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
888 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
892 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
893 sizeof (struct GNUNET_CADET_AxHeader),
897 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
902 * Delete a key from the list of skipped keys.
904 * @param ax key material to delete @a key from.
905 * @param key Key to delete.
908 delete_skipped_key (struct CadetTunnelAxolotl *ax,
909 struct CadetTunnelSkippedKey *key)
911 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
920 * Decrypt and verify data with the appropriate tunnel key and verify that the
921 * data has not been altered since it was sent by the remote peer.
923 * @param ax key material to use.
924 * @param dst Destination for the plaintext.
925 * @param src Source of the message. Can overlap with @c dst.
926 * @param size Size of the message.
927 * @return Size of the decrypted data, -1 if an error was encountered.
930 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
932 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
935 struct CadetTunnelSkippedKey *key;
936 struct GNUNET_ShortHashCode *hmac;
937 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
938 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
939 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
945 LOG (GNUNET_ERROR_TYPE_DEBUG,
946 "Trying skipped keys\n");
947 hmac = &plaintext_header.hmac;
948 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
950 /* Find a correct Header Key */
952 for (key = ax->skipped_head; NULL != key; key = key->next)
954 t_hmac (&src->ax_header,
955 sizeof (struct GNUNET_CADET_AxHeader) + esize,
959 if (0 == memcmp (hmac,
970 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
971 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
972 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
973 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
976 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
980 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
981 sizeof (struct GNUNET_CADET_AxHeader),
984 &plaintext_header.ax_header.Ns);
985 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
987 /* Find the correct message key */
988 N = ntohl (plaintext_header.ax_header.Ns);
989 while ( (NULL != key) &&
992 if ( (NULL == key) ||
993 (0 != memcmp (&key->HK,
995 sizeof (*valid_HK))) )
998 /* Decrypt payload */
999 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1004 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1009 delete_skipped_key (ax,
1016 * Delete a key from the list of skipped keys.
1018 * @param ax key material to delete from.
1019 * @param HKr Header Key to use.
1022 store_skipped_key (struct CadetTunnelAxolotl *ax,
1023 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1025 struct CadetTunnelSkippedKey *key;
1027 key = GNUNET_new (struct CadetTunnelSkippedKey);
1028 key->timestamp = GNUNET_TIME_absolute_get ();
1031 t_hmac_derive_key (&ax->CKr,
1035 t_hmac_derive_key (&ax->CKr,
1039 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1048 * Stage skipped AX keys and calculate the message key.
1049 * Stores each HK and MK for skipped messages.
1051 * @param ax key material to use
1052 * @param HKr Header key.
1053 * @param Np Received meesage number.
1054 * @return #GNUNET_OK if keys were stored.
1055 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1058 store_ax_keys (struct CadetTunnelAxolotl *ax,
1059 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1065 LOG (GNUNET_ERROR_TYPE_DEBUG,
1066 "Storing skipped keys [%u, %u)\n",
1069 if (MAX_KEY_GAP < gap)
1071 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1072 /* TODO: start new key exchange on return */
1073 GNUNET_break_op (0);
1074 LOG (GNUNET_ERROR_TYPE_WARNING,
1075 "Got message %u, expected %u+\n",
1078 return GNUNET_SYSERR;
1082 /* Delayed message: don't store keys, flag to try old keys. */
1083 return GNUNET_SYSERR;
1087 store_skipped_key (ax,
1090 while (ax->skipped > MAX_SKIPPED_KEYS)
1091 delete_skipped_key (ax,
1098 * Decrypt and verify data with the appropriate tunnel key and verify that the
1099 * data has not been altered since it was sent by the remote peer.
1101 * @param ax key material to use
1102 * @param dst Destination for the plaintext.
1103 * @param src Source of the message. Can overlap with @c dst.
1104 * @param size Size of the message.
1105 * @return Size of the decrypted data, -1 if an error was encountered.
1108 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1110 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1113 struct GNUNET_ShortHashCode msg_hmac;
1114 struct GNUNET_HashCode hmac;
1115 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1118 size_t esize; /* Size of encryped payload */
1120 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1122 /* Try current HK */
1123 t_hmac (&src->ax_header,
1124 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1127 if (0 != memcmp (&msg_hmac,
1131 static const char ctx[] = "axolotl ratchet";
1132 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1133 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1134 struct GNUNET_HashCode dh;
1135 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1138 t_hmac (&src->ax_header,
1139 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1143 if (0 != memcmp (&msg_hmac,
1147 /* Try the skipped keys, if that fails, we're out of luck. */
1148 return try_old_ax_keys (ax,
1158 Np = ntohl (plaintext_header.ax_header.Ns);
1159 PNp = ntohl (plaintext_header.ax_header.PNs);
1160 DHRp = &plaintext_header.ax_header.DHRs;
1165 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1166 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1169 t_ax_hmac_hash (&ax->RK,
1172 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1174 &hmac, sizeof (hmac),
1177 /* Commit "purported" keys */
1183 ax->ratchet_allowed = GNUNET_YES;
1190 Np = ntohl (plaintext_header.ax_header.Ns);
1191 PNp = ntohl (plaintext_header.ax_header.PNs);
1193 if ( (Np != ax->Nr) &&
1194 (GNUNET_OK != store_ax_keys (ax,
1198 /* Try the skipped keys, if that fails, we're out of luck. */
1199 return try_old_ax_keys (ax,
1215 * Our tunnel became ready for the first time, notify channels
1216 * that have been waiting.
1218 * @param cls our tunnel, not used
1219 * @param key unique ID of the channel, not used
1220 * @param value the `struct CadetChannel` to notify
1221 * @return #GNUNET_OK (continue to iterate)
1224 notify_tunnel_up_cb (void *cls,
1228 struct CadetChannel *ch = value;
1230 GCCH_tunnel_up (ch);
1236 * Change the tunnel encryption state.
1237 * If the encryption state changes to OK, stop the rekey task.
1239 * @param t Tunnel whose encryption state to change, or NULL.
1240 * @param state New encryption state.
1243 GCT_change_estate (struct CadetTunnel *t,
1244 enum CadetTunnelEState state)
1246 enum CadetTunnelEState old = t->estate;
1249 LOG (GNUNET_ERROR_TYPE_DEBUG,
1250 "%s estate changed from %s to %s\n",
1255 if ( (CADET_TUNNEL_KEY_OK != old) &&
1256 (CADET_TUNNEL_KEY_OK == t->estate) )
1258 if (NULL != t->kx_task)
1260 GNUNET_SCHEDULER_cancel (t->kx_task);
1263 /* notify all channels that have been waiting */
1264 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1265 ¬ify_tunnel_up_cb,
1267 if (NULL != t->send_task)
1268 GNUNET_SCHEDULER_cancel (t->send_task);
1269 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1276 * Send a KX message.
1278 * @param t tunnel on which to send the KX_AUTH
1279 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1280 * we are to find one that is ready.
1281 * @param ax axolotl key context to use
1284 send_kx (struct CadetTunnel *t,
1285 struct CadetTConnection *ct,
1286 struct CadetTunnelAxolotl *ax)
1288 struct CadetConnection *cc;
1289 struct GNUNET_MQ_Envelope *env;
1290 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1291 enum GNUNET_CADET_KX_Flags flags;
1294 ct = get_ready_connection (t);
1297 LOG (GNUNET_ERROR_TYPE_DEBUG,
1298 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1300 estate2s (t->estate));
1301 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1305 LOG (GNUNET_ERROR_TYPE_DEBUG,
1306 "Sending KX on %s via %s using %s in state %s\n",
1309 estate2s (t->estate));
1310 env = GNUNET_MQ_msg (msg,
1311 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1312 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1313 msg->flags = htonl (flags);
1314 msg->cid = *GCC_get_id (cc);
1315 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1316 &msg->ephemeral_key);
1317 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1319 ct->is_ready = GNUNET_NO;
1320 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1321 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1322 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1323 GCT_change_estate (t,
1324 CADET_TUNNEL_KEY_AX_SENT);
1325 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1326 GCT_change_estate (t,
1327 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1334 * Send a KX_AUTH message.
1336 * @param t tunnel on which to send the KX_AUTH
1337 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1338 * we are to find one that is ready.
1339 * @param ax axolotl key context to use
1340 * @param force_reply Force the other peer to reply with a KX_AUTH message
1341 * (set if we would like to transmit right now, but cannot)
1344 send_kx_auth (struct CadetTunnel *t,
1345 struct CadetTConnection *ct,
1346 struct CadetTunnelAxolotl *ax,
1349 struct CadetConnection *cc;
1350 struct GNUNET_MQ_Envelope *env;
1351 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1352 enum GNUNET_CADET_KX_Flags flags;
1354 if ( (NULL == ct) ||
1355 (GNUNET_NO == ct->is_ready) )
1356 ct = get_ready_connection (t);
1359 LOG (GNUNET_ERROR_TYPE_DEBUG,
1360 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1362 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1363 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1366 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1368 LOG (GNUNET_ERROR_TYPE_DEBUG,
1369 "Sending KX_AUTH on %s using %s\n",
1373 env = GNUNET_MQ_msg (msg,
1374 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1375 flags = GNUNET_CADET_KX_FLAG_NONE;
1376 if (GNUNET_YES == force_reply)
1377 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1378 msg->kx.flags = htonl (flags);
1379 msg->kx.cid = *GCC_get_id (cc);
1380 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1381 &msg->kx.ephemeral_key);
1382 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1383 &msg->kx.ratchet_key);
1384 /* Compute authenticator (this is the main difference to #send_kx()) */
1385 GNUNET_CRYPTO_hash (&ax->RK,
1389 /* Compute when to be triggered again; actual job will
1390 be scheduled via #connection_ready_cb() */
1392 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1394 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1396 /* Send via cc, mark it as unready */
1397 ct->is_ready = GNUNET_NO;
1399 /* Update state machine, unless we are already OK */
1400 if (CADET_TUNNEL_KEY_OK != t->estate)
1401 GCT_change_estate (t,
1402 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1410 * Cleanup state used by @a ax.
1412 * @param ax state to free, but not memory of @a ax itself
1415 cleanup_ax (struct CadetTunnelAxolotl *ax)
1417 while (NULL != ax->skipped_head)
1418 delete_skipped_key (ax,
1420 GNUNET_assert (0 == ax->skipped);
1421 GNUNET_free_non_null (ax->kx_0);
1422 GNUNET_free_non_null (ax->DHRs);
1427 * Update our Axolotl key state based on the KX data we received.
1428 * Computes the new chain keys, and root keys, etc, and also checks
1429 * wether this is a replay of the current chain.
1431 * @param[in|out] axolotl chain key state to recompute
1432 * @param pid peer identity of the other peer
1433 * @param ephemeral_key ephemeral public key of the other peer
1434 * @param ratchet_key senders next ephemeral public key
1435 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1436 * root key is already in @a ax and thus the KX is useless;
1437 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1440 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1441 const struct GNUNET_PeerIdentity *pid,
1442 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1443 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1445 struct GNUNET_HashCode key_material[3];
1446 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1447 const char salt[] = "CADET Axolotl salt";
1450 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1452 am_I_alice = GNUNET_YES;
1453 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1455 am_I_alice = GNUNET_NO;
1458 GNUNET_break_op (0);
1459 return GNUNET_SYSERR;
1462 if (0 == memcmp (&ax->DHRr,
1464 sizeof (*ratchet_key)))
1466 LOG (GNUNET_ERROR_TYPE_DEBUG,
1467 "Ratchet key already known. Ignoring KX.\n");
1471 ax->DHRr = *ratchet_key;
1474 if (GNUNET_YES == am_I_alice)
1476 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1477 ephemeral_key, /* B0 */
1482 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1483 &pid->public_key, /* A */
1488 if (GNUNET_YES == am_I_alice)
1490 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1491 &pid->public_key, /* B */
1496 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1497 ephemeral_key, /* B0 */
1504 /* (This is the triple-DH, we could probably safely skip this,
1505 as A0/B0 are already in the key material.) */
1506 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1507 ephemeral_key, /* B0 or A0 */
1511 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1512 salt, sizeof (salt),
1513 &key_material, sizeof (key_material),
1516 if (0 == memcmp (&ax->RK,
1520 LOG (GNUNET_ERROR_TYPE_DEBUG,
1521 "Root key of handshake already known. Ignoring KX.\n");
1526 if (GNUNET_YES == am_I_alice)
1532 ax->ratchet_flag = GNUNET_YES;
1540 ax->ratchet_flag = GNUNET_NO;
1541 ax->ratchet_expiration
1542 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1550 * Try to redo the KX or KX_AUTH handshake, if we can.
1552 * @param cls the `struct CadetTunnel` to do KX for.
1555 retry_kx (void *cls)
1557 struct CadetTunnel *t = cls;
1558 struct CadetTunnelAxolotl *ax;
1561 LOG (GNUNET_ERROR_TYPE_DEBUG,
1562 "Trying to make KX progress on %s in state %s\n",
1564 estate2s (t->estate));
1567 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1568 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1573 case CADET_TUNNEL_KEY_AX_RECV:
1574 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1575 /* We are responding, so only require reply
1576 if WE have a channel waiting. */
1577 if (NULL != t->unverified_ax)
1579 /* Send AX_AUTH so we might get this one verified */
1580 ax = t->unverified_ax;
1584 /* How can this be? */
1591 (0 == GCT_count_channels (t))
1595 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1596 /* We are responding, so only require reply
1597 if WE have a channel waiting. */
1598 if (NULL != t->unverified_ax)
1600 /* Send AX_AUTH so we might get this one verified */
1601 ax = t->unverified_ax;
1605 /* How can this be? */
1612 (0 == GCT_count_channels (t))
1616 case CADET_TUNNEL_KEY_OK:
1617 /* Must have been the *other* peer asking us to
1618 respond with a KX_AUTH. */
1619 if (NULL != t->unverified_ax)
1621 /* Sending AX_AUTH in response to AX so we might get this one verified */
1622 ax = t->unverified_ax;
1626 /* Sending AX_AUTH in response to AX_AUTH */
1639 * Handle KX message that lacks authentication (and which will thus
1640 * only be considered authenticated after we respond with our own
1641 * KX_AUTH and finally successfully decrypt payload).
1643 * @param ct connection/tunnel combo that received encrypted message
1644 * @param msg the key exchange message
1647 GCT_handle_kx (struct CadetTConnection *ct,
1648 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1650 struct CadetTunnel *t = ct->t;
1651 struct CadetTunnelAxolotl *ax;
1655 memcmp (&t->ax.DHRr,
1657 sizeof (msg->ratchet_key)))
1659 LOG (GNUNET_ERROR_TYPE_DEBUG,
1660 "Got duplicate KX. Firing back KX_AUTH.\n");
1668 /* We only keep ONE unverified KX around, so if there is an existing one,
1670 if (NULL != t->unverified_ax)
1673 memcmp (&t->unverified_ax->DHRr,
1675 sizeof (msg->ratchet_key)))
1677 LOG (GNUNET_ERROR_TYPE_DEBUG,
1678 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1686 LOG (GNUNET_ERROR_TYPE_DEBUG,
1687 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1689 memset (t->unverified_ax,
1691 sizeof (struct CadetTunnelAxolotl));
1692 t->unverified_ax->DHRs = t->ax.DHRs;
1693 t->unverified_ax->kx_0 = t->ax.kx_0;
1697 LOG (GNUNET_ERROR_TYPE_DEBUG,
1698 "Creating fresh unverified KX for %s.\n",
1700 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1701 t->unverified_ax->DHRs = t->ax.DHRs;
1702 t->unverified_ax->kx_0 = t->ax.kx_0;
1704 /* Set as the 'current' RK/DHRr the one we are currently using,
1705 so that the duplicate-detection logic of
1706 #update_ax_by_kx can work. */
1707 t->unverified_ax->RK = t->ax.RK;
1708 t->unverified_ax->DHRr = t->ax.DHRr;
1709 t->unverified_attempts = 0;
1710 ax = t->unverified_ax;
1712 /* Update 'ax' by the new key material */
1713 ret = update_ax_by_kx (ax,
1714 GCP_get_id (t->destination),
1715 &msg->ephemeral_key,
1717 GNUNET_break (GNUNET_SYSERR != ret);
1718 if (GNUNET_OK != ret)
1719 return; /* duplicate KX, nothing to do */
1721 /* move ahead in our state machine */
1722 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1723 GCT_change_estate (t,
1724 CADET_TUNNEL_KEY_AX_RECV);
1725 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1726 GCT_change_estate (t,
1727 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1729 /* KX is still not done, try again our end. */
1730 if (CADET_TUNNEL_KEY_OK != t->estate)
1732 if (NULL != t->kx_task)
1733 GNUNET_SCHEDULER_cancel (t->kx_task);
1735 = GNUNET_SCHEDULER_add_now (&retry_kx,
1742 * Handle KX_AUTH message.
1744 * @param ct connection/tunnel combo that received encrypted message
1745 * @param msg the key exchange message
1748 GCT_handle_kx_auth (struct CadetTConnection *ct,
1749 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1751 struct CadetTunnel *t = ct->t;
1752 struct CadetTunnelAxolotl ax_tmp;
1753 struct GNUNET_HashCode kx_auth;
1756 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1757 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1759 /* Confusing, we got a KX_AUTH before we even send our own
1760 KX. This should not happen. We'll send our own KX ASAP anyway,
1761 so let's ignore this here. */
1762 GNUNET_break_op (0);
1765 LOG (GNUNET_ERROR_TYPE_DEBUG,
1766 "Handling KX_AUTH message for %s\n",
1769 /* We do everything in ax_tmp until we've checked the authentication
1770 so we don't clobber anything we care about by accident. */
1773 /* Update 'ax' by the new key material */
1774 ret = update_ax_by_kx (&ax_tmp,
1775 GCP_get_id (t->destination),
1776 &msg->kx.ephemeral_key,
1777 &msg->kx.ratchet_key);
1778 GNUNET_break (GNUNET_OK == ret);
1779 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1782 if (0 != memcmp (&kx_auth,
1786 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1787 we transmitted to the sender, refuse it! */
1788 GNUNET_break_op (0);
1791 /* Yep, we're good. */
1793 if (NULL != t->unverified_ax)
1795 /* We got some "stale" KX before, drop that. */
1796 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1797 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1798 cleanup_ax (t->unverified_ax);
1799 GNUNET_free (t->unverified_ax);
1800 t->unverified_ax = NULL;
1803 /* move ahead in our state machine */
1806 case CADET_TUNNEL_KEY_UNINITIALIZED:
1807 case CADET_TUNNEL_KEY_AX_RECV:
1808 /* Checked above, this is impossible. */
1811 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1812 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1813 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1814 GCT_change_estate (t,
1815 CADET_TUNNEL_KEY_OK);
1817 case CADET_TUNNEL_KEY_OK:
1818 /* Did not expect another KX_AUTH, but so what, still acceptable.
1819 Nothing to do here. */
1826 /* ************************************** end core crypto ***************************** */
1830 * Compute the next free channel tunnel number for this tunnel.
1832 * @param t the tunnel
1833 * @return unused number that can uniquely identify a channel in the tunnel
1835 static struct GNUNET_CADET_ChannelTunnelNumber
1836 get_next_free_ctn (struct CadetTunnel *t)
1838 #define HIGH_BIT 0x8000000
1839 struct GNUNET_CADET_ChannelTunnelNumber ret;
1844 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1845 GCP_get_id (GCT_get_destination (t)));
1851 GNUNET_assert (0); // loopback must never go here!
1852 ctn = ntohl (t->next_ctn.cn);
1854 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1857 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1859 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1860 ret.cn = ntohl (ctn);
1866 * Add a channel to a tunnel, and notify channel that we are ready
1867 * for transmission if we are already up. Otherwise that notification
1868 * will be done later in #notify_tunnel_up_cb().
1872 * @return unique number identifying @a ch within @a t
1874 struct GNUNET_CADET_ChannelTunnelNumber
1875 GCT_add_channel (struct CadetTunnel *t,
1876 struct CadetChannel *ch)
1878 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1880 ctn = get_next_free_ctn (t);
1881 GNUNET_assert (GNUNET_YES ==
1882 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1885 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1886 LOG (GNUNET_ERROR_TYPE_DEBUG,
1887 "Adding %s to %s\n",
1892 case CADET_TUNNEL_KEY_UNINITIALIZED:
1893 /* waiting for connection to start KX */
1895 case CADET_TUNNEL_KEY_AX_RECV:
1896 case CADET_TUNNEL_KEY_AX_SENT:
1897 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1898 /* we're currently waiting for KX to complete */
1900 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1901 /* waiting for OTHER peer to send us data,
1902 we might need to prompt more aggressively! */
1903 if (NULL == t->kx_task)
1905 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1909 case CADET_TUNNEL_KEY_OK:
1910 /* We are ready. Tell the new channel that we are up. */
1911 GCCH_tunnel_up (ch);
1919 * We lost a connection, remove it from our list and clean up
1920 * the connection object itself.
1922 * @param ct binding of connection to tunnel of the connection that was lost.
1925 GCT_connection_lost (struct CadetTConnection *ct)
1927 struct CadetTunnel *t = ct->t;
1929 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1937 * This tunnel is no longer used, destroy it.
1939 * @param cls the idle tunnel
1942 destroy_tunnel (void *cls)
1944 struct CadetTunnel *t = cls;
1945 struct CadetTConnection *ct;
1946 struct CadetTunnelQueueEntry *tq;
1948 t->destroy_task = NULL;
1949 LOG (GNUNET_ERROR_TYPE_DEBUG,
1950 "Destroying idle %s\n",
1952 GNUNET_assert (0 == GCT_count_channels (t));
1953 while (NULL != (ct = t->connection_head))
1955 struct CadetConnection *cc;
1957 GNUNET_assert (ct->t == t);
1959 GCT_connection_lost (ct);
1960 GCC_destroy_without_tunnel (cc);
1962 while (NULL != (tq = t->tq_head))
1964 if (NULL != tq->cont)
1965 tq->cont (tq->cont_cls);
1966 GCT_send_cancel (tq);
1968 GCP_drop_tunnel (t->destination,
1970 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1971 if (NULL != t->maintain_connections_task)
1973 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1974 t->maintain_connections_task = NULL;
1976 if (NULL != t->send_task)
1978 GNUNET_SCHEDULER_cancel (t->send_task);
1979 t->send_task = NULL;
1981 if (NULL != t->kx_task)
1983 GNUNET_SCHEDULER_cancel (t->kx_task);
1986 GNUNET_MST_destroy (t->mst);
1987 GNUNET_MQ_destroy (t->mq);
1988 if (NULL != t->unverified_ax)
1990 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1991 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1992 cleanup_ax (t->unverified_ax);
1993 GNUNET_free (t->unverified_ax);
1995 cleanup_ax (&t->ax);
2001 * Remove a channel from a tunnel.
2005 * @param ctn unique number identifying @a ch within @a t
2008 GCT_remove_channel (struct CadetTunnel *t,
2009 struct CadetChannel *ch,
2010 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2012 LOG (GNUNET_ERROR_TYPE_DEBUG,
2013 "Removing %s from %s\n",
2016 GNUNET_assert (GNUNET_YES ==
2017 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2021 GCT_count_channels (t))
2023 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2031 * Destroy remaining channels during shutdown.
2033 * @param cls the `struct CadetTunnel` of the channel
2034 * @param key key of the channel
2035 * @param value the `struct CadetChannel`
2036 * @return #GNUNET_OK (continue to iterate)
2039 destroy_remaining_channels (void *cls,
2043 struct CadetChannel *ch = value;
2045 GCCH_handle_remote_destroy (ch);
2051 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2053 * @param t tunnel to destroy
2056 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2058 GNUNET_assert (GNUNET_YES == shutting_down);
2059 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2060 &destroy_remaining_channels,
2063 GCT_count_channels (t));
2064 if (NULL != t->destroy_task)
2066 GNUNET_SCHEDULER_cancel (t->destroy_task);
2067 t->destroy_task = NULL;
2074 * Send normal payload from queue in @a t via connection @a ct.
2075 * Does nothing if our payload queue is empty.
2077 * @param t tunnel to send data from
2078 * @param ct connection to use for transmission (is ready)
2081 try_send_normal_payload (struct CadetTunnel *t,
2082 struct CadetTConnection *ct)
2084 struct CadetTunnelQueueEntry *tq;
2086 GNUNET_assert (GNUNET_YES == ct->is_ready);
2090 /* no messages pending right now */
2091 LOG (GNUNET_ERROR_TYPE_DEBUG,
2092 "Not sending payload of %s on ready %s (nothing pending)\n",
2097 /* ready to send message 'tq' on tunnel 'ct' */
2098 GNUNET_assert (t == tq->t);
2099 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2102 if (NULL != tq->cid)
2103 *tq->cid = *GCC_get_id (ct->cc);
2104 ct->is_ready = GNUNET_NO;
2105 LOG (GNUNET_ERROR_TYPE_DEBUG,
2106 "Sending payload of %s on %s\n",
2109 GCC_transmit (ct->cc,
2111 if (NULL != tq->cont)
2112 tq->cont (tq->cont_cls);
2118 * A connection is @a is_ready for transmission. Looks at our message
2119 * queue and if there is a message, sends it out via the connection.
2121 * @param cls the `struct CadetTConnection` that is @a is_ready
2122 * @param is_ready #GNUNET_YES if connection are now ready,
2123 * #GNUNET_NO if connection are no longer ready
2126 connection_ready_cb (void *cls,
2129 struct CadetTConnection *ct = cls;
2130 struct CadetTunnel *t = ct->t;
2132 if (GNUNET_NO == is_ready)
2134 LOG (GNUNET_ERROR_TYPE_DEBUG,
2135 "%s no longer ready for %s\n",
2138 ct->is_ready = GNUNET_NO;
2141 ct->is_ready = GNUNET_YES;
2142 LOG (GNUNET_ERROR_TYPE_DEBUG,
2143 "%s now ready for %s in state %s\n",
2146 estate2s (t->estate));
2149 case CADET_TUNNEL_KEY_UNINITIALIZED:
2150 /* Do not begin KX if WE have no channels waiting! */
2151 if (0 == GCT_count_channels (t))
2153 /* We are uninitialized, just transmit immediately,
2154 without undue delay. */
2155 if (NULL != t->kx_task)
2157 GNUNET_SCHEDULER_cancel (t->kx_task);
2164 case CADET_TUNNEL_KEY_AX_RECV:
2165 case CADET_TUNNEL_KEY_AX_SENT:
2166 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2167 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2168 /* we're currently waiting for KX to complete, schedule job */
2169 if (NULL == t->kx_task)
2171 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2175 case CADET_TUNNEL_KEY_OK:
2176 if (GNUNET_YES == t->kx_auth_requested)
2178 if (NULL != t->kx_task)
2180 GNUNET_SCHEDULER_cancel (t->kx_task);
2189 try_send_normal_payload (t,
2197 * Called when either we have a new connection, or a new message in the
2198 * queue, or some existing connection has transmission capacity. Looks
2199 * at our message queue and if there is a message, picks a connection
2202 * @param cls the `struct CadetTunnel` to process messages on
2205 trigger_transmissions (void *cls)
2207 struct CadetTunnel *t = cls;
2208 struct CadetTConnection *ct;
2210 t->send_task = NULL;
2211 if (NULL == t->tq_head)
2212 return; /* no messages pending right now */
2213 ct = get_ready_connection (t);
2215 return; /* no connections ready */
2216 try_send_normal_payload (t,
2222 * Consider using the path @a p for the tunnel @a t.
2223 * The tunnel destination is at offset @a off in path @a p.
2225 * @param cls our tunnel
2226 * @param path a path to our destination
2227 * @param off offset of the destination on path @a path
2228 * @return #GNUNET_YES (should keep iterating)
2231 consider_path_cb (void *cls,
2232 struct CadetPeerPath *path,
2235 struct CadetTunnel *t = cls;
2236 unsigned int min_length = UINT_MAX;
2237 GNUNET_CONTAINER_HeapCostType max_desire = 0;
2238 struct CadetTConnection *ct;
2240 /* Check if we care about the new path. */
2241 for (ct = t->connection_head;
2245 struct CadetPeerPath *ps;
2247 ps = GCC_get_path (ct->cc);
2250 LOG (GNUNET_ERROR_TYPE_DEBUG,
2251 "Ignoring duplicate path %s for %s.\n",
2254 return GNUNET_YES; /* duplicate */
2256 min_length = GNUNET_MIN (min_length,
2257 GCPP_get_length (ps));
2258 max_desire = GNUNET_MAX (max_desire,
2259 GCPP_get_desirability (ps));
2262 /* FIXME: not sure we should really just count
2263 'num_connections' here, as they may all have
2264 consistently failed to connect. */
2266 /* We iterate by increasing path length; if we have enough paths and
2267 this one is more than twice as long than what we are currently
2268 using, then ignore all of these super-long ones! */
2269 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2270 (min_length * 2 < off) )
2272 LOG (GNUNET_ERROR_TYPE_DEBUG,
2273 "Ignoring paths of length %u, they are way too long.\n",
2277 /* If we have enough paths and this one looks no better, ignore it. */
2278 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2279 (min_length < GCPP_get_length (path)) &&
2280 (max_desire > GCPP_get_desirability (path)) )
2282 LOG (GNUNET_ERROR_TYPE_DEBUG,
2283 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2284 GCPP_get_length (path),
2285 (unsigned long long) GCPP_get_desirability (path),
2286 GCP_2s (t->destination));
2290 /* Path is interesting (better by some metric, or we don't have
2291 enough paths yet). */
2292 ct = GNUNET_new (struct CadetTConnection);
2293 ct->created = GNUNET_TIME_absolute_get ();
2295 ct->cc = GCC_create (t->destination,
2298 &connection_ready_cb,
2300 /* FIXME: schedule job to kill connection (and path?) if it takes
2301 too long to get ready! (And track performance data on how long
2302 other connections took with the tunnel!)
2303 => Note: to be done within 'connection'-logic! */
2304 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2307 t->num_connections++;
2308 LOG (GNUNET_ERROR_TYPE_DEBUG,
2309 "Found interesting path %s for %s, created %s\n",
2318 * Function called to maintain the connections underlying our tunnel.
2319 * Tries to maintain (incl. tear down) connections for the tunnel, and
2320 * if there is a significant change, may trigger transmissions.
2322 * Basically, needs to check if there are connections that perform
2323 * badly, and if so eventually kill them and trigger a replacement.
2324 * The strategy is to open one more connection than
2325 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2326 * least-performing one, and then inquire for new ones.
2328 * @param cls the `struct CadetTunnel`
2331 maintain_connections_cb (void *cls)
2333 struct CadetTunnel *t = cls;
2335 t->maintain_connections_task = NULL;
2336 LOG (GNUNET_ERROR_TYPE_DEBUG,
2337 "Performing connection maintenance for %s.\n",
2340 (void) GCP_iterate_paths (t->destination,
2344 GNUNET_break (0); // FIXME: implement!
2349 * Consider using the path @a p for the tunnel @a t.
2350 * The tunnel destination is at offset @a off in path @a p.
2352 * @param cls our tunnel
2353 * @param path a path to our destination
2354 * @param off offset of the destination on path @a path
2357 GCT_consider_path (struct CadetTunnel *t,
2358 struct CadetPeerPath *p,
2361 (void) consider_path_cb (t,
2368 * We got a keepalive. Track in statistics.
2370 * @param cls the `struct CadetTunnel` for which we decrypted the message
2371 * @param msg the message we received on the tunnel
2374 handle_plaintext_keepalive (void *cls,
2375 const struct GNUNET_MessageHeader *msg)
2377 struct CadetTunnel *t = cls;
2379 LOG (GNUNET_ERROR_TYPE_DEBUG,
2380 "Received KEEPALIVE on %s\n",
2382 GNUNET_STATISTICS_update (stats,
2383 "# keepalives received",
2390 * Check that @a msg is well-formed.
2392 * @param cls the `struct CadetTunnel` for which we decrypted the message
2393 * @param msg the message we received on the tunnel
2394 * @return #GNUNET_OK (any variable-size payload goes)
2397 check_plaintext_data (void *cls,
2398 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2405 * We received payload data for a channel. Locate the channel
2406 * and process the data, or return an error if the channel is unknown.
2408 * @param cls the `struct CadetTunnel` for which we decrypted the message
2409 * @param msg the message we received on the tunnel
2412 handle_plaintext_data (void *cls,
2413 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2415 struct CadetTunnel *t = cls;
2416 struct CadetChannel *ch;
2418 ch = lookup_channel (t,
2422 /* We don't know about such a channel, might have been destroyed on our
2423 end in the meantime, or never existed. Send back a DESTROY. */
2424 LOG (GNUNET_ERROR_TYPE_DEBUG,
2425 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2426 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2427 ntohl (msg->ctn.cn));
2428 GCT_send_channel_destroy (t,
2432 GCCH_handle_channel_plaintext_data (ch,
2438 * We received an acknowledgement for data we sent on a channel.
2439 * Locate the channel and process it, or return an error if the
2440 * channel is unknown.
2442 * @param cls the `struct CadetTunnel` for which we decrypted the message
2443 * @param ack the message we received on the tunnel
2446 handle_plaintext_data_ack (void *cls,
2447 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2449 struct CadetTunnel *t = cls;
2450 struct CadetChannel *ch;
2452 ch = lookup_channel (t,
2456 /* We don't know about such a channel, might have been destroyed on our
2457 end in the meantime, or never existed. Send back a DESTROY. */
2458 LOG (GNUNET_ERROR_TYPE_DEBUG,
2459 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2460 ntohl (ack->ctn.cn));
2461 GCT_send_channel_destroy (t,
2465 GCCH_handle_channel_plaintext_data_ack (ch,
2471 * We have received a request to open a channel to a port from
2472 * another peer. Creates the incoming channel.
2474 * @param cls the `struct CadetTunnel` for which we decrypted the message
2475 * @param copen the message we received on the tunnel
2478 handle_plaintext_channel_open (void *cls,
2479 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2481 struct CadetTunnel *t = cls;
2482 struct CadetChannel *ch;
2484 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2485 ntohl (copen->ctn.cn));
2488 LOG (GNUNET_ERROR_TYPE_DEBUG,
2489 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2490 GNUNET_h2s (&copen->port),
2493 GCCH_handle_duplicate_open (ch);
2496 LOG (GNUNET_ERROR_TYPE_DEBUG,
2497 "Receicved channel OPEN on port %s from %s\n",
2498 GNUNET_h2s (&copen->port),
2500 ch = GCCH_channel_incoming_new (t,
2503 ntohl (copen->opt));
2504 GNUNET_assert (GNUNET_OK ==
2505 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2506 ntohl (copen->ctn.cn),
2508 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2513 * Send a DESTROY message via the tunnel.
2515 * @param t the tunnel to transmit over
2516 * @param ctn ID of the channel to destroy
2519 GCT_send_channel_destroy (struct CadetTunnel *t,
2520 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2522 struct GNUNET_CADET_ChannelManageMessage msg;
2524 LOG (GNUNET_ERROR_TYPE_DEBUG,
2525 "Sending DESTORY message for channel ID %u\n",
2527 msg.header.size = htons (sizeof (msg));
2528 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2529 msg.reserved = htonl (0);
2539 * We have received confirmation from the target peer that the
2540 * given channel could be established (the port is open).
2543 * @param cls the `struct CadetTunnel` for which we decrypted the message
2544 * @param cm the message we received on the tunnel
2547 handle_plaintext_channel_open_ack (void *cls,
2548 const struct GNUNET_CADET_ChannelManageMessage *cm)
2550 struct CadetTunnel *t = cls;
2551 struct CadetChannel *ch;
2553 ch = lookup_channel (t,
2557 /* We don't know about such a channel, might have been destroyed on our
2558 end in the meantime, or never existed. Send back a DESTROY. */
2559 LOG (GNUNET_ERROR_TYPE_DEBUG,
2560 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2561 ntohl (cm->ctn.cn));
2562 GCT_send_channel_destroy (t,
2566 LOG (GNUNET_ERROR_TYPE_DEBUG,
2567 "Received channel OPEN_ACK on channel %s from %s\n",
2570 GCCH_handle_channel_open_ack (ch);
2575 * We received a message saying that a channel should be destroyed.
2576 * Pass it on to the correct channel.
2578 * @param cls the `struct CadetTunnel` for which we decrypted the message
2579 * @param cm the message we received on the tunnel
2582 handle_plaintext_channel_destroy (void *cls,
2583 const struct GNUNET_CADET_ChannelManageMessage *cm)
2585 struct CadetTunnel *t = cls;
2586 struct CadetChannel *ch;
2588 ch = lookup_channel (t,
2592 /* We don't know about such a channel, might have been destroyed on our
2593 end in the meantime, or never existed. */
2594 LOG (GNUNET_ERROR_TYPE_DEBUG,
2595 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2596 ntohl (cm->ctn.cn));
2599 LOG (GNUNET_ERROR_TYPE_DEBUG,
2600 "Receicved channel DESTROY on %s from %s\n",
2603 GCCH_handle_remote_destroy (ch);
2608 * Handles a message we decrypted, by injecting it into
2609 * our message queue (which will do the dispatching).
2611 * @param cls the `struct CadetTunnel` that got the message
2612 * @param msg the message
2613 * @return #GNUNET_OK (continue to process)
2616 handle_decrypted (void *cls,
2617 const struct GNUNET_MessageHeader *msg)
2619 struct CadetTunnel *t = cls;
2621 GNUNET_MQ_inject_message (t->mq,
2628 * Function called if we had an error processing
2629 * an incoming decrypted message.
2631 * @param cls the `struct CadetTunnel`
2632 * @param error error code
2635 decrypted_error_cb (void *cls,
2636 enum GNUNET_MQ_Error error)
2638 GNUNET_break_op (0);
2643 * Create a tunnel to @a destionation. Must only be called
2644 * from within #GCP_get_tunnel().
2646 * @param destination where to create the tunnel to
2647 * @return new tunnel to @a destination
2649 struct CadetTunnel *
2650 GCT_create_tunnel (struct CadetPeer *destination)
2652 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2653 struct GNUNET_MQ_MessageHandler handlers[] = {
2654 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2655 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2656 struct GNUNET_MessageHeader,
2658 GNUNET_MQ_hd_var_size (plaintext_data,
2659 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2660 struct GNUNET_CADET_ChannelAppDataMessage,
2662 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2663 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2664 struct GNUNET_CADET_ChannelDataAckMessage,
2666 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2667 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2668 struct GNUNET_CADET_ChannelOpenMessage,
2670 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2671 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2672 struct GNUNET_CADET_ChannelManageMessage,
2674 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2675 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2676 struct GNUNET_CADET_ChannelManageMessage,
2678 GNUNET_MQ_handler_end ()
2681 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2682 new_ephemeral (&t->ax);
2683 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2684 t->destination = destination;
2685 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2686 t->maintain_connections_task
2687 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2689 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2694 &decrypted_error_cb,
2696 t->mst = GNUNET_MST_create (&handle_decrypted,
2703 * Add a @a connection to the @a tunnel.
2706 * @param cid connection identifer to use for the connection
2707 * @param path path to use for the connection
2708 * @return #GNUNET_OK on success,
2709 * #GNUNET_SYSERR on failure (duplicate connection)
2712 GCT_add_inbound_connection (struct CadetTunnel *t,
2713 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2714 struct CadetPeerPath *path)
2716 struct CadetTConnection *ct;
2718 ct = GNUNET_new (struct CadetTConnection);
2719 ct->created = GNUNET_TIME_absolute_get ();
2721 ct->cc = GCC_create_inbound (t->destination,
2725 &connection_ready_cb,
2729 LOG (GNUNET_ERROR_TYPE_DEBUG,
2730 "%s refused inbound %s (duplicate)\n",
2734 return GNUNET_SYSERR;
2736 /* FIXME: schedule job to kill connection (and path?) if it takes
2737 too long to get ready! (And track performance data on how long
2738 other connections took with the tunnel!)
2739 => Note: to be done within 'connection'-logic! */
2740 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2743 t->num_connections++;
2744 LOG (GNUNET_ERROR_TYPE_DEBUG,
2753 * Handle encrypted message.
2755 * @param ct connection/tunnel combo that received encrypted message
2756 * @param msg the encrypted message to decrypt
2759 GCT_handle_encrypted (struct CadetTConnection *ct,
2760 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2762 struct CadetTunnel *t = ct->t;
2763 uint16_t size = ntohs (msg->header.size);
2764 char cbuf [size] GNUNET_ALIGN;
2765 ssize_t decrypted_size;
2767 LOG (GNUNET_ERROR_TYPE_DEBUG,
2768 "%s received %u bytes of encrypted data in state %d\n",
2770 (unsigned int) size,
2775 case CADET_TUNNEL_KEY_UNINITIALIZED:
2776 case CADET_TUNNEL_KEY_AX_RECV:
2777 /* We did not even SEND our KX, how can the other peer
2778 send us encrypted data? */
2779 GNUNET_break_op (0);
2781 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2782 /* We send KX, and other peer send KX to us at the same time.
2783 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
2784 GNUNET_STATISTICS_update (stats,
2785 "# received encrypted without KX_AUTH",
2788 if (NULL != t->kx_task)
2790 GNUNET_SCHEDULER_cancel (t->kx_task);
2798 case CADET_TUNNEL_KEY_AX_SENT:
2799 /* We did not get the KX of the other peer, but that
2800 might have been lost. Send our KX again immediately. */
2801 GNUNET_STATISTICS_update (stats,
2802 "# received encrypted without KX",
2805 if (NULL != t->kx_task)
2807 GNUNET_SCHEDULER_cancel (t->kx_task);
2814 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2815 /* Great, first payload, we might graduate to OK! */
2816 case CADET_TUNNEL_KEY_OK:
2817 /* We are up and running, all good. */
2821 GNUNET_STATISTICS_update (stats,
2822 "# received encrypted",
2825 decrypted_size = -1;
2826 if (CADET_TUNNEL_KEY_OK == t->estate)
2828 /* We have well-established key material available,
2829 try that. (This is the common case.) */
2830 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2836 if ( (-1 == decrypted_size) &&
2837 (NULL != t->unverified_ax) )
2839 /* We have un-authenticated KX material available. We should try
2840 this as a back-up option, in case the sender crashed and
2842 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2846 if (-1 != decrypted_size)
2848 /* It worked! Treat this as authentication of the AX data! */
2849 t->ax.DHRs = NULL; /* aliased with ax.DHRs */
2850 t->ax.kx_0 = NULL; /* aliased with ax.DHRs */
2851 cleanup_ax (&t->ax);
2852 t->ax = *t->unverified_ax;
2853 GNUNET_free (t->unverified_ax);
2854 t->unverified_ax = NULL;
2856 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
2858 /* First time it worked, move tunnel into production! */
2859 GCT_change_estate (t,
2860 CADET_TUNNEL_KEY_OK);
2861 if (NULL != t->send_task)
2862 GNUNET_SCHEDULER_cancel (t->send_task);
2863 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2867 if (NULL != t->unverified_ax)
2869 /* We had unverified KX material that was useless; so increment
2870 counter and eventually move to ignore it. Note that we even do
2871 this increment if we successfully decrypted with the old KX
2872 material and thus didn't even both with the new one. This is
2873 the ideal case, as a malicious injection of bogus KX data
2874 basically only causes us to increment a counter a few times. */
2875 t->unverified_attempts++;
2876 LOG (GNUNET_ERROR_TYPE_DEBUG,
2877 "Failed to decrypt message with unverified KX data %u times\n",
2878 t->unverified_attempts);
2879 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2881 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
2882 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
2883 cleanup_ax (t->unverified_ax);
2884 GNUNET_free (t->unverified_ax);
2885 t->unverified_ax = NULL;
2889 if (-1 == decrypted_size)
2891 /* Decryption failed for good, complain. */
2892 GNUNET_break_op (0);
2893 LOG (GNUNET_ERROR_TYPE_WARNING,
2894 "%s failed to decrypt and validate encrypted data\n",
2896 GNUNET_STATISTICS_update (stats,
2897 "# unable to decrypt",
2903 /* The MST will ultimately call #handle_decrypted() on each message. */
2904 GNUNET_break_op (GNUNET_OK ==
2905 GNUNET_MST_from_buffer (t->mst,
2914 * Sends an already built message on a tunnel, encrypting it and
2915 * choosing the best connection if not provided.
2917 * @param message Message to send. Function modifies it.
2918 * @param t Tunnel on which this message is transmitted.
2919 * @param cont Continuation to call once message is really sent.
2920 * @param cont_cls Closure for @c cont.
2921 * @return Handle to cancel message
2923 struct CadetTunnelQueueEntry *
2924 GCT_send (struct CadetTunnel *t,
2925 const struct GNUNET_MessageHeader *message,
2926 GNUNET_SCHEDULER_TaskCallback cont,
2929 struct CadetTunnelQueueEntry *tq;
2930 uint16_t payload_size;
2931 struct GNUNET_MQ_Envelope *env;
2932 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2934 if (CADET_TUNNEL_KEY_OK != t->estate)
2939 payload_size = ntohs (message->size);
2940 LOG (GNUNET_ERROR_TYPE_DEBUG,
2941 "Encrypting %u bytes for %s\n",
2942 (unsigned int) payload_size,
2944 env = GNUNET_MQ_msg_extra (ax_msg,
2946 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2947 t_ax_encrypt (&t->ax,
2951 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2952 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2953 /* FIXME: we should do this once, not once per message;
2954 this is a point multiplication, and DHRs does not
2955 change all the time. */
2956 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2957 &ax_msg->ax_header.DHRs);
2958 t_h_encrypt (&t->ax,
2960 t_hmac (&ax_msg->ax_header,
2961 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2966 tq = GNUNET_malloc (sizeof (*tq));
2969 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2971 tq->cont_cls = cont_cls;
2972 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2975 if (NULL != t->send_task)
2976 GNUNET_SCHEDULER_cancel (t->send_task);
2978 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2985 * Cancel a previously sent message while it's in the queue.
2987 * ONLY can be called before the continuation given to the send
2988 * function is called. Once the continuation is called, the message is
2989 * no longer in the queue!
2991 * @param tq Handle to the queue entry to cancel.
2994 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2996 struct CadetTunnel *t = tq->t;
2998 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3001 GNUNET_MQ_discard (tq->env);
3007 * Iterate over all connections of a tunnel.
3009 * @param t Tunnel whose connections to iterate.
3010 * @param iter Iterator.
3011 * @param iter_cls Closure for @c iter.
3014 GCT_iterate_connections (struct CadetTunnel *t,
3015 GCT_ConnectionIterator iter,
3018 for (struct CadetTConnection *ct = t->connection_head;
3027 * Closure for #iterate_channels_cb.
3034 GCT_ChannelIterator iter;
3037 * Closure for @e iter.
3044 * Helper function for #GCT_iterate_channels.
3046 * @param cls the `struct ChanIterCls`
3048 * @param value a `struct CadetChannel`
3049 * @return #GNUNET_OK
3052 iterate_channels_cb (void *cls,
3056 struct ChanIterCls *ctx = cls;
3057 struct CadetChannel *ch = value;
3059 ctx->iter (ctx->iter_cls,
3066 * Iterate over all channels of a tunnel.
3068 * @param t Tunnel whose channels to iterate.
3069 * @param iter Iterator.
3070 * @param iter_cls Closure for @c iter.
3073 GCT_iterate_channels (struct CadetTunnel *t,
3074 GCT_ChannelIterator iter,
3077 struct ChanIterCls ctx;
3080 ctx.iter_cls = iter_cls;
3081 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3082 &iterate_channels_cb,
3089 * Call #GCCH_debug() on a channel.
3091 * @param cls points to the log level to use
3093 * @param value the `struct CadetChannel` to dump
3094 * @return #GNUNET_OK (continue iteration)
3097 debug_channel (void *cls,
3101 const enum GNUNET_ErrorType *level = cls;
3102 struct CadetChannel *ch = value;
3104 GCCH_debug (ch, *level);
3109 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3113 * Log all possible info about the tunnel state.
3115 * @param t Tunnel to debug.
3116 * @param level Debug level to use.
3119 GCT_debug (const struct CadetTunnel *t,
3120 enum GNUNET_ErrorType level)
3122 struct CadetTConnection *iter_c;
3125 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3127 __FILE__, __FUNCTION__, __LINE__);
3132 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3134 estate2s (t->estate),
3136 t->num_connections);
3139 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3143 "TTT connections:\n");
3144 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
3145 GCC_debug (iter_c->cc,
3149 "TTT TUNNEL END\n");
3153 /* end of gnunet-service-cadet-new_tunnels.c */