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 it.
1279 * @param ax axolotl key context to use
1282 send_kx (struct CadetTunnel *t,
1283 struct CadetTunnelAxolotl *ax)
1285 struct CadetTConnection *ct;
1286 struct CadetConnection *cc;
1287 struct GNUNET_MQ_Envelope *env;
1288 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1289 enum GNUNET_CADET_KX_Flags flags;
1291 ct = get_ready_connection (t);
1294 LOG (GNUNET_ERROR_TYPE_DEBUG,
1295 "Wanted to send KX on %s, but no connection is ready, deferring\n",
1297 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1301 LOG (GNUNET_ERROR_TYPE_DEBUG,
1302 "Sending KX on %s using %s in state %s\n",
1305 estate2s (t->estate));
1307 env = GNUNET_MQ_msg (msg,
1308 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1309 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1310 msg->flags = htonl (flags);
1311 msg->cid = *GCC_get_id (cc);
1312 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1313 &msg->ephemeral_key);
1314 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1316 ct->is_ready = GNUNET_NO;
1317 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1318 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1319 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1320 GCT_change_estate (t,
1321 CADET_TUNNEL_KEY_AX_SENT);
1322 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1323 GCT_change_estate (t,
1324 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1331 * Send a KX_AUTH message.
1333 * @param t Tunnel on which to send it.
1334 * @param ax axolotl key context to use
1335 * @param force_reply Force the other peer to reply with a KX_AUTH message
1336 * (set if we would like to transmit right now, but cannot)
1339 send_kx_auth (struct CadetTunnel *t,
1340 struct CadetTunnelAxolotl *ax,
1343 struct CadetTConnection *ct;
1344 struct CadetConnection *cc;
1345 struct GNUNET_MQ_Envelope *env;
1346 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1347 enum GNUNET_CADET_KX_Flags flags;
1349 ct = get_ready_connection (t);
1352 LOG (GNUNET_ERROR_TYPE_DEBUG,
1353 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1355 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1356 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1359 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1361 LOG (GNUNET_ERROR_TYPE_DEBUG,
1362 "Sending KX_AUTH on %s using %s\n",
1366 env = GNUNET_MQ_msg (msg,
1367 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1368 flags = GNUNET_CADET_KX_FLAG_NONE;
1369 if (GNUNET_YES == force_reply)
1370 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1371 msg->kx.flags = htonl (flags);
1372 msg->kx.cid = *GCC_get_id (cc);
1373 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1374 &msg->kx.ephemeral_key);
1375 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1376 &msg->kx.ratchet_key);
1377 /* Compute authenticator (this is the main difference to #send_kx()) */
1378 GNUNET_CRYPTO_hash (&ax->RK,
1382 /* Compute when to be triggered again; actual job will
1383 be scheduled via #connection_ready_cb() */
1385 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1387 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1389 /* Send via cc, mark it as unready */
1390 ct->is_ready = GNUNET_NO;
1392 /* Update state machine, unless we are already OK */
1393 if (CADET_TUNNEL_KEY_OK != t->estate)
1394 GCT_change_estate (t,
1395 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1403 * Cleanup state used by @a ax.
1405 * @param ax state to free, but not memory of @a ax itself
1408 cleanup_ax (struct CadetTunnelAxolotl *ax)
1410 while (NULL != ax->skipped_head)
1411 delete_skipped_key (ax,
1413 GNUNET_assert (0 == ax->skipped);
1414 GNUNET_free_non_null (ax->kx_0);
1415 GNUNET_free_non_null (ax->DHRs);
1420 * Update our Axolotl key state based on the KX data we received.
1421 * Computes the new chain keys, and root keys, etc, and also checks
1422 * wether this is a replay of the current chain.
1424 * @param[in|out] axolotl chain key state to recompute
1425 * @param pid peer identity of the other peer
1426 * @param ephemeral_key ephemeral public key of the other peer
1427 * @param ratchet_key senders next ephemeral public key
1428 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1429 * root key is already in @a ax and thus the KX is useless;
1430 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1433 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1434 const struct GNUNET_PeerIdentity *pid,
1435 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1436 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1438 struct GNUNET_HashCode key_material[3];
1439 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1440 const char salt[] = "CADET Axolotl salt";
1443 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1445 am_I_alice = GNUNET_YES;
1446 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1448 am_I_alice = GNUNET_NO;
1451 GNUNET_break_op (0);
1452 return GNUNET_SYSERR;
1455 if (0 == memcmp (&ax->DHRr,
1457 sizeof (*ratchet_key)))
1459 LOG (GNUNET_ERROR_TYPE_DEBUG,
1460 "Ratchet key already known. Ignoring KX.\n");
1464 ax->DHRr = *ratchet_key;
1467 if (GNUNET_YES == am_I_alice)
1469 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1470 ephemeral_key, /* B0 */
1475 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1476 &pid->public_key, /* A */
1481 if (GNUNET_YES == am_I_alice)
1483 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1484 &pid->public_key, /* B */
1489 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1490 ephemeral_key, /* B0 */
1497 /* (This is the triple-DH, we could probably safely skip this,
1498 as A0/B0 are already in the key material.) */
1499 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1500 ephemeral_key, /* B0 or A0 */
1504 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1505 salt, sizeof (salt),
1506 &key_material, sizeof (key_material),
1509 if (0 == memcmp (&ax->RK,
1513 LOG (GNUNET_ERROR_TYPE_DEBUG,
1514 "Root key of handshake already known. Ignoring KX.\n");
1519 if (GNUNET_YES == am_I_alice)
1525 ax->ratchet_flag = GNUNET_YES;
1533 ax->ratchet_flag = GNUNET_NO;
1534 ax->ratchet_expiration
1535 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1543 * Try to redo the KX or KX_AUTH handshake, if we can.
1545 * @param cls the `struct CadetTunnel` to do KX for.
1548 retry_kx (void *cls)
1550 struct CadetTunnel *t = cls;
1551 struct CadetTunnelAxolotl *ax;
1554 LOG (GNUNET_ERROR_TYPE_DEBUG,
1555 "Trying to make KX progress on %s in state %s\n",
1557 estate2s (t->estate));
1560 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1561 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1565 case CADET_TUNNEL_KEY_AX_RECV:
1566 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1567 /* We are responding, so only require reply
1568 if WE have a channel waiting. */
1569 if (NULL != t->unverified_ax)
1571 /* Send AX_AUTH so we might get this one verified */
1572 ax = t->unverified_ax;
1576 /* How can this be? */
1582 (0 == GCT_count_channels (t))
1586 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1587 /* We are responding, so only require reply
1588 if WE have a channel waiting. */
1589 if (NULL != t->unverified_ax)
1591 /* Send AX_AUTH so we might get this one verified */
1592 ax = t->unverified_ax;
1596 /* How can this be? */
1602 (0 == GCT_count_channels (t))
1606 case CADET_TUNNEL_KEY_OK:
1607 /* Must have been the *other* peer asking us to
1608 respond with a KX_AUTH. */
1609 if (NULL != t->unverified_ax)
1611 /* Sending AX_AUTH in response to AX so we might get this one verified */
1612 ax = t->unverified_ax;
1616 /* Sending AX_AUTH in response to AX_AUTH */
1628 * Handle KX message that lacks authentication (and which will thus
1629 * only be considered authenticated after we respond with our own
1630 * KX_AUTH and finally successfully decrypt payload).
1632 * @param ct connection/tunnel combo that received encrypted message
1633 * @param msg the key exchange message
1636 GCT_handle_kx (struct CadetTConnection *ct,
1637 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1639 struct CadetTunnel *t = ct->t;
1640 struct CadetTunnelAxolotl *ax;
1644 memcmp (&t->ax.DHRr,
1646 sizeof (msg->ratchet_key)))
1648 LOG (GNUNET_ERROR_TYPE_DEBUG,
1649 "Got duplicate KX. Firing back KX_AUTH.\n");
1656 /* We only keep ONE unverified KX around, so if there is an existing one,
1658 if (NULL != t->unverified_ax)
1661 memcmp (&t->unverified_ax->DHRr,
1663 sizeof (msg->ratchet_key)))
1665 LOG (GNUNET_ERROR_TYPE_DEBUG,
1666 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1673 LOG (GNUNET_ERROR_TYPE_DEBUG,
1674 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1676 memset (t->unverified_ax,
1678 sizeof (struct CadetTunnelAxolotl));
1679 t->unverified_ax->DHRs = t->ax.DHRs;
1680 t->unverified_ax->kx_0 = t->ax.kx_0;
1684 LOG (GNUNET_ERROR_TYPE_DEBUG,
1685 "Creating fresh unverified KX for %s.\n",
1687 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1688 t->unverified_ax->DHRs = t->ax.DHRs;
1689 t->unverified_ax->kx_0 = t->ax.kx_0;
1691 /* Set as the 'current' RK/DHRr the one we are currently using,
1692 so that the duplicate-detection logic of
1693 #update_ax_by_kx can work. */
1694 t->unverified_ax->RK = t->ax.RK;
1695 t->unverified_ax->DHRr = t->ax.DHRr;
1696 t->unverified_attempts = 0;
1697 ax = t->unverified_ax;
1699 /* Update 'ax' by the new key material */
1700 ret = update_ax_by_kx (ax,
1701 GCP_get_id (t->destination),
1702 &msg->ephemeral_key,
1704 GNUNET_break (GNUNET_SYSERR != ret);
1705 if (GNUNET_OK != ret)
1706 return; /* duplicate KX, nothing to do */
1708 /* move ahead in our state machine */
1709 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1710 GCT_change_estate (t,
1711 CADET_TUNNEL_KEY_AX_RECV);
1712 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1713 GCT_change_estate (t,
1714 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1716 /* KX is still not done, try again our end. */
1717 if (CADET_TUNNEL_KEY_OK != t->estate)
1719 if (NULL != t->kx_task)
1720 GNUNET_SCHEDULER_cancel (t->kx_task);
1722 = GNUNET_SCHEDULER_add_now (&retry_kx,
1729 * Handle KX_AUTH message.
1731 * @param ct connection/tunnel combo that received encrypted message
1732 * @param msg the key exchange message
1735 GCT_handle_kx_auth (struct CadetTConnection *ct,
1736 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1738 struct CadetTunnel *t = ct->t;
1739 struct CadetTunnelAxolotl ax_tmp;
1740 struct GNUNET_HashCode kx_auth;
1743 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1744 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1746 /* Confusing, we got a KX_AUTH before we even send our own
1747 KX. This should not happen. We'll send our own KX ASAP anyway,
1748 so let's ignore this here. */
1749 GNUNET_break_op (0);
1752 LOG (GNUNET_ERROR_TYPE_DEBUG,
1753 "Handling KX_AUTH message for %s\n",
1756 /* We do everything in ax_tmp until we've checked the authentication
1757 so we don't clobber anything we care about by accident. */
1760 /* Update 'ax' by the new key material */
1761 ret = update_ax_by_kx (&ax_tmp,
1762 GCP_get_id (t->destination),
1763 &msg->kx.ephemeral_key,
1764 &msg->kx.ratchet_key);
1765 GNUNET_break (GNUNET_OK == ret);
1766 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1769 if (0 != memcmp (&kx_auth,
1773 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1774 we transmitted to the sender, refuse it! */
1775 GNUNET_break_op (0);
1778 /* Yep, we're good. */
1780 if (NULL != t->unverified_ax)
1782 /* We got some "stale" KX before, drop that. */
1783 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1784 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1785 cleanup_ax (t->unverified_ax);
1786 GNUNET_free (t->unverified_ax);
1787 t->unverified_ax = NULL;
1790 /* move ahead in our state machine */
1793 case CADET_TUNNEL_KEY_UNINITIALIZED:
1794 case CADET_TUNNEL_KEY_AX_RECV:
1795 /* Checked above, this is impossible. */
1798 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1799 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1800 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1801 GCT_change_estate (t,
1802 CADET_TUNNEL_KEY_OK);
1804 case CADET_TUNNEL_KEY_OK:
1805 /* Did not expect another KX_AUTH, but so what, still acceptable.
1806 Nothing to do here. */
1813 /* ************************************** end core crypto ***************************** */
1817 * Compute the next free channel tunnel number for this tunnel.
1819 * @param t the tunnel
1820 * @return unused number that can uniquely identify a channel in the tunnel
1822 static struct GNUNET_CADET_ChannelTunnelNumber
1823 get_next_free_ctn (struct CadetTunnel *t)
1825 #define HIGH_BIT 0x8000000
1826 struct GNUNET_CADET_ChannelTunnelNumber ret;
1831 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1832 GCP_get_id (GCT_get_destination (t)));
1838 GNUNET_assert (0); // loopback must never go here!
1839 ctn = ntohl (t->next_ctn.cn);
1841 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1844 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1846 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1847 ret.cn = ntohl (ctn);
1853 * Add a channel to a tunnel, and notify channel that we are ready
1854 * for transmission if we are already up. Otherwise that notification
1855 * will be done later in #notify_tunnel_up_cb().
1859 * @return unique number identifying @a ch within @a t
1861 struct GNUNET_CADET_ChannelTunnelNumber
1862 GCT_add_channel (struct CadetTunnel *t,
1863 struct CadetChannel *ch)
1865 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1867 ctn = get_next_free_ctn (t);
1868 GNUNET_assert (GNUNET_YES ==
1869 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1872 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1873 LOG (GNUNET_ERROR_TYPE_DEBUG,
1874 "Adding %s to %s\n",
1879 case CADET_TUNNEL_KEY_UNINITIALIZED:
1880 /* waiting for connection to start KX */
1882 case CADET_TUNNEL_KEY_AX_RECV:
1883 case CADET_TUNNEL_KEY_AX_SENT:
1884 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1885 /* we're currently waiting for KX to complete */
1887 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1888 /* waiting for OTHER peer to send us data,
1889 we might need to prompt more aggressively! */
1890 if (NULL == t->kx_task)
1892 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1896 case CADET_TUNNEL_KEY_OK:
1897 /* We are ready. Tell the new channel that we are up. */
1898 GCCH_tunnel_up (ch);
1906 * We lost a connection, remove it from our list and clean up
1907 * the connection object itself.
1909 * @param ct binding of connection to tunnel of the connection that was lost.
1912 GCT_connection_lost (struct CadetTConnection *ct)
1914 struct CadetTunnel *t = ct->t;
1916 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1924 * This tunnel is no longer used, destroy it.
1926 * @param cls the idle tunnel
1929 destroy_tunnel (void *cls)
1931 struct CadetTunnel *t = cls;
1932 struct CadetTConnection *ct;
1933 struct CadetTunnelQueueEntry *tq;
1935 t->destroy_task = NULL;
1936 LOG (GNUNET_ERROR_TYPE_DEBUG,
1937 "Destroying idle %s\n",
1939 GNUNET_assert (0 == GCT_count_channels (t));
1940 while (NULL != (ct = t->connection_head))
1942 struct CadetConnection *cc;
1944 GNUNET_assert (ct->t == t);
1946 GCT_connection_lost (ct);
1947 GCC_destroy_without_tunnel (cc);
1949 while (NULL != (tq = t->tq_head))
1951 if (NULL != tq->cont)
1952 tq->cont (tq->cont_cls);
1953 GCT_send_cancel (tq);
1955 GCP_drop_tunnel (t->destination,
1957 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1958 if (NULL != t->maintain_connections_task)
1960 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1961 t->maintain_connections_task = NULL;
1963 if (NULL != t->send_task)
1965 GNUNET_SCHEDULER_cancel (t->send_task);
1966 t->send_task = NULL;
1968 if (NULL != t->kx_task)
1970 GNUNET_SCHEDULER_cancel (t->kx_task);
1973 GNUNET_MST_destroy (t->mst);
1974 GNUNET_MQ_destroy (t->mq);
1975 if (NULL != t->unverified_ax)
1977 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1978 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1979 cleanup_ax (t->unverified_ax);
1980 GNUNET_free (t->unverified_ax);
1982 cleanup_ax (&t->ax);
1988 * Remove a channel from a tunnel.
1992 * @param ctn unique number identifying @a ch within @a t
1995 GCT_remove_channel (struct CadetTunnel *t,
1996 struct CadetChannel *ch,
1997 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1999 LOG (GNUNET_ERROR_TYPE_DEBUG,
2000 "Removing %s from %s\n",
2003 GNUNET_assert (GNUNET_YES ==
2004 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2008 GCT_count_channels (t))
2010 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2018 * Destroy remaining channels during shutdown.
2020 * @param cls the `struct CadetTunnel` of the channel
2021 * @param key key of the channel
2022 * @param value the `struct CadetChannel`
2023 * @return #GNUNET_OK (continue to iterate)
2026 destroy_remaining_channels (void *cls,
2030 struct CadetChannel *ch = value;
2032 GCCH_handle_remote_destroy (ch);
2038 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2040 * @param t tunnel to destroy
2043 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2045 GNUNET_assert (GNUNET_YES == shutting_down);
2046 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2047 &destroy_remaining_channels,
2050 GCT_count_channels (t));
2051 if (NULL != t->destroy_task)
2053 GNUNET_SCHEDULER_cancel (t->destroy_task);
2054 t->destroy_task = NULL;
2061 * Send normal payload from queue in @a t via connection @a ct.
2062 * Does nothing if our payload queue is empty.
2064 * @param t tunnel to send data from
2065 * @param ct connection to use for transmission (is ready)
2068 try_send_normal_payload (struct CadetTunnel *t,
2069 struct CadetTConnection *ct)
2071 struct CadetTunnelQueueEntry *tq;
2073 GNUNET_assert (GNUNET_YES == ct->is_ready);
2077 /* no messages pending right now */
2078 LOG (GNUNET_ERROR_TYPE_DEBUG,
2079 "Not sending payload of %s on ready %s (nothing pending)\n",
2084 /* ready to send message 'tq' on tunnel 'ct' */
2085 GNUNET_assert (t == tq->t);
2086 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2089 if (NULL != tq->cid)
2090 *tq->cid = *GCC_get_id (ct->cc);
2091 ct->is_ready = GNUNET_NO;
2092 LOG (GNUNET_ERROR_TYPE_DEBUG,
2093 "Sending payload of %s on %s\n",
2096 GCC_transmit (ct->cc,
2098 if (NULL != tq->cont)
2099 tq->cont (tq->cont_cls);
2105 * A connection is @a is_ready for transmission. Looks at our message
2106 * queue and if there is a message, sends it out via the connection.
2108 * @param cls the `struct CadetTConnection` that is @a is_ready
2109 * @param is_ready #GNUNET_YES if connection are now ready,
2110 * #GNUNET_NO if connection are no longer ready
2113 connection_ready_cb (void *cls,
2116 struct CadetTConnection *ct = cls;
2117 struct CadetTunnel *t = ct->t;
2119 if (GNUNET_NO == is_ready)
2121 LOG (GNUNET_ERROR_TYPE_DEBUG,
2122 "%s no longer ready for %s\n",
2125 ct->is_ready = GNUNET_NO;
2128 ct->is_ready = GNUNET_YES;
2129 LOG (GNUNET_ERROR_TYPE_DEBUG,
2130 "%s now ready for %s in state %s\n",
2133 estate2s (t->estate));
2136 case CADET_TUNNEL_KEY_UNINITIALIZED:
2137 /* Do not begin KX if WE have no channels waiting! */
2138 if (0 == GCT_count_channels (t))
2140 /* We are uninitialized, just transmit immediately,
2141 without undue delay. */
2142 if (NULL != t->kx_task)
2144 GNUNET_SCHEDULER_cancel (t->kx_task);
2150 case CADET_TUNNEL_KEY_AX_RECV:
2151 case CADET_TUNNEL_KEY_AX_SENT:
2152 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2153 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2154 /* we're currently waiting for KX to complete, schedule job */
2155 if (NULL == t->kx_task)
2157 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2161 case CADET_TUNNEL_KEY_OK:
2162 if (GNUNET_YES == t->kx_auth_requested)
2164 if (NULL != t->kx_task)
2166 GNUNET_SCHEDULER_cancel (t->kx_task);
2174 try_send_normal_payload (t,
2182 * Called when either we have a new connection, or a new message in the
2183 * queue, or some existing connection has transmission capacity. Looks
2184 * at our message queue and if there is a message, picks a connection
2187 * @param cls the `struct CadetTunnel` to process messages on
2190 trigger_transmissions (void *cls)
2192 struct CadetTunnel *t = cls;
2193 struct CadetTConnection *ct;
2195 t->send_task = NULL;
2196 if (NULL == t->tq_head)
2197 return; /* no messages pending right now */
2198 ct = get_ready_connection (t);
2200 return; /* no connections ready */
2201 try_send_normal_payload (t,
2207 * Consider using the path @a p for the tunnel @a t.
2208 * The tunnel destination is at offset @a off in path @a p.
2210 * @param cls our tunnel
2211 * @param path a path to our destination
2212 * @param off offset of the destination on path @a path
2213 * @return #GNUNET_YES (should keep iterating)
2216 consider_path_cb (void *cls,
2217 struct CadetPeerPath *path,
2220 struct CadetTunnel *t = cls;
2221 unsigned int min_length = UINT_MAX;
2222 GNUNET_CONTAINER_HeapCostType max_desire = 0;
2223 struct CadetTConnection *ct;
2225 /* Check if we care about the new path. */
2226 for (ct = t->connection_head;
2230 struct CadetPeerPath *ps;
2232 ps = GCC_get_path (ct->cc);
2235 LOG (GNUNET_ERROR_TYPE_DEBUG,
2236 "Ignoring duplicate path %s for %s.\n",
2239 return GNUNET_YES; /* duplicate */
2241 min_length = GNUNET_MIN (min_length,
2242 GCPP_get_length (ps));
2243 max_desire = GNUNET_MAX (max_desire,
2244 GCPP_get_desirability (ps));
2247 /* FIXME: not sure we should really just count
2248 'num_connections' here, as they may all have
2249 consistently failed to connect. */
2251 /* We iterate by increasing path length; if we have enough paths and
2252 this one is more than twice as long than what we are currently
2253 using, then ignore all of these super-long ones! */
2254 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2255 (min_length * 2 < off) )
2257 LOG (GNUNET_ERROR_TYPE_DEBUG,
2258 "Ignoring paths of length %u, they are way too long.\n",
2262 /* If we have enough paths and this one looks no better, ignore it. */
2263 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2264 (min_length < GCPP_get_length (path)) &&
2265 (max_desire > GCPP_get_desirability (path)) )
2267 LOG (GNUNET_ERROR_TYPE_DEBUG,
2268 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2269 GCPP_get_length (path),
2270 (unsigned long long) GCPP_get_desirability (path),
2271 GCP_2s (t->destination));
2275 /* Path is interesting (better by some metric, or we don't have
2276 enough paths yet). */
2277 ct = GNUNET_new (struct CadetTConnection);
2278 ct->created = GNUNET_TIME_absolute_get ();
2280 ct->cc = GCC_create (t->destination,
2283 &connection_ready_cb,
2285 /* FIXME: schedule job to kill connection (and path?) if it takes
2286 too long to get ready! (And track performance data on how long
2287 other connections took with the tunnel!)
2288 => Note: to be done within 'connection'-logic! */
2289 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2292 t->num_connections++;
2293 LOG (GNUNET_ERROR_TYPE_DEBUG,
2294 "Found interesting path %s for %s, created %s\n",
2303 * Function called to maintain the connections underlying our tunnel.
2304 * Tries to maintain (incl. tear down) connections for the tunnel, and
2305 * if there is a significant change, may trigger transmissions.
2307 * Basically, needs to check if there are connections that perform
2308 * badly, and if so eventually kill them and trigger a replacement.
2309 * The strategy is to open one more connection than
2310 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2311 * least-performing one, and then inquire for new ones.
2313 * @param cls the `struct CadetTunnel`
2316 maintain_connections_cb (void *cls)
2318 struct CadetTunnel *t = cls;
2320 t->maintain_connections_task = NULL;
2321 LOG (GNUNET_ERROR_TYPE_DEBUG,
2322 "Performing connection maintenance for %s.\n",
2325 (void) GCP_iterate_paths (t->destination,
2329 GNUNET_break (0); // FIXME: implement!
2334 * Consider using the path @a p for the tunnel @a t.
2335 * The tunnel destination is at offset @a off in path @a p.
2337 * @param cls our tunnel
2338 * @param path a path to our destination
2339 * @param off offset of the destination on path @a path
2342 GCT_consider_path (struct CadetTunnel *t,
2343 struct CadetPeerPath *p,
2346 (void) consider_path_cb (t,
2353 * We got a keepalive. Track in statistics.
2355 * @param cls the `struct CadetTunnel` for which we decrypted the message
2356 * @param msg the message we received on the tunnel
2359 handle_plaintext_keepalive (void *cls,
2360 const struct GNUNET_MessageHeader *msg)
2362 struct CadetTunnel *t = cls;
2364 LOG (GNUNET_ERROR_TYPE_DEBUG,
2365 "Received KEEPALIVE on %s\n",
2367 GNUNET_STATISTICS_update (stats,
2368 "# keepalives received",
2375 * Check that @a msg is well-formed.
2377 * @param cls the `struct CadetTunnel` for which we decrypted the message
2378 * @param msg the message we received on the tunnel
2379 * @return #GNUNET_OK (any variable-size payload goes)
2382 check_plaintext_data (void *cls,
2383 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2390 * We received payload data for a channel. Locate the channel
2391 * and process the data, or return an error if the channel is unknown.
2393 * @param cls the `struct CadetTunnel` for which we decrypted the message
2394 * @param msg the message we received on the tunnel
2397 handle_plaintext_data (void *cls,
2398 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2400 struct CadetTunnel *t = cls;
2401 struct CadetChannel *ch;
2403 ch = lookup_channel (t,
2407 /* We don't know about such a channel, might have been destroyed on our
2408 end in the meantime, or never existed. Send back a DESTROY. */
2409 LOG (GNUNET_ERROR_TYPE_DEBUG,
2410 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2411 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2412 ntohl (msg->ctn.cn));
2413 GCT_send_channel_destroy (t,
2417 GCCH_handle_channel_plaintext_data (ch,
2423 * We received an acknowledgement for data we sent on a channel.
2424 * Locate the channel and process it, or return an error if the
2425 * channel is unknown.
2427 * @param cls the `struct CadetTunnel` for which we decrypted the message
2428 * @param ack the message we received on the tunnel
2431 handle_plaintext_data_ack (void *cls,
2432 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2434 struct CadetTunnel *t = cls;
2435 struct CadetChannel *ch;
2437 ch = lookup_channel (t,
2441 /* We don't know about such a channel, might have been destroyed on our
2442 end in the meantime, or never existed. Send back a DESTROY. */
2443 LOG (GNUNET_ERROR_TYPE_DEBUG,
2444 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2445 ntohl (ack->ctn.cn));
2446 GCT_send_channel_destroy (t,
2450 GCCH_handle_channel_plaintext_data_ack (ch,
2456 * We have received a request to open a channel to a port from
2457 * another peer. Creates the incoming channel.
2459 * @param cls the `struct CadetTunnel` for which we decrypted the message
2460 * @param copen the message we received on the tunnel
2463 handle_plaintext_channel_open (void *cls,
2464 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2466 struct CadetTunnel *t = cls;
2467 struct CadetChannel *ch;
2469 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2470 ntohl (copen->ctn.cn));
2473 LOG (GNUNET_ERROR_TYPE_DEBUG,
2474 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2475 GNUNET_h2s (&copen->port),
2478 GCCH_handle_duplicate_open (ch);
2481 LOG (GNUNET_ERROR_TYPE_DEBUG,
2482 "Receicved channel OPEN on port %s from %s\n",
2483 GNUNET_h2s (&copen->port),
2485 ch = GCCH_channel_incoming_new (t,
2488 ntohl (copen->opt));
2489 GNUNET_assert (GNUNET_OK ==
2490 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2491 ntohl (copen->ctn.cn),
2493 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2498 * Send a DESTROY message via the tunnel.
2500 * @param t the tunnel to transmit over
2501 * @param ctn ID of the channel to destroy
2504 GCT_send_channel_destroy (struct CadetTunnel *t,
2505 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2507 struct GNUNET_CADET_ChannelManageMessage msg;
2509 LOG (GNUNET_ERROR_TYPE_DEBUG,
2510 "Sending DESTORY message for channel ID %u\n",
2512 msg.header.size = htons (sizeof (msg));
2513 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2514 msg.reserved = htonl (0);
2524 * We have received confirmation from the target peer that the
2525 * given channel could be established (the port is open).
2528 * @param cls the `struct CadetTunnel` for which we decrypted the message
2529 * @param cm the message we received on the tunnel
2532 handle_plaintext_channel_open_ack (void *cls,
2533 const struct GNUNET_CADET_ChannelManageMessage *cm)
2535 struct CadetTunnel *t = cls;
2536 struct CadetChannel *ch;
2538 ch = lookup_channel (t,
2542 /* We don't know about such a channel, might have been destroyed on our
2543 end in the meantime, or never existed. Send back a DESTROY. */
2544 LOG (GNUNET_ERROR_TYPE_DEBUG,
2545 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2546 ntohl (cm->ctn.cn));
2547 GCT_send_channel_destroy (t,
2551 LOG (GNUNET_ERROR_TYPE_DEBUG,
2552 "Received channel OPEN_ACK on channel %s from %s\n",
2555 GCCH_handle_channel_open_ack (ch);
2560 * We received a message saying that a channel should be destroyed.
2561 * Pass it on to the correct channel.
2563 * @param cls the `struct CadetTunnel` for which we decrypted the message
2564 * @param cm the message we received on the tunnel
2567 handle_plaintext_channel_destroy (void *cls,
2568 const struct GNUNET_CADET_ChannelManageMessage *cm)
2570 struct CadetTunnel *t = cls;
2571 struct CadetChannel *ch;
2573 ch = lookup_channel (t,
2577 /* We don't know about such a channel, might have been destroyed on our
2578 end in the meantime, or never existed. */
2579 LOG (GNUNET_ERROR_TYPE_DEBUG,
2580 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2581 ntohl (cm->ctn.cn));
2584 LOG (GNUNET_ERROR_TYPE_DEBUG,
2585 "Receicved channel DESTROY on %s from %s\n",
2588 GCCH_handle_remote_destroy (ch);
2593 * Handles a message we decrypted, by injecting it into
2594 * our message queue (which will do the dispatching).
2596 * @param cls the `struct CadetTunnel` that got the message
2597 * @param msg the message
2598 * @return #GNUNET_OK (continue to process)
2601 handle_decrypted (void *cls,
2602 const struct GNUNET_MessageHeader *msg)
2604 struct CadetTunnel *t = cls;
2606 GNUNET_MQ_inject_message (t->mq,
2613 * Function called if we had an error processing
2614 * an incoming decrypted message.
2616 * @param cls the `struct CadetTunnel`
2617 * @param error error code
2620 decrypted_error_cb (void *cls,
2621 enum GNUNET_MQ_Error error)
2623 GNUNET_break_op (0);
2628 * Create a tunnel to @a destionation. Must only be called
2629 * from within #GCP_get_tunnel().
2631 * @param destination where to create the tunnel to
2632 * @return new tunnel to @a destination
2634 struct CadetTunnel *
2635 GCT_create_tunnel (struct CadetPeer *destination)
2637 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2638 struct GNUNET_MQ_MessageHandler handlers[] = {
2639 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2640 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2641 struct GNUNET_MessageHeader,
2643 GNUNET_MQ_hd_var_size (plaintext_data,
2644 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2645 struct GNUNET_CADET_ChannelAppDataMessage,
2647 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2648 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2649 struct GNUNET_CADET_ChannelDataAckMessage,
2651 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2652 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2653 struct GNUNET_CADET_ChannelOpenMessage,
2655 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2656 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2657 struct GNUNET_CADET_ChannelManageMessage,
2659 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2660 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2661 struct GNUNET_CADET_ChannelManageMessage,
2663 GNUNET_MQ_handler_end ()
2666 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2667 new_ephemeral (&t->ax);
2668 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2669 t->destination = destination;
2670 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2671 t->maintain_connections_task
2672 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2674 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2679 &decrypted_error_cb,
2681 t->mst = GNUNET_MST_create (&handle_decrypted,
2688 * Add a @a connection to the @a tunnel.
2691 * @param cid connection identifer to use for the connection
2692 * @param path path to use for the connection
2693 * @return #GNUNET_OK on success,
2694 * #GNUNET_SYSERR on failure (duplicate connection)
2697 GCT_add_inbound_connection (struct CadetTunnel *t,
2698 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2699 struct CadetPeerPath *path)
2701 struct CadetTConnection *ct;
2703 ct = GNUNET_new (struct CadetTConnection);
2704 ct->created = GNUNET_TIME_absolute_get ();
2706 ct->cc = GCC_create_inbound (t->destination,
2710 &connection_ready_cb,
2714 LOG (GNUNET_ERROR_TYPE_DEBUG,
2715 "%s refused inbound %s (duplicate)\n",
2719 return GNUNET_SYSERR;
2721 /* FIXME: schedule job to kill connection (and path?) if it takes
2722 too long to get ready! (And track performance data on how long
2723 other connections took with the tunnel!)
2724 => Note: to be done within 'connection'-logic! */
2725 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2728 t->num_connections++;
2729 LOG (GNUNET_ERROR_TYPE_DEBUG,
2738 * Handle encrypted message.
2740 * @param ct connection/tunnel combo that received encrypted message
2741 * @param msg the encrypted message to decrypt
2744 GCT_handle_encrypted (struct CadetTConnection *ct,
2745 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2747 struct CadetTunnel *t = ct->t;
2748 uint16_t size = ntohs (msg->header.size);
2749 char cbuf [size] GNUNET_ALIGN;
2750 ssize_t decrypted_size;
2752 LOG (GNUNET_ERROR_TYPE_DEBUG,
2753 "%s received %u bytes of encrypted data in state %d\n",
2755 (unsigned int) size,
2760 case CADET_TUNNEL_KEY_UNINITIALIZED:
2761 case CADET_TUNNEL_KEY_AX_RECV:
2762 /* We did not even SEND our KX, how can the other peer
2763 send us encrypted data? */
2764 GNUNET_break_op (0);
2766 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2767 /* We send KX, and other peer send KX to us at the same time.
2768 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
2769 GNUNET_STATISTICS_update (stats,
2770 "# received encrypted without KX_AUTH",
2773 if (NULL != t->kx_task)
2775 GNUNET_SCHEDULER_cancel (t->kx_task);
2782 case CADET_TUNNEL_KEY_AX_SENT:
2783 /* We did not get the KX of the other peer, but that
2784 might have been lost. Send our KX again immediately. */
2785 GNUNET_STATISTICS_update (stats,
2786 "# received encrypted without KX",
2789 if (NULL != t->kx_task)
2791 GNUNET_SCHEDULER_cancel (t->kx_task);
2797 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2798 /* Great, first payload, we might graduate to OK! */
2799 case CADET_TUNNEL_KEY_OK:
2800 /* We are up and running, all good. */
2804 GNUNET_STATISTICS_update (stats,
2805 "# received encrypted",
2808 decrypted_size = -1;
2809 if (CADET_TUNNEL_KEY_OK == t->estate)
2811 /* We have well-established key material available,
2812 try that. (This is the common case.) */
2813 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2819 if ( (-1 == decrypted_size) &&
2820 (NULL != t->unverified_ax) )
2822 /* We have un-authenticated KX material available. We should try
2823 this as a back-up option, in case the sender crashed and
2825 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2829 if (-1 != decrypted_size)
2831 /* It worked! Treat this as authentication of the AX data! */
2832 t->ax.DHRs = NULL; /* aliased with ax.DHRs */
2833 t->ax.kx_0 = NULL; /* aliased with ax.DHRs */
2834 cleanup_ax (&t->ax);
2835 t->ax = *t->unverified_ax;
2836 GNUNET_free (t->unverified_ax);
2837 t->unverified_ax = NULL;
2839 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
2841 /* First time it worked, move tunnel into production! */
2842 GCT_change_estate (t,
2843 CADET_TUNNEL_KEY_OK);
2844 if (NULL != t->send_task)
2845 GNUNET_SCHEDULER_cancel (t->send_task);
2846 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2850 if (NULL != t->unverified_ax)
2852 /* We had unverified KX material that was useless; so increment
2853 counter and eventually move to ignore it. Note that we even do
2854 this increment if we successfully decrypted with the old KX
2855 material and thus didn't even both with the new one. This is
2856 the ideal case, as a malicious injection of bogus KX data
2857 basically only causes us to increment a counter a few times. */
2858 t->unverified_attempts++;
2859 LOG (GNUNET_ERROR_TYPE_DEBUG,
2860 "Failed to decrypt message with unverified KX data %u times\n",
2861 t->unverified_attempts);
2862 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2864 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
2865 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
2866 cleanup_ax (t->unverified_ax);
2867 GNUNET_free (t->unverified_ax);
2868 t->unverified_ax = NULL;
2872 if (-1 == decrypted_size)
2874 /* Decryption failed for good, complain. */
2875 GNUNET_break_op (0);
2876 LOG (GNUNET_ERROR_TYPE_WARNING,
2877 "%s failed to decrypt and validate encrypted data\n",
2879 GNUNET_STATISTICS_update (stats,
2880 "# unable to decrypt",
2886 /* The MST will ultimately call #handle_decrypted() on each message. */
2887 GNUNET_break_op (GNUNET_OK ==
2888 GNUNET_MST_from_buffer (t->mst,
2897 * Sends an already built message on a tunnel, encrypting it and
2898 * choosing the best connection if not provided.
2900 * @param message Message to send. Function modifies it.
2901 * @param t Tunnel on which this message is transmitted.
2902 * @param cont Continuation to call once message is really sent.
2903 * @param cont_cls Closure for @c cont.
2904 * @return Handle to cancel message
2906 struct CadetTunnelQueueEntry *
2907 GCT_send (struct CadetTunnel *t,
2908 const struct GNUNET_MessageHeader *message,
2909 GNUNET_SCHEDULER_TaskCallback cont,
2912 struct CadetTunnelQueueEntry *tq;
2913 uint16_t payload_size;
2914 struct GNUNET_MQ_Envelope *env;
2915 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2917 if (CADET_TUNNEL_KEY_OK != t->estate)
2922 payload_size = ntohs (message->size);
2923 LOG (GNUNET_ERROR_TYPE_DEBUG,
2924 "Encrypting %u bytes for %s\n",
2925 (unsigned int) payload_size,
2927 env = GNUNET_MQ_msg_extra (ax_msg,
2929 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2930 t_ax_encrypt (&t->ax,
2934 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2935 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2936 /* FIXME: we should do this once, not once per message;
2937 this is a point multiplication, and DHRs does not
2938 change all the time. */
2939 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2940 &ax_msg->ax_header.DHRs);
2941 t_h_encrypt (&t->ax,
2943 t_hmac (&ax_msg->ax_header,
2944 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2949 tq = GNUNET_malloc (sizeof (*tq));
2952 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2954 tq->cont_cls = cont_cls;
2955 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2958 if (NULL != t->send_task)
2959 GNUNET_SCHEDULER_cancel (t->send_task);
2961 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2968 * Cancel a previously sent message while it's in the queue.
2970 * ONLY can be called before the continuation given to the send
2971 * function is called. Once the continuation is called, the message is
2972 * no longer in the queue!
2974 * @param tq Handle to the queue entry to cancel.
2977 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2979 struct CadetTunnel *t = tq->t;
2981 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2984 GNUNET_MQ_discard (tq->env);
2990 * Iterate over all connections of a tunnel.
2992 * @param t Tunnel whose connections to iterate.
2993 * @param iter Iterator.
2994 * @param iter_cls Closure for @c iter.
2997 GCT_iterate_connections (struct CadetTunnel *t,
2998 GCT_ConnectionIterator iter,
3001 for (struct CadetTConnection *ct = t->connection_head;
3010 * Closure for #iterate_channels_cb.
3017 GCT_ChannelIterator iter;
3020 * Closure for @e iter.
3027 * Helper function for #GCT_iterate_channels.
3029 * @param cls the `struct ChanIterCls`
3031 * @param value a `struct CadetChannel`
3032 * @return #GNUNET_OK
3035 iterate_channels_cb (void *cls,
3039 struct ChanIterCls *ctx = cls;
3040 struct CadetChannel *ch = value;
3042 ctx->iter (ctx->iter_cls,
3049 * Iterate over all channels of a tunnel.
3051 * @param t Tunnel whose channels to iterate.
3052 * @param iter Iterator.
3053 * @param iter_cls Closure for @c iter.
3056 GCT_iterate_channels (struct CadetTunnel *t,
3057 GCT_ChannelIterator iter,
3060 struct ChanIterCls ctx;
3063 ctx.iter_cls = iter_cls;
3064 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3065 &iterate_channels_cb,
3072 * Call #GCCH_debug() on a channel.
3074 * @param cls points to the log level to use
3076 * @param value the `struct CadetChannel` to dump
3077 * @return #GNUNET_OK (continue iteration)
3080 debug_channel (void *cls,
3084 const enum GNUNET_ErrorType *level = cls;
3085 struct CadetChannel *ch = value;
3087 GCCH_debug (ch, *level);
3092 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3096 * Log all possible info about the tunnel state.
3098 * @param t Tunnel to debug.
3099 * @param level Debug level to use.
3102 GCT_debug (const struct CadetTunnel *t,
3103 enum GNUNET_ErrorType level)
3105 struct CadetTConnection *iter_c;
3108 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3110 __FILE__, __FUNCTION__, __LINE__);
3115 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3117 estate2s (t->estate),
3119 t->num_connections);
3122 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3126 "TTT connections:\n");
3127 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
3128 GCC_debug (iter_c->cc,
3132 "TTT TUNNEL END\n");
3136 /* end of gnunet-service-cadet-new_tunnels.c */