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 * - proper connection evaluation during connection management:
28 * + consider quality (or quality spread?) of current connection set
29 * when deciding how often to do maintenance
30 * + interact with PEER to drive DHT GET/PUT operations based
31 * on how much we like our connections
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).
178 struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
181 * ECDH Ratchet key (our private key in the current DH).
183 struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
186 * ECDH Ratchet key (other peer's public key in the current DH).
188 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
191 * Time when the current ratchet expires and a new one is triggered
192 * (if @e ratchet_allowed is #GNUNET_YES).
194 struct GNUNET_TIME_Absolute ratchet_expiration;
197 * Number of elements in @a skipped_head <-> @a skipped_tail.
199 unsigned int skipped;
202 * Message number (reset to 0 with each new ratchet, next message to send).
207 * Message number (reset to 0 with each new ratchet, next message to recv).
212 * Previous message numbers (# of msgs sent under prev ratchet)
217 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
222 * True (#GNUNET_YES) if we have received a message from the
223 * other peer that uses the keys from our last ratchet step.
224 * This implies that we are again allowed to advance the ratchet,
225 * otherwise we have to wait until the other peer sees our current
226 * ephemeral key and advances first.
228 * #GNUNET_NO if we have advanced the ratched but lack any evidence
229 * that the other peer has noticed this.
234 * Number of messages recieved since our last ratchet advance.
236 * If this counter = 0, we cannot send a new ratchet key in the next
239 * If this counter > 0, we could (but don't have to) send a new key.
241 * Once the @e ratchet_counter is larger than
242 * #ratchet_messages (or @e ratchet_expiration time has past), and
243 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
245 unsigned int ratchet_counter;
251 * Struct used to save messages in a non-ready tunnel to send once connected.
253 struct CadetTunnelQueueEntry
256 * We are entries in a DLL
258 struct CadetTunnelQueueEntry *next;
261 * We are entries in a DLL
263 struct CadetTunnelQueueEntry *prev;
266 * Tunnel these messages belong in.
268 struct CadetTunnel *t;
271 * Continuation to call once sent (on the channel layer).
273 GCT_SendContinuation cont;
276 * Closure for @c cont.
281 * Envelope of message to send follows.
283 struct GNUNET_MQ_Envelope *env;
286 * Where to put the connection identifier into the payload
287 * of the message in @e env once we have it?
289 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
294 * Struct containing all information regarding a tunnel to a peer.
299 * Destination of the tunnel.
301 struct CadetPeer *destination;
304 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
305 * ephemeral key changes.
307 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
310 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
312 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
315 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
317 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
322 struct CadetTunnelAxolotl ax;
325 * Unverified Axolotl info, used only if we got a fresh KX (not a
326 * KX_AUTH) while our end of the tunnel was still up. In this case,
327 * we keep the fresh KX around but do not put it into action until
328 * we got encrypted payload that assures us of the authenticity of
331 struct CadetTunnelAxolotl *unverified_ax;
334 * Task scheduled if there are no more channels using the tunnel.
336 struct GNUNET_SCHEDULER_Task *destroy_task;
339 * Task to trim connections if too many are present.
341 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
344 * Task to send messages from queue (if possible).
346 struct GNUNET_SCHEDULER_Task *send_task;
349 * Task to trigger KX.
351 struct GNUNET_SCHEDULER_Task *kx_task;
354 * Tokenizer for decrypted messages.
356 struct GNUNET_MessageStreamTokenizer *mst;
359 * Dispatcher for decrypted messages only (do NOT use for sending!).
361 struct GNUNET_MQ_Handle *mq;
364 * DLL of ready connections that are actively used to reach the destination peer.
366 struct CadetTConnection *connection_ready_head;
369 * DLL of ready connections that are actively used to reach the destination peer.
371 struct CadetTConnection *connection_ready_tail;
374 * DLL of connections that we maintain that might be used to reach the destination peer.
376 struct CadetTConnection *connection_busy_head;
379 * DLL of connections that we maintain that might be used to reach the destination peer.
381 struct CadetTConnection *connection_busy_tail;
384 * Channels inside this tunnel. Maps
385 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
387 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
390 * Channel ID for the next created channel in this tunnel.
392 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
395 * Queued messages, to transmit once tunnel gets connected.
397 struct CadetTunnelQueueEntry *tq_head;
400 * Queued messages, to transmit once tunnel gets connected.
402 struct CadetTunnelQueueEntry *tq_tail;
405 * Identification of the connection from which we are currently processing
406 * a message. Only valid (non-NULL) during #handle_decrypted() and the
407 * handle-*()-functions called from our @e mq during that function.
409 struct CadetTConnection *current_ct;
412 * How long do we wait until we retry the KX?
414 struct GNUNET_TIME_Relative kx_retry_delay;
417 * When do we try the next KX?
419 struct GNUNET_TIME_Absolute next_kx_attempt;
422 * Number of connections in the @e connection_ready_head DLL.
424 unsigned int num_ready_connections;
427 * Number of connections in the @e connection_busy_head DLL.
429 unsigned int num_busy_connections;
432 * How often have we tried and failed to decrypt a message using
433 * the unverified KX material from @e unverified_ax? Used to
434 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
436 unsigned int unverified_attempts;
439 * Number of entries in the @e tq_head DLL.
444 * State of the tunnel encryption.
446 enum CadetTunnelEState estate;
449 * Force triggering KX_AUTH independent of @e estate.
451 int kx_auth_requested;
457 * Connection @a ct is now unready, clear it's ready flag
458 * and move it from the ready DLL to the busy DLL.
460 * @param ct connection to move to unready status
463 mark_connection_unready (struct CadetTConnection *ct)
465 struct CadetTunnel *t = ct->t;
467 GNUNET_assert (GNUNET_YES == ct->is_ready);
468 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
469 t->connection_ready_tail,
471 GNUNET_assert (0 < t->num_ready_connections);
472 t->num_ready_connections--;
473 ct->is_ready = GNUNET_NO;
474 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
475 t->connection_busy_tail,
477 t->num_busy_connections++;
482 * Get the static string for the peer this tunnel is directed.
486 * @return Static string the destination peer's ID.
489 GCT_2s (const struct CadetTunnel *t)
494 return "Tunnel(NULL)";
495 GNUNET_snprintf (buf,
498 GNUNET_i2s (GCP_get_id (t->destination)));
504 * Get string description for tunnel encryption state.
506 * @param es Tunnel state.
508 * @return String representation.
511 estate2s (enum CadetTunnelEState es)
517 case CADET_TUNNEL_KEY_UNINITIALIZED:
518 return "CADET_TUNNEL_KEY_UNINITIALIZED";
519 case CADET_TUNNEL_KEY_AX_RECV:
520 return "CADET_TUNNEL_KEY_AX_RECV";
521 case CADET_TUNNEL_KEY_AX_SENT:
522 return "CADET_TUNNEL_KEY_AX_SENT";
523 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
524 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
525 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
526 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
527 case CADET_TUNNEL_KEY_OK:
528 return "CADET_TUNNEL_KEY_OK";
530 GNUNET_snprintf (buf,
532 "%u (UNKNOWN STATE)",
540 * Return the peer to which this tunnel goes.
543 * @return the destination of the tunnel
546 GCT_get_destination (struct CadetTunnel *t)
548 return t->destination;
553 * Count channels of a tunnel.
555 * @param t Tunnel on which to count.
557 * @return Number of channels.
560 GCT_count_channels (struct CadetTunnel *t)
562 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
567 * Lookup a channel by its @a ctn.
569 * @param t tunnel to look in
570 * @param ctn number of channel to find
571 * @return NULL if channel does not exist
573 struct CadetChannel *
574 lookup_channel (struct CadetTunnel *t,
575 struct GNUNET_CADET_ChannelTunnelNumber ctn)
577 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
583 * Count all created connections of a tunnel. Not necessarily ready connections!
585 * @param t Tunnel on which to count.
587 * @return Number of connections created, either being established or ready.
590 GCT_count_any_connections (const struct CadetTunnel *t)
592 return t->num_ready_connections + t->num_busy_connections;
597 * Find first connection that is ready in the list of
598 * our connections. Picks ready connections round-robin.
600 * @param t tunnel to search
601 * @return NULL if we have no connection that is ready
603 static struct CadetTConnection *
604 get_ready_connection (struct CadetTunnel *t)
606 GNUNET_assert (GNUNET_YES == t->connection_ready_head->is_ready);
607 return t->connection_ready_head;
612 * Get the encryption state of a tunnel.
616 * @return Tunnel's encryption state.
618 enum CadetTunnelEState
619 GCT_get_estate (struct CadetTunnel *t)
626 * Called when either we have a new connection, or a new message in the
627 * queue, or some existing connection has transmission capacity. Looks
628 * at our message queue and if there is a message, picks a connection
631 * @param cls the `struct CadetTunnel` to process messages on
634 trigger_transmissions (void *cls);
637 /* ************************************** start core crypto ***************************** */
641 * Create a new Axolotl ephemeral (ratchet) key.
643 * @param ax key material to update
646 new_ephemeral (struct CadetTunnelAxolotl *ax)
648 LOG (GNUNET_ERROR_TYPE_DEBUG,
649 "Creating new ephemeral ratchet key (DHRs)\n");
650 GNUNET_assert (GNUNET_OK ==
651 GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
658 * @param plaintext Content to HMAC.
659 * @param size Size of @c plaintext.
660 * @param iv Initialization vector for the message.
661 * @param key Key to use.
662 * @param hmac[out] Destination to store the HMAC.
665 t_hmac (const void *plaintext,
668 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
669 struct GNUNET_ShortHashCode *hmac)
671 static const char ctx[] = "cadet authentication key";
672 struct GNUNET_CRYPTO_AuthKey auth_key;
673 struct GNUNET_HashCode hash;
675 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
681 /* Two step: GNUNET_ShortHash is only 256 bits,
682 GNUNET_HashCode is 512, so we truncate. */
683 GNUNET_CRYPTO_hmac (&auth_key,
696 * @param key Key to use.
697 * @param[out] hash Resulting HMAC.
698 * @param source Source key material (data to HMAC).
699 * @param len Length of @a source.
702 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
703 struct GNUNET_HashCode *hash,
707 static const char ctx[] = "axolotl HMAC-HASH";
708 struct GNUNET_CRYPTO_AuthKey auth_key;
710 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
714 GNUNET_CRYPTO_hmac (&auth_key,
722 * Derive a symmetric encryption key from an HMAC-HASH.
724 * @param key Key to use for the HMAC.
725 * @param[out] out Key to generate.
726 * @param source Source key material (data to HMAC).
727 * @param len Length of @a source.
730 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
731 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
735 static const char ctx[] = "axolotl derive key";
736 struct GNUNET_HashCode h;
742 GNUNET_CRYPTO_kdf (out, sizeof (*out),
750 * Encrypt data with the axolotl tunnel key.
752 * @param ax key material to use.
753 * @param dst Destination with @a size bytes for the encrypted data.
754 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
755 * @param size Size of the buffers at @a src and @a dst
758 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
763 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
764 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
767 ax->ratchet_counter++;
768 if ( (GNUNET_YES == ax->ratchet_allowed) &&
769 ( (ratchet_messages <= ax->ratchet_counter) ||
770 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
772 ax->ratchet_flag = GNUNET_YES;
774 if (GNUNET_YES == ax->ratchet_flag)
776 /* Advance ratchet */
777 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
778 struct GNUNET_HashCode dh;
779 struct GNUNET_HashCode hmac;
780 static const char ctx[] = "axolotl ratchet";
785 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
786 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
789 t_ax_hmac_hash (&ax->RK,
793 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
795 &hmac, sizeof (hmac),
803 ax->ratchet_flag = GNUNET_NO;
804 ax->ratchet_allowed = GNUNET_NO;
805 ax->ratchet_counter = 0;
806 ax->ratchet_expiration
807 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
811 t_hmac_derive_key (&ax->CKs,
815 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
820 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
825 GNUNET_assert (size == out_size);
826 t_hmac_derive_key (&ax->CKs,
834 * Decrypt data with the axolotl tunnel key.
836 * @param ax key material to use.
837 * @param dst Destination for the decrypted data, must contain @a size bytes.
838 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
839 * @param size Size of the @a src and @a dst buffers
842 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
847 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
848 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
851 t_hmac_derive_key (&ax->CKr,
855 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
859 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
860 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
865 GNUNET_assert (out_size == size);
866 t_hmac_derive_key (&ax->CKr,
874 * Encrypt header with the axolotl header key.
876 * @param ax key material to use.
877 * @param[in|out] msg Message whose header to encrypt.
880 t_h_encrypt (struct CadetTunnelAxolotl *ax,
881 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
883 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
886 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
890 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
891 sizeof (struct GNUNET_CADET_AxHeader),
895 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
900 * Decrypt header with the current axolotl header key.
902 * @param ax key material to use.
903 * @param src Message whose header to decrypt.
904 * @param dst Where to decrypt header to.
907 t_h_decrypt (struct CadetTunnelAxolotl *ax,
908 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
909 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
911 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
914 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
918 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
919 sizeof (struct GNUNET_CADET_AxHeader),
923 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
928 * Delete a key from the list of skipped keys.
930 * @param ax key material to delete @a key from.
931 * @param key Key to delete.
934 delete_skipped_key (struct CadetTunnelAxolotl *ax,
935 struct CadetTunnelSkippedKey *key)
937 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
946 * Decrypt and verify data with the appropriate tunnel key and verify that the
947 * data has not been altered since it was sent by the remote peer.
949 * @param ax key material to use.
950 * @param dst Destination for the plaintext.
951 * @param src Source of the message. Can overlap with @c dst.
952 * @param size Size of the message.
953 * @return Size of the decrypted data, -1 if an error was encountered.
956 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
958 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
961 struct CadetTunnelSkippedKey *key;
962 struct GNUNET_ShortHashCode *hmac;
963 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
964 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
965 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
971 LOG (GNUNET_ERROR_TYPE_DEBUG,
972 "Trying skipped keys\n");
973 hmac = &plaintext_header.hmac;
974 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
976 /* Find a correct Header Key */
978 for (key = ax->skipped_head; NULL != key; key = key->next)
980 t_hmac (&src->ax_header,
981 sizeof (struct GNUNET_CADET_AxHeader) + esize,
985 if (0 == memcmp (hmac,
996 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
997 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
998 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
999 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1001 /* Decrypt header */
1002 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1006 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1007 sizeof (struct GNUNET_CADET_AxHeader),
1010 &plaintext_header.ax_header.Ns);
1011 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1013 /* Find the correct message key */
1014 N = ntohl (plaintext_header.ax_header.Ns);
1015 while ( (NULL != key) &&
1018 if ( (NULL == key) ||
1019 (0 != memcmp (&key->HK,
1021 sizeof (*valid_HK))) )
1024 /* Decrypt payload */
1025 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1030 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1035 delete_skipped_key (ax,
1042 * Delete a key from the list of skipped keys.
1044 * @param ax key material to delete from.
1045 * @param HKr Header Key to use.
1048 store_skipped_key (struct CadetTunnelAxolotl *ax,
1049 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1051 struct CadetTunnelSkippedKey *key;
1053 key = GNUNET_new (struct CadetTunnelSkippedKey);
1054 key->timestamp = GNUNET_TIME_absolute_get ();
1057 t_hmac_derive_key (&ax->CKr,
1061 t_hmac_derive_key (&ax->CKr,
1065 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1074 * Stage skipped AX keys and calculate the message key.
1075 * Stores each HK and MK for skipped messages.
1077 * @param ax key material to use
1078 * @param HKr Header key.
1079 * @param Np Received meesage number.
1080 * @return #GNUNET_OK if keys were stored.
1081 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1084 store_ax_keys (struct CadetTunnelAxolotl *ax,
1085 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1091 LOG (GNUNET_ERROR_TYPE_DEBUG,
1092 "Storing skipped keys [%u, %u)\n",
1095 if (MAX_KEY_GAP < gap)
1097 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1098 /* TODO: start new key exchange on return */
1099 GNUNET_break_op (0);
1100 LOG (GNUNET_ERROR_TYPE_WARNING,
1101 "Got message %u, expected %u+\n",
1104 return GNUNET_SYSERR;
1108 /* Delayed message: don't store keys, flag to try old keys. */
1109 return GNUNET_SYSERR;
1113 store_skipped_key (ax,
1116 while (ax->skipped > MAX_SKIPPED_KEYS)
1117 delete_skipped_key (ax,
1124 * Decrypt and verify data with the appropriate tunnel key and verify that the
1125 * data has not been altered since it was sent by the remote peer.
1127 * @param ax key material to use
1128 * @param dst Destination for the plaintext.
1129 * @param src Source of the message. Can overlap with @c dst.
1130 * @param size Size of the message.
1131 * @return Size of the decrypted data, -1 if an error was encountered.
1134 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1136 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1139 struct GNUNET_ShortHashCode msg_hmac;
1140 struct GNUNET_HashCode hmac;
1141 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1144 size_t esize; /* Size of encryped payload */
1146 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1148 /* Try current HK */
1149 t_hmac (&src->ax_header,
1150 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1153 if (0 != memcmp (&msg_hmac,
1157 static const char ctx[] = "axolotl ratchet";
1158 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1159 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1160 struct GNUNET_HashCode dh;
1161 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1164 t_hmac (&src->ax_header,
1165 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1169 if (0 != memcmp (&msg_hmac,
1173 /* Try the skipped keys, if that fails, we're out of luck. */
1174 return try_old_ax_keys (ax,
1184 Np = ntohl (plaintext_header.ax_header.Ns);
1185 PNp = ntohl (plaintext_header.ax_header.PNs);
1186 DHRp = &plaintext_header.ax_header.DHRs;
1191 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1192 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1195 t_ax_hmac_hash (&ax->RK,
1198 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1200 &hmac, sizeof (hmac),
1203 /* Commit "purported" keys */
1209 ax->ratchet_allowed = GNUNET_YES;
1216 Np = ntohl (plaintext_header.ax_header.Ns);
1217 PNp = ntohl (plaintext_header.ax_header.PNs);
1219 if ( (Np != ax->Nr) &&
1220 (GNUNET_OK != store_ax_keys (ax,
1224 /* Try the skipped keys, if that fails, we're out of luck. */
1225 return try_old_ax_keys (ax,
1241 * Our tunnel became ready for the first time, notify channels
1242 * that have been waiting.
1244 * @param cls our tunnel, not used
1245 * @param key unique ID of the channel, not used
1246 * @param value the `struct CadetChannel` to notify
1247 * @return #GNUNET_OK (continue to iterate)
1250 notify_tunnel_up_cb (void *cls,
1254 struct CadetChannel *ch = value;
1256 GCCH_tunnel_up (ch);
1262 * Change the tunnel encryption state.
1263 * If the encryption state changes to OK, stop the rekey task.
1265 * @param t Tunnel whose encryption state to change, or NULL.
1266 * @param state New encryption state.
1269 GCT_change_estate (struct CadetTunnel *t,
1270 enum CadetTunnelEState state)
1272 enum CadetTunnelEState old = t->estate;
1275 LOG (GNUNET_ERROR_TYPE_DEBUG,
1276 "%s estate changed from %s to %s\n",
1281 if ( (CADET_TUNNEL_KEY_OK != old) &&
1282 (CADET_TUNNEL_KEY_OK == t->estate) )
1284 if (NULL != t->kx_task)
1286 GNUNET_SCHEDULER_cancel (t->kx_task);
1289 /* notify all channels that have been waiting */
1290 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1291 ¬ify_tunnel_up_cb,
1293 if (NULL != t->send_task)
1294 GNUNET_SCHEDULER_cancel (t->send_task);
1295 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1302 * Send a KX message.
1304 * @param t tunnel on which to send the KX_AUTH
1305 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1306 * we are to find one that is ready.
1307 * @param ax axolotl key context to use
1310 send_kx (struct CadetTunnel *t,
1311 struct CadetTConnection *ct,
1312 struct CadetTunnelAxolotl *ax)
1314 struct CadetConnection *cc;
1315 struct GNUNET_MQ_Envelope *env;
1316 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1317 enum GNUNET_CADET_KX_Flags flags;
1320 ct = get_ready_connection (t);
1323 LOG (GNUNET_ERROR_TYPE_DEBUG,
1324 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1326 estate2s (t->estate));
1327 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1331 LOG (GNUNET_ERROR_TYPE_DEBUG,
1332 "Sending KX on %s via %s in state %s\n",
1335 estate2s (t->estate));
1336 env = GNUNET_MQ_msg (msg,
1337 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1338 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1339 msg->flags = htonl (flags);
1340 msg->cid = *GCC_get_id (cc);
1341 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1342 &msg->ephemeral_key);
1343 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1345 mark_connection_unready (ct);
1346 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1347 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1348 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1349 GCT_change_estate (t,
1350 CADET_TUNNEL_KEY_AX_SENT);
1351 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1352 GCT_change_estate (t,
1353 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1360 * Send a KX_AUTH message.
1362 * @param t tunnel on which to send the KX_AUTH
1363 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1364 * we are to find one that is ready.
1365 * @param ax axolotl key context to use
1366 * @param force_reply Force the other peer to reply with a KX_AUTH message
1367 * (set if we would like to transmit right now, but cannot)
1370 send_kx_auth (struct CadetTunnel *t,
1371 struct CadetTConnection *ct,
1372 struct CadetTunnelAxolotl *ax,
1375 struct CadetConnection *cc;
1376 struct GNUNET_MQ_Envelope *env;
1377 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1378 enum GNUNET_CADET_KX_Flags flags;
1380 if ( (NULL == ct) ||
1381 (GNUNET_NO == ct->is_ready) )
1382 ct = get_ready_connection (t);
1385 LOG (GNUNET_ERROR_TYPE_DEBUG,
1386 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1388 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1389 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1392 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1394 LOG (GNUNET_ERROR_TYPE_DEBUG,
1395 "Sending KX_AUTH on %s using %s\n",
1399 env = GNUNET_MQ_msg (msg,
1400 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1401 flags = GNUNET_CADET_KX_FLAG_NONE;
1402 if (GNUNET_YES == force_reply)
1403 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1404 msg->kx.flags = htonl (flags);
1405 msg->kx.cid = *GCC_get_id (cc);
1406 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1407 &msg->kx.ephemeral_key);
1408 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1409 &msg->kx.ratchet_key);
1410 /* Compute authenticator (this is the main difference to #send_kx()) */
1411 GNUNET_CRYPTO_hash (&ax->RK,
1415 /* Compute when to be triggered again; actual job will
1416 be scheduled via #connection_ready_cb() */
1418 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1420 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1422 /* Send via cc, mark it as unready */
1423 mark_connection_unready (ct);
1425 /* Update state machine, unless we are already OK */
1426 if (CADET_TUNNEL_KEY_OK != t->estate)
1427 GCT_change_estate (t,
1428 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1436 * Cleanup state used by @a ax.
1438 * @param ax state to free, but not memory of @a ax itself
1441 cleanup_ax (struct CadetTunnelAxolotl *ax)
1443 while (NULL != ax->skipped_head)
1444 delete_skipped_key (ax,
1446 GNUNET_assert (0 == ax->skipped);
1447 GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1448 GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1453 * Update our Axolotl key state based on the KX data we received.
1454 * Computes the new chain keys, and root keys, etc, and also checks
1455 * wether this is a replay of the current chain.
1457 * @param[in|out] axolotl chain key state to recompute
1458 * @param pid peer identity of the other peer
1459 * @param ephemeral_key ephemeral public key of the other peer
1460 * @param ratchet_key senders next ephemeral public key
1461 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1462 * root key is already in @a ax and thus the KX is useless;
1463 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1466 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1467 const struct GNUNET_PeerIdentity *pid,
1468 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1469 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1471 struct GNUNET_HashCode key_material[3];
1472 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1473 const char salt[] = "CADET Axolotl salt";
1476 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1478 am_I_alice = GNUNET_YES;
1479 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1481 am_I_alice = GNUNET_NO;
1484 GNUNET_break_op (0);
1485 return GNUNET_SYSERR;
1488 if (0 == memcmp (&ax->DHRr,
1490 sizeof (*ratchet_key)))
1492 LOG (GNUNET_ERROR_TYPE_DEBUG,
1493 "Ratchet key already known. Ignoring KX.\n");
1497 ax->DHRr = *ratchet_key;
1500 if (GNUNET_YES == am_I_alice)
1502 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1503 ephemeral_key, /* B0 */
1508 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* B0 */
1509 &pid->public_key, /* A */
1514 if (GNUNET_YES == am_I_alice)
1516 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* A0 */
1517 &pid->public_key, /* B */
1522 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1523 ephemeral_key, /* B0 */
1530 /* (This is the triple-DH, we could probably safely skip this,
1531 as A0/B0 are already in the key material.) */
1532 GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0, /* A0 or B0 */
1533 ephemeral_key, /* B0 or A0 */
1537 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1538 salt, sizeof (salt),
1539 &key_material, sizeof (key_material),
1542 if (0 == memcmp (&ax->RK,
1546 LOG (GNUNET_ERROR_TYPE_DEBUG,
1547 "Root key of handshake already known. Ignoring KX.\n");
1552 if (GNUNET_YES == am_I_alice)
1558 ax->ratchet_flag = GNUNET_YES;
1566 ax->ratchet_flag = GNUNET_NO;
1567 ax->ratchet_expiration
1568 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1576 * Try to redo the KX or KX_AUTH handshake, if we can.
1578 * @param cls the `struct CadetTunnel` to do KX for.
1581 retry_kx (void *cls)
1583 struct CadetTunnel *t = cls;
1584 struct CadetTunnelAxolotl *ax;
1587 LOG (GNUNET_ERROR_TYPE_DEBUG,
1588 "Trying to make KX progress on %s in state %s\n",
1590 estate2s (t->estate));
1593 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1594 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1599 case CADET_TUNNEL_KEY_AX_RECV:
1600 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1601 /* We are responding, so only require reply
1602 if WE have a channel waiting. */
1603 if (NULL != t->unverified_ax)
1605 /* Send AX_AUTH so we might get this one verified */
1606 ax = t->unverified_ax;
1610 /* How can this be? */
1617 (0 == GCT_count_channels (t))
1621 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1622 /* We are responding, so only require reply
1623 if WE have a channel waiting. */
1624 if (NULL != t->unverified_ax)
1626 /* Send AX_AUTH so we might get this one verified */
1627 ax = t->unverified_ax;
1631 /* How can this be? */
1638 (0 == GCT_count_channels (t))
1642 case CADET_TUNNEL_KEY_OK:
1643 /* Must have been the *other* peer asking us to
1644 respond with a KX_AUTH. */
1645 if (NULL != t->unverified_ax)
1647 /* Sending AX_AUTH in response to AX so we might get this one verified */
1648 ax = t->unverified_ax;
1652 /* Sending AX_AUTH in response to AX_AUTH */
1665 * Handle KX message that lacks authentication (and which will thus
1666 * only be considered authenticated after we respond with our own
1667 * KX_AUTH and finally successfully decrypt payload).
1669 * @param ct connection/tunnel combo that received encrypted message
1670 * @param msg the key exchange message
1673 GCT_handle_kx (struct CadetTConnection *ct,
1674 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1676 struct CadetTunnel *t = ct->t;
1677 struct CadetTunnelAxolotl *ax;
1681 memcmp (&t->ax.DHRr,
1683 sizeof (msg->ratchet_key)))
1685 LOG (GNUNET_ERROR_TYPE_DEBUG,
1686 "Got duplicate KX. Firing back KX_AUTH.\n");
1694 /* We only keep ONE unverified KX around, so if there is an existing one,
1696 if (NULL != t->unverified_ax)
1699 memcmp (&t->unverified_ax->DHRr,
1701 sizeof (msg->ratchet_key)))
1703 LOG (GNUNET_ERROR_TYPE_DEBUG,
1704 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1712 LOG (GNUNET_ERROR_TYPE_DEBUG,
1713 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1715 memset (t->unverified_ax,
1717 sizeof (struct CadetTunnelAxolotl));
1718 t->unverified_ax->DHRs = t->ax.DHRs;
1719 t->unverified_ax->kx_0 = t->ax.kx_0;
1723 LOG (GNUNET_ERROR_TYPE_DEBUG,
1724 "Creating fresh unverified KX for %s.\n",
1726 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1727 t->unverified_ax->DHRs = t->ax.DHRs;
1728 t->unverified_ax->kx_0 = t->ax.kx_0;
1730 /* Set as the 'current' RK/DHRr the one we are currently using,
1731 so that the duplicate-detection logic of
1732 #update_ax_by_kx can work. */
1733 t->unverified_ax->RK = t->ax.RK;
1734 t->unverified_ax->DHRr = t->ax.DHRr;
1735 t->unverified_attempts = 0;
1736 ax = t->unverified_ax;
1738 /* Update 'ax' by the new key material */
1739 ret = update_ax_by_kx (ax,
1740 GCP_get_id (t->destination),
1741 &msg->ephemeral_key,
1743 GNUNET_break (GNUNET_SYSERR != ret);
1744 if (GNUNET_OK != ret)
1745 return; /* duplicate KX, nothing to do */
1747 /* move ahead in our state machine */
1748 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1749 GCT_change_estate (t,
1750 CADET_TUNNEL_KEY_AX_RECV);
1751 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1752 GCT_change_estate (t,
1753 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1755 /* KX is still not done, try again our end. */
1756 if (CADET_TUNNEL_KEY_OK != t->estate)
1758 if (NULL != t->kx_task)
1759 GNUNET_SCHEDULER_cancel (t->kx_task);
1761 = GNUNET_SCHEDULER_add_now (&retry_kx,
1768 * Handle KX_AUTH message.
1770 * @param ct connection/tunnel combo that received encrypted message
1771 * @param msg the key exchange message
1774 GCT_handle_kx_auth (struct CadetTConnection *ct,
1775 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1777 struct CadetTunnel *t = ct->t;
1778 struct CadetTunnelAxolotl ax_tmp;
1779 struct GNUNET_HashCode kx_auth;
1782 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1783 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1785 /* Confusing, we got a KX_AUTH before we even send our own
1786 KX. This should not happen. We'll send our own KX ASAP anyway,
1787 so let's ignore this here. */
1788 GNUNET_break_op (0);
1791 LOG (GNUNET_ERROR_TYPE_DEBUG,
1792 "Handling KX_AUTH message for %s\n",
1795 /* We do everything in ax_tmp until we've checked the authentication
1796 so we don't clobber anything we care about by accident. */
1799 /* Update 'ax' by the new key material */
1800 ret = update_ax_by_kx (&ax_tmp,
1801 GCP_get_id (t->destination),
1802 &msg->kx.ephemeral_key,
1803 &msg->kx.ratchet_key);
1804 if (GNUNET_OK != ret)
1806 if (GNUNET_NO == ret)
1807 GNUNET_STATISTICS_update (stats,
1808 "# redundant KX_AUTH received",
1812 GNUNET_break (0); /* connect to self!? */
1815 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1818 if (0 != memcmp (&kx_auth,
1822 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1823 we transmitted to the sender, refuse it, try KX again. */
1824 GNUNET_STATISTICS_update (stats,
1825 "# KX_AUTH not using our last KX received (auth failure)",
1833 /* Yep, we're good. */
1835 if (NULL != t->unverified_ax)
1837 /* We got some "stale" KX before, drop that. */
1838 cleanup_ax (t->unverified_ax);
1839 GNUNET_free (t->unverified_ax);
1840 t->unverified_ax = NULL;
1843 /* move ahead in our state machine */
1846 case CADET_TUNNEL_KEY_UNINITIALIZED:
1847 case CADET_TUNNEL_KEY_AX_RECV:
1848 /* Checked above, this is impossible. */
1851 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1852 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1853 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1854 GCT_change_estate (t,
1855 CADET_TUNNEL_KEY_OK);
1857 case CADET_TUNNEL_KEY_OK:
1858 /* Did not expect another KX_AUTH, but so what, still acceptable.
1859 Nothing to do here. */
1866 /* ************************************** end core crypto ***************************** */
1870 * Compute the next free channel tunnel number for this tunnel.
1872 * @param t the tunnel
1873 * @return unused number that can uniquely identify a channel in the tunnel
1875 static struct GNUNET_CADET_ChannelTunnelNumber
1876 get_next_free_ctn (struct CadetTunnel *t)
1878 #define HIGH_BIT 0x8000000
1879 struct GNUNET_CADET_ChannelTunnelNumber ret;
1884 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1885 GCP_get_id (GCT_get_destination (t)));
1891 GNUNET_assert (0); // loopback must never go here!
1892 ctn = ntohl (t->next_ctn.cn);
1894 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1897 ctn = ((ctn + 1) & (~ HIGH_BIT));
1899 t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
1900 ret.cn = htonl (ctn | highbit);
1906 * Add a channel to a tunnel, and notify channel that we are ready
1907 * for transmission if we are already up. Otherwise that notification
1908 * will be done later in #notify_tunnel_up_cb().
1912 * @return unique number identifying @a ch within @a t
1914 struct GNUNET_CADET_ChannelTunnelNumber
1915 GCT_add_channel (struct CadetTunnel *t,
1916 struct CadetChannel *ch)
1918 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1920 ctn = get_next_free_ctn (t);
1921 if (NULL != t->destroy_task)
1923 GNUNET_SCHEDULER_cancel (t->destroy_task);
1924 t->destroy_task = NULL;
1926 GNUNET_assert (GNUNET_YES ==
1927 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1930 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1931 LOG (GNUNET_ERROR_TYPE_DEBUG,
1932 "Adding %s to %s\n",
1937 case CADET_TUNNEL_KEY_UNINITIALIZED:
1938 /* waiting for connection to start KX */
1940 case CADET_TUNNEL_KEY_AX_RECV:
1941 case CADET_TUNNEL_KEY_AX_SENT:
1942 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1943 /* we're currently waiting for KX to complete */
1945 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1946 /* waiting for OTHER peer to send us data,
1947 we might need to prompt more aggressively! */
1948 if (NULL == t->kx_task)
1950 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1954 case CADET_TUNNEL_KEY_OK:
1955 /* We are ready. Tell the new channel that we are up. */
1956 GCCH_tunnel_up (ch);
1964 * We lost a connection, remove it from our list and clean up
1965 * the connection object itself.
1967 * @param ct binding of connection to tunnel of the connection that was lost.
1970 GCT_connection_lost (struct CadetTConnection *ct)
1972 struct CadetTunnel *t = ct->t;
1974 if (GNUNET_YES == ct->is_ready)
1976 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
1977 t->connection_ready_tail,
1979 t->num_ready_connections--;
1983 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
1984 t->connection_busy_tail,
1986 t->num_busy_connections--;
1993 * Clean up connection @a ct of a tunnel.
1995 * @param cls the `struct CadetTunnel`
1996 * @param ct connection to clean up
1999 destroy_t_connection (void *cls,
2000 struct CadetTConnection *ct)
2002 struct CadetTunnel *t = cls;
2003 struct CadetConnection *cc = ct->cc;
2005 GNUNET_assert (ct->t == t);
2006 GCT_connection_lost (ct);
2007 GCC_destroy_without_tunnel (cc);
2012 * This tunnel is no longer used, destroy it.
2014 * @param cls the idle tunnel
2017 destroy_tunnel (void *cls)
2019 struct CadetTunnel *t = cls;
2020 struct CadetTunnelQueueEntry *tq;
2022 t->destroy_task = NULL;
2023 LOG (GNUNET_ERROR_TYPE_DEBUG,
2024 "Destroying idle %s\n",
2026 GNUNET_assert (0 == GCT_count_channels (t));
2027 GCT_iterate_connections (t,
2028 &destroy_t_connection,
2030 GNUNET_assert (NULL == t->connection_ready_head);
2031 GNUNET_assert (NULL == t->connection_busy_head);
2032 while (NULL != (tq = t->tq_head))
2034 if (NULL != tq->cont)
2035 tq->cont (tq->cont_cls,
2037 GCT_send_cancel (tq);
2039 GCP_drop_tunnel (t->destination,
2041 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2042 if (NULL != t->maintain_connections_task)
2044 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2045 t->maintain_connections_task = NULL;
2047 if (NULL != t->send_task)
2049 GNUNET_SCHEDULER_cancel (t->send_task);
2050 t->send_task = NULL;
2052 if (NULL != t->kx_task)
2054 GNUNET_SCHEDULER_cancel (t->kx_task);
2057 GNUNET_MST_destroy (t->mst);
2058 GNUNET_MQ_destroy (t->mq);
2059 if (NULL != t->unverified_ax)
2061 cleanup_ax (t->unverified_ax);
2062 GNUNET_free (t->unverified_ax);
2064 cleanup_ax (&t->ax);
2065 GNUNET_assert (NULL == t->destroy_task);
2071 * Remove a channel from a tunnel.
2075 * @param ctn unique number identifying @a ch within @a t
2078 GCT_remove_channel (struct CadetTunnel *t,
2079 struct CadetChannel *ch,
2080 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2082 LOG (GNUNET_ERROR_TYPE_DEBUG,
2083 "Removing %s from %s\n",
2086 GNUNET_assert (GNUNET_YES ==
2087 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2091 GCT_count_channels (t)) &&
2092 (NULL == t->destroy_task) )
2095 = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2103 * Destroy remaining channels during shutdown.
2105 * @param cls the `struct CadetTunnel` of the channel
2106 * @param key key of the channel
2107 * @param value the `struct CadetChannel`
2108 * @return #GNUNET_OK (continue to iterate)
2111 destroy_remaining_channels (void *cls,
2115 struct CadetChannel *ch = value;
2117 GCCH_handle_remote_destroy (ch,
2124 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2126 * @param t tunnel to destroy
2129 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2131 GNUNET_assert (GNUNET_YES == shutting_down);
2132 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2133 &destroy_remaining_channels,
2136 GCT_count_channels (t));
2137 if (NULL != t->destroy_task)
2139 GNUNET_SCHEDULER_cancel (t->destroy_task);
2140 t->destroy_task = NULL;
2147 * Send normal payload from queue in @a t via connection @a ct.
2148 * Does nothing if our payload queue is empty.
2150 * @param t tunnel to send data from
2151 * @param ct connection to use for transmission (is ready)
2154 try_send_normal_payload (struct CadetTunnel *t,
2155 struct CadetTConnection *ct)
2157 struct CadetTunnelQueueEntry *tq;
2159 GNUNET_assert (GNUNET_YES == ct->is_ready);
2163 /* no messages pending right now */
2164 LOG (GNUNET_ERROR_TYPE_DEBUG,
2165 "Not sending payload of %s on ready %s (nothing pending)\n",
2170 /* ready to send message 'tq' on tunnel 'ct' */
2171 GNUNET_assert (t == tq->t);
2172 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2175 if (NULL != tq->cid)
2176 *tq->cid = *GCC_get_id (ct->cc);
2177 mark_connection_unready (ct);
2178 LOG (GNUNET_ERROR_TYPE_DEBUG,
2179 "Sending payload of %s on %s\n",
2182 GCC_transmit (ct->cc,
2184 if (NULL != tq->cont)
2185 tq->cont (tq->cont_cls,
2186 GCC_get_id (ct->cc));
2192 * A connection is @a is_ready for transmission. Looks at our message
2193 * queue and if there is a message, sends it out via the connection.
2195 * @param cls the `struct CadetTConnection` that is @a is_ready
2196 * @param is_ready #GNUNET_YES if connection are now ready,
2197 * #GNUNET_NO if connection are no longer ready
2200 connection_ready_cb (void *cls,
2203 struct CadetTConnection *ct = cls;
2204 struct CadetTunnel *t = ct->t;
2206 if (GNUNET_NO == is_ready)
2208 LOG (GNUNET_ERROR_TYPE_DEBUG,
2209 "%s no longer ready for %s\n",
2212 mark_connection_unready (ct);
2215 GNUNET_assert (GNUNET_NO == ct->is_ready);
2216 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2217 t->connection_busy_tail,
2219 GNUNET_assert (0 < t->num_busy_connections);
2220 t->num_busy_connections--;
2221 ct->is_ready = GNUNET_YES;
2222 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2223 t->connection_ready_tail,
2225 t->num_ready_connections++;
2227 LOG (GNUNET_ERROR_TYPE_DEBUG,
2228 "%s now ready for %s in state %s\n",
2231 estate2s (t->estate));
2234 case CADET_TUNNEL_KEY_UNINITIALIZED:
2235 /* Do not begin KX if WE have no channels waiting! */
2236 if (0 == GCT_count_channels (t))
2238 /* We are uninitialized, just transmit immediately,
2239 without undue delay. */
2240 if (NULL != t->kx_task)
2242 GNUNET_SCHEDULER_cancel (t->kx_task);
2249 case CADET_TUNNEL_KEY_AX_RECV:
2250 case CADET_TUNNEL_KEY_AX_SENT:
2251 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2252 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2253 /* we're currently waiting for KX to complete, schedule job */
2254 if (NULL == t->kx_task)
2256 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2260 case CADET_TUNNEL_KEY_OK:
2261 if (GNUNET_YES == t->kx_auth_requested)
2263 if (NULL != t->kx_task)
2265 GNUNET_SCHEDULER_cancel (t->kx_task);
2274 try_send_normal_payload (t,
2282 * Called when either we have a new connection, or a new message in the
2283 * queue, or some existing connection has transmission capacity. Looks
2284 * at our message queue and if there is a message, picks a connection
2287 * @param cls the `struct CadetTunnel` to process messages on
2290 trigger_transmissions (void *cls)
2292 struct CadetTunnel *t = cls;
2293 struct CadetTConnection *ct;
2295 t->send_task = NULL;
2296 if (NULL == t->tq_head)
2297 return; /* no messages pending right now */
2298 ct = get_ready_connection (t);
2300 return; /* no connections ready */
2301 try_send_normal_payload (t,
2307 * Closure for #evaluate_connection. Used to assemble summary information
2308 * about the existing connections so we can evaluate a new path.
2310 struct EvaluationSummary
2314 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2316 unsigned int min_length;
2319 * Maximum length of any of our connections, 0 if we have none.
2321 unsigned int max_length;
2324 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2326 GNUNET_CONTAINER_HeapCostType min_desire;
2329 * Maximum desirability of any of our connections, 0 if we have none.
2331 GNUNET_CONTAINER_HeapCostType max_desire;
2334 * Path we are comparing against for #evaluate_connection, can be NULL.
2336 struct CadetPeerPath *path;
2339 * Connection deemed the "worst" so far encountered by #evaluate_connection,
2340 * NULL if we did not yet encounter any connections.
2342 struct CadetTConnection *worst;
2345 * Numeric score of @e worst, only set if @e worst is non-NULL.
2350 * Set to #GNUNET_YES if we have a connection over @e path already.
2358 * Evaluate a connection, updating our summary information in @a cls about
2359 * what kinds of connections we have.
2361 * @param cls the `struct EvaluationSummary *` to update
2362 * @param ct a connection to include in the summary
2365 evaluate_connection (void *cls,
2366 struct CadetTConnection *ct)
2368 struct EvaluationSummary *es = cls;
2369 struct CadetConnection *cc = ct->cc;
2370 struct CadetPeerPath *ps = GCC_get_path (cc);
2371 const struct CadetConnectionMetrics *metrics;
2372 GNUNET_CONTAINER_HeapCostType ct_desirability;
2373 struct GNUNET_TIME_Relative uptime;
2374 struct GNUNET_TIME_Relative last_use;
2377 double success_rate;
2381 LOG (GNUNET_ERROR_TYPE_DEBUG,
2382 "Ignoring duplicate path %s.\n",
2383 GCPP_2s (es->path));
2384 es->duplicate = GNUNET_YES;
2387 ct_desirability = GCPP_get_desirability (ps);
2388 ct_length = GCPP_get_length (ps);
2389 metrics = GCC_get_metrics (cc);
2390 uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2391 last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2392 /* We add 1.0 here to avoid division by zero. */
2393 success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2396 + 100.0 / (1.0 + ct_length) /* longer paths = better */
2397 + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2398 - last_use.rel_value_us / 1000L; /* longer idle = worse */
2399 score *= success_rate; /* weigh overall by success rate */
2401 if ( (NULL == es->worst) ||
2402 (score < es->worst_score) )
2405 es->worst_score = score;
2407 es->min_length = GNUNET_MIN (es->min_length,
2409 es->max_length = GNUNET_MAX (es->max_length,
2411 es->min_desire = GNUNET_MIN (es->min_desire,
2413 es->max_desire = GNUNET_MAX (es->max_desire,
2419 * Consider using the path @a p for the tunnel @a t.
2420 * The tunnel destination is at offset @a off in path @a p.
2422 * @param cls our tunnel
2423 * @param path a path to our destination
2424 * @param off offset of the destination on path @a path
2425 * @return #GNUNET_YES (should keep iterating)
2428 consider_path_cb (void *cls,
2429 struct CadetPeerPath *path,
2432 struct CadetTunnel *t = cls;
2433 struct EvaluationSummary es;
2434 struct CadetTConnection *ct;
2436 GNUNET_assert (off < GCPP_get_length (path));
2437 es.min_length = UINT_MAX;
2440 es.min_desire = UINT64_MAX;
2442 es.duplicate = GNUNET_NO;
2445 /* Compute evaluation summary over existing connections. */
2446 GCT_iterate_connections (t,
2447 &evaluate_connection,
2449 if (GNUNET_YES == es.duplicate)
2452 /* FIXME: not sure we should really just count
2453 'num_connections' here, as they may all have
2454 consistently failed to connect. */
2456 /* We iterate by increasing path length; if we have enough paths and
2457 this one is more than twice as long than what we are currently
2458 using, then ignore all of these super-long ones! */
2459 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2460 (es.min_length * 2 < off) &&
2461 (es.max_length < off) )
2463 LOG (GNUNET_ERROR_TYPE_DEBUG,
2464 "Ignoring paths of length %u, they are way too long.\n",
2468 /* If we have enough paths and this one looks no better, ignore it. */
2469 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2470 (es.min_length < GCPP_get_length (path)) &&
2471 (es.min_desire > GCPP_get_desirability (path)) &&
2472 (es.max_length < off) )
2474 LOG (GNUNET_ERROR_TYPE_DEBUG,
2475 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2476 GCPP_get_length (path),
2477 (unsigned long long) GCPP_get_desirability (path),
2478 GCP_2s (t->destination));
2482 /* Path is interesting (better by some metric, or we don't have
2483 enough paths yet). */
2484 ct = GNUNET_new (struct CadetTConnection);
2485 ct->created = GNUNET_TIME_absolute_get ();
2487 ct->cc = GCC_create (t->destination,
2490 GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2492 &connection_ready_cb,
2495 /* FIXME: schedule job to kill connection (and path?) if it takes
2496 too long to get ready! (And track performance data on how long
2497 other connections took with the tunnel!)
2498 => Note: to be done within 'connection'-logic! */
2499 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2500 t->connection_busy_tail,
2502 t->num_busy_connections++;
2503 LOG (GNUNET_ERROR_TYPE_DEBUG,
2504 "Found interesting path %s for %s, created %s\n",
2513 * Function called to maintain the connections underlying our tunnel.
2514 * Tries to maintain (incl. tear down) connections for the tunnel, and
2515 * if there is a significant change, may trigger transmissions.
2517 * Basically, needs to check if there are connections that perform
2518 * badly, and if so eventually kill them and trigger a replacement.
2519 * The strategy is to open one more connection than
2520 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2521 * least-performing one, and then inquire for new ones.
2523 * @param cls the `struct CadetTunnel`
2526 maintain_connections_cb (void *cls)
2528 struct CadetTunnel *t = cls;
2529 struct GNUNET_TIME_Relative delay;
2530 struct EvaluationSummary es;
2532 t->maintain_connections_task = NULL;
2533 LOG (GNUNET_ERROR_TYPE_DEBUG,
2534 "Performing connection maintenance for %s.\n",
2537 es.min_length = UINT_MAX;
2540 es.min_desire = UINT64_MAX;
2543 es.duplicate = GNUNET_NO;
2544 GCT_iterate_connections (t,
2545 &evaluate_connection,
2547 if ( (NULL != es.worst) &&
2548 (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2550 /* Clear out worst-performing connection 'es.worst'. */
2551 destroy_t_connection (t,
2555 /* Consider additional paths */
2556 (void) GCP_iterate_paths (t->destination,
2560 /* FIXME: calculate when to try again based on how well we are doing;
2561 in particular, if we have to few connections, we might be able
2562 to do without this (as PATHS should tell us whenever a new path
2563 is available instantly; however, need to make sure this job is
2564 restarted after that happens).
2565 Furthermore, if the paths we do know are in a reasonably narrow
2566 quality band and are plentyful, we might also consider us stabilized
2567 and then reduce the frequency accordingly. */
2568 delay = GNUNET_TIME_UNIT_MINUTES;
2569 t->maintain_connections_task
2570 = GNUNET_SCHEDULER_add_delayed (delay,
2571 &maintain_connections_cb,
2577 * Consider using the path @a p for the tunnel @a t.
2578 * The tunnel destination is at offset @a off in path @a p.
2580 * @param cls our tunnel
2581 * @param path a path to our destination
2582 * @param off offset of the destination on path @a path
2585 GCT_consider_path (struct CadetTunnel *t,
2586 struct CadetPeerPath *p,
2589 LOG (GNUNET_ERROR_TYPE_DEBUG,
2590 "Considering %s for %s\n",
2593 (void) consider_path_cb (t,
2600 * We got a keepalive. Track in statistics.
2602 * @param cls the `struct CadetTunnel` for which we decrypted the message
2603 * @param msg the message we received on the tunnel
2606 handle_plaintext_keepalive (void *cls,
2607 const struct GNUNET_MessageHeader *msg)
2609 struct CadetTunnel *t = cls;
2611 LOG (GNUNET_ERROR_TYPE_DEBUG,
2612 "Received KEEPALIVE on %s\n",
2614 GNUNET_STATISTICS_update (stats,
2615 "# keepalives received",
2622 * Check that @a msg is well-formed.
2624 * @param cls the `struct CadetTunnel` for which we decrypted the message
2625 * @param msg the message we received on the tunnel
2626 * @return #GNUNET_OK (any variable-size payload goes)
2629 check_plaintext_data (void *cls,
2630 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2637 * We received payload data for a channel. Locate the channel
2638 * and process the data, or return an error if the channel is unknown.
2640 * @param cls the `struct CadetTunnel` for which we decrypted the message
2641 * @param msg the message we received on the tunnel
2644 handle_plaintext_data (void *cls,
2645 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2647 struct CadetTunnel *t = cls;
2648 struct CadetChannel *ch;
2650 ch = lookup_channel (t,
2654 /* We don't know about such a channel, might have been destroyed on our
2655 end in the meantime, or never existed. Send back a DESTROY. */
2656 LOG (GNUNET_ERROR_TYPE_DEBUG,
2657 "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2658 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2659 ntohl (msg->ctn.cn));
2660 GCT_send_channel_destroy (t,
2664 GCCH_handle_channel_plaintext_data (ch,
2665 GCC_get_id (t->current_ct->cc),
2671 * We received an acknowledgement for data we sent on a channel.
2672 * Locate the channel and process it, or return an error if the
2673 * channel is unknown.
2675 * @param cls the `struct CadetTunnel` for which we decrypted the message
2676 * @param ack the message we received on the tunnel
2679 handle_plaintext_data_ack (void *cls,
2680 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2682 struct CadetTunnel *t = cls;
2683 struct CadetChannel *ch;
2685 ch = lookup_channel (t,
2689 /* We don't know about such a channel, might have been destroyed on our
2690 end in the meantime, or never existed. Send back a DESTROY. */
2691 LOG (GNUNET_ERROR_TYPE_DEBUG,
2692 "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2693 ntohl (ack->ctn.cn));
2694 GCT_send_channel_destroy (t,
2698 GCCH_handle_channel_plaintext_data_ack (ch,
2699 GCC_get_id (t->current_ct->cc),
2705 * We have received a request to open a channel to a port from
2706 * another peer. Creates the incoming channel.
2708 * @param cls the `struct CadetTunnel` for which we decrypted the message
2709 * @param copen the message we received on the tunnel
2712 handle_plaintext_channel_open (void *cls,
2713 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2715 struct CadetTunnel *t = cls;
2716 struct CadetChannel *ch;
2718 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2719 ntohl (copen->ctn.cn));
2722 LOG (GNUNET_ERROR_TYPE_DEBUG,
2723 "Received duplicate channel CHANNEL_OPEN on port %s from %s (%s), resending ACK\n",
2724 GNUNET_h2s (&copen->port),
2727 GCCH_handle_duplicate_open (ch,
2728 GCC_get_id (t->current_ct->cc));
2731 LOG (GNUNET_ERROR_TYPE_DEBUG,
2732 "Received CHANNEL_OPEN on port %s from %s\n",
2733 GNUNET_h2s (&copen->port),
2735 ch = GCCH_channel_incoming_new (t,
2738 ntohl (copen->opt));
2739 if (NULL != t->destroy_task)
2741 GNUNET_SCHEDULER_cancel (t->destroy_task);
2742 t->destroy_task = NULL;
2744 GNUNET_assert (GNUNET_OK ==
2745 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2746 ntohl (copen->ctn.cn),
2748 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2753 * Send a DESTROY message via the tunnel.
2755 * @param t the tunnel to transmit over
2756 * @param ctn ID of the channel to destroy
2759 GCT_send_channel_destroy (struct CadetTunnel *t,
2760 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2762 struct GNUNET_CADET_ChannelManageMessage msg;
2764 LOG (GNUNET_ERROR_TYPE_DEBUG,
2765 "Sending DESTORY message for channel ID %u\n",
2767 msg.header.size = htons (sizeof (msg));
2768 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2769 msg.reserved = htonl (0);
2779 * We have received confirmation from the target peer that the
2780 * given channel could be established (the port is open).
2783 * @param cls the `struct CadetTunnel` for which we decrypted the message
2784 * @param cm the message we received on the tunnel
2787 handle_plaintext_channel_open_ack (void *cls,
2788 const struct GNUNET_CADET_ChannelManageMessage *cm)
2790 struct CadetTunnel *t = cls;
2791 struct CadetChannel *ch;
2793 ch = lookup_channel (t,
2797 /* We don't know about such a channel, might have been destroyed on our
2798 end in the meantime, or never existed. Send back a DESTROY. */
2799 LOG (GNUNET_ERROR_TYPE_DEBUG,
2800 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2801 ntohl (cm->ctn.cn));
2802 GCT_send_channel_destroy (t,
2806 LOG (GNUNET_ERROR_TYPE_DEBUG,
2807 "Received channel OPEN_ACK on channel %s from %s\n",
2810 GCCH_handle_channel_open_ack (ch,
2811 GCC_get_id (t->current_ct->cc));
2816 * We received a message saying that a channel should be destroyed.
2817 * Pass it on to the correct channel.
2819 * @param cls the `struct CadetTunnel` for which we decrypted the message
2820 * @param cm the message we received on the tunnel
2823 handle_plaintext_channel_destroy (void *cls,
2824 const struct GNUNET_CADET_ChannelManageMessage *cm)
2826 struct CadetTunnel *t = cls;
2827 struct CadetChannel *ch;
2829 ch = lookup_channel (t,
2833 /* We don't know about such a channel, might have been destroyed on our
2834 end in the meantime, or never existed. */
2835 LOG (GNUNET_ERROR_TYPE_DEBUG,
2836 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2837 ntohl (cm->ctn.cn));
2840 LOG (GNUNET_ERROR_TYPE_DEBUG,
2841 "Received channel DESTROY on %s from %s\n",
2844 GCCH_handle_remote_destroy (ch,
2845 GCC_get_id (t->current_ct->cc));
2850 * Handles a message we decrypted, by injecting it into
2851 * our message queue (which will do the dispatching).
2853 * @param cls the `struct CadetTunnel` that got the message
2854 * @param msg the message
2855 * @return #GNUNET_OK (continue to process)
2858 handle_decrypted (void *cls,
2859 const struct GNUNET_MessageHeader *msg)
2861 struct CadetTunnel *t = cls;
2863 GNUNET_assert (NULL != t->current_ct);
2864 GNUNET_MQ_inject_message (t->mq,
2871 * Function called if we had an error processing
2872 * an incoming decrypted message.
2874 * @param cls the `struct CadetTunnel`
2875 * @param error error code
2878 decrypted_error_cb (void *cls,
2879 enum GNUNET_MQ_Error error)
2881 GNUNET_break_op (0);
2886 * Create a tunnel to @a destionation. Must only be called
2887 * from within #GCP_get_tunnel().
2889 * @param destination where to create the tunnel to
2890 * @return new tunnel to @a destination
2892 struct CadetTunnel *
2893 GCT_create_tunnel (struct CadetPeer *destination)
2895 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2896 struct GNUNET_MQ_MessageHandler handlers[] = {
2897 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2898 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2899 struct GNUNET_MessageHeader,
2901 GNUNET_MQ_hd_var_size (plaintext_data,
2902 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2903 struct GNUNET_CADET_ChannelAppDataMessage,
2905 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2906 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2907 struct GNUNET_CADET_ChannelDataAckMessage,
2909 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2910 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2911 struct GNUNET_CADET_ChannelOpenMessage,
2913 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2914 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2915 struct GNUNET_CADET_ChannelManageMessage,
2917 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2918 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2919 struct GNUNET_CADET_ChannelManageMessage,
2921 GNUNET_MQ_handler_end ()
2924 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2925 new_ephemeral (&t->ax);
2926 GNUNET_assert (GNUNET_OK ==
2927 GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2928 t->destination = destination;
2929 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2930 t->maintain_connections_task
2931 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2933 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2938 &decrypted_error_cb,
2940 t->mst = GNUNET_MST_create (&handle_decrypted,
2947 * Add a @a connection to the @a tunnel.
2950 * @param cid connection identifer to use for the connection
2951 * @param options options for the connection
2952 * @param path path to use for the connection
2953 * @return #GNUNET_OK on success,
2954 * #GNUNET_SYSERR on failure (duplicate connection)
2957 GCT_add_inbound_connection (struct CadetTunnel *t,
2958 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2959 enum GNUNET_CADET_ChannelOption options,
2960 struct CadetPeerPath *path)
2962 struct CadetTConnection *ct;
2964 ct = GNUNET_new (struct CadetTConnection);
2965 ct->created = GNUNET_TIME_absolute_get ();
2967 ct->cc = GCC_create_inbound (t->destination,
2972 &connection_ready_cb,
2976 LOG (GNUNET_ERROR_TYPE_DEBUG,
2977 "%s refused inbound %s (duplicate)\n",
2981 return GNUNET_SYSERR;
2983 /* FIXME: schedule job to kill connection (and path?) if it takes
2984 too long to get ready! (And track performance data on how long
2985 other connections took with the tunnel!)
2986 => Note: to be done within 'connection'-logic! */
2987 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2988 t->connection_busy_tail,
2990 t->num_busy_connections++;
2991 LOG (GNUNET_ERROR_TYPE_DEBUG,
3000 * Handle encrypted message.
3002 * @param ct connection/tunnel combo that received encrypted message
3003 * @param msg the encrypted message to decrypt
3006 GCT_handle_encrypted (struct CadetTConnection *ct,
3007 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3009 struct CadetTunnel *t = ct->t;
3010 uint16_t size = ntohs (msg->header.size);
3011 char cbuf [size] GNUNET_ALIGN;
3012 ssize_t decrypted_size;
3014 LOG (GNUNET_ERROR_TYPE_DEBUG,
3015 "%s received %u bytes of encrypted data in state %d\n",
3017 (unsigned int) size,
3022 case CADET_TUNNEL_KEY_UNINITIALIZED:
3023 case CADET_TUNNEL_KEY_AX_RECV:
3024 /* We did not even SEND our KX, how can the other peer
3025 send us encrypted data? Must have been that we went
3026 down and the other peer still things we are up.
3027 Let's send it KX back. */
3028 GNUNET_STATISTICS_update (stats,
3029 "# received encrypted without any KX",
3032 if (NULL != t->kx_task)
3034 GNUNET_SCHEDULER_cancel (t->kx_task);
3041 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3042 /* We send KX, and other peer send KX to us at the same time.
3043 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3044 GNUNET_STATISTICS_update (stats,
3045 "# received encrypted without KX_AUTH",
3048 if (NULL != t->kx_task)
3050 GNUNET_SCHEDULER_cancel (t->kx_task);
3058 case CADET_TUNNEL_KEY_AX_SENT:
3059 /* We did not get the KX of the other peer, but that
3060 might have been lost. Send our KX again immediately. */
3061 GNUNET_STATISTICS_update (stats,
3062 "# received encrypted without KX",
3065 if (NULL != t->kx_task)
3067 GNUNET_SCHEDULER_cancel (t->kx_task);
3074 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3075 /* Great, first payload, we might graduate to OK! */
3076 case CADET_TUNNEL_KEY_OK:
3077 /* We are up and running, all good. */
3081 GNUNET_STATISTICS_update (stats,
3082 "# received encrypted",
3085 decrypted_size = -1;
3086 if (CADET_TUNNEL_KEY_OK == t->estate)
3088 /* We have well-established key material available,
3089 try that. (This is the common case.) */
3090 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3096 if ( (-1 == decrypted_size) &&
3097 (NULL != t->unverified_ax) )
3099 /* We have un-authenticated KX material available. We should try
3100 this as a back-up option, in case the sender crashed and
3102 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3106 if (-1 != decrypted_size)
3108 /* It worked! Treat this as authentication of the AX data! */
3109 cleanup_ax (&t->ax);
3110 t->ax = *t->unverified_ax;
3111 GNUNET_free (t->unverified_ax);
3112 t->unverified_ax = NULL;
3114 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3116 /* First time it worked, move tunnel into production! */
3117 GCT_change_estate (t,
3118 CADET_TUNNEL_KEY_OK);
3119 if (NULL != t->send_task)
3120 GNUNET_SCHEDULER_cancel (t->send_task);
3121 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3125 if (NULL != t->unverified_ax)
3127 /* We had unverified KX material that was useless; so increment
3128 counter and eventually move to ignore it. Note that we even do
3129 this increment if we successfully decrypted with the old KX
3130 material and thus didn't even both with the new one. This is
3131 the ideal case, as a malicious injection of bogus KX data
3132 basically only causes us to increment a counter a few times. */
3133 t->unverified_attempts++;
3134 LOG (GNUNET_ERROR_TYPE_DEBUG,
3135 "Failed to decrypt message with unverified KX data %u times\n",
3136 t->unverified_attempts);
3137 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3139 cleanup_ax (t->unverified_ax);
3140 GNUNET_free (t->unverified_ax);
3141 t->unverified_ax = NULL;
3145 if (-1 == decrypted_size)
3147 /* Decryption failed for good, complain. */
3148 LOG (GNUNET_ERROR_TYPE_WARNING,
3149 "%s failed to decrypt and validate encrypted data, retrying KX\n",
3151 GNUNET_STATISTICS_update (stats,
3152 "# unable to decrypt",
3155 if (NULL != t->kx_task)
3157 GNUNET_SCHEDULER_cancel (t->kx_task);
3166 /* The MST will ultimately call #handle_decrypted() on each message. */
3168 GNUNET_break_op (GNUNET_OK ==
3169 GNUNET_MST_from_buffer (t->mst,
3174 t->current_ct = NULL;
3179 * Sends an already built message on a tunnel, encrypting it and
3180 * choosing the best connection if not provided.
3182 * @param message Message to send. Function modifies it.
3183 * @param t Tunnel on which this message is transmitted.
3184 * @param cont Continuation to call once message is really sent.
3185 * @param cont_cls Closure for @c cont.
3186 * @return Handle to cancel message
3188 struct CadetTunnelQueueEntry *
3189 GCT_send (struct CadetTunnel *t,
3190 const struct GNUNET_MessageHeader *message,
3191 GCT_SendContinuation cont,
3194 struct CadetTunnelQueueEntry *tq;
3195 uint16_t payload_size;
3196 struct GNUNET_MQ_Envelope *env;
3197 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3199 if (CADET_TUNNEL_KEY_OK != t->estate)
3204 payload_size = ntohs (message->size);
3205 LOG (GNUNET_ERROR_TYPE_DEBUG,
3206 "Encrypting %u bytes for %s\n",
3207 (unsigned int) payload_size,
3209 env = GNUNET_MQ_msg_extra (ax_msg,
3211 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3212 t_ax_encrypt (&t->ax,
3216 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3217 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3218 /* FIXME: we should do this once, not once per message;
3219 this is a point multiplication, and DHRs does not
3220 change all the time. */
3221 GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3222 &ax_msg->ax_header.DHRs);
3223 t_h_encrypt (&t->ax,
3225 t_hmac (&ax_msg->ax_header,
3226 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3231 tq = GNUNET_malloc (sizeof (*tq));
3234 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3236 tq->cont_cls = cont_cls;
3237 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3240 if (NULL != t->send_task)
3241 GNUNET_SCHEDULER_cancel (t->send_task);
3243 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3250 * Cancel a previously sent message while it's in the queue.
3252 * ONLY can be called before the continuation given to the send
3253 * function is called. Once the continuation is called, the message is
3254 * no longer in the queue!
3256 * @param tq Handle to the queue entry to cancel.
3259 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3261 struct CadetTunnel *t = tq->t;
3263 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3266 GNUNET_MQ_discard (tq->env);
3272 * Iterate over all connections of a tunnel.
3274 * @param t Tunnel whose connections to iterate.
3275 * @param iter Iterator.
3276 * @param iter_cls Closure for @c iter.
3279 GCT_iterate_connections (struct CadetTunnel *t,
3280 GCT_ConnectionIterator iter,
3283 struct CadetTConnection *n;
3284 for (struct CadetTConnection *ct = t->connection_ready_head;
3292 for (struct CadetTConnection *ct = t->connection_busy_head;
3304 * Closure for #iterate_channels_cb.
3311 GCT_ChannelIterator iter;
3314 * Closure for @e iter.
3321 * Helper function for #GCT_iterate_channels.
3323 * @param cls the `struct ChanIterCls`
3325 * @param value a `struct CadetChannel`
3326 * @return #GNUNET_OK
3329 iterate_channels_cb (void *cls,
3333 struct ChanIterCls *ctx = cls;
3334 struct CadetChannel *ch = value;
3336 ctx->iter (ctx->iter_cls,
3343 * Iterate over all channels of a tunnel.
3345 * @param t Tunnel whose channels to iterate.
3346 * @param iter Iterator.
3347 * @param iter_cls Closure for @c iter.
3350 GCT_iterate_channels (struct CadetTunnel *t,
3351 GCT_ChannelIterator iter,
3354 struct ChanIterCls ctx;
3357 ctx.iter_cls = iter_cls;
3358 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3359 &iterate_channels_cb,
3366 * Call #GCCH_debug() on a channel.
3368 * @param cls points to the log level to use
3370 * @param value the `struct CadetChannel` to dump
3371 * @return #GNUNET_OK (continue iteration)
3374 debug_channel (void *cls,
3378 const enum GNUNET_ErrorType *level = cls;
3379 struct CadetChannel *ch = value;
3381 GCCH_debug (ch, *level);
3386 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3390 * Log all possible info about the tunnel state.
3392 * @param t Tunnel to debug.
3393 * @param level Debug level to use.
3396 GCT_debug (const struct CadetTunnel *t,
3397 enum GNUNET_ErrorType level)
3399 struct CadetTConnection *iter_c;
3402 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3404 __FILE__, __FUNCTION__, __LINE__);
3409 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3411 estate2s (t->estate),
3413 GCT_count_any_connections (t));
3416 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3420 "TTT connections:\n");
3421 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3422 GCC_debug (iter_c->cc,
3424 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3425 GCC_debug (iter_c->cc,
3429 "TTT TUNNEL END\n");
3433 /* end of gnunet-service-cadet-new_tunnels.c */