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_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 "cadet_protocol.h"
38 #include "gnunet-service-cadet_channel.h"
39 #include "gnunet-service-cadet_connection.h"
40 #include "gnunet-service-cadet_tunnels.h"
41 #include "gnunet-service-cadet_peer.h"
42 #include "gnunet-service-cadet_paths.h"
45 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
48 * How often do we try to decrypt payload with unverified key
49 * material? Used to limit CPU increase upon receiving bogus
52 #define MAX_UNVERIFIED_ATTEMPTS 16
55 * How long do we wait until tearing down an idle tunnel?
57 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
60 * How long do we wait initially before retransmitting the KX?
61 * TODO: replace by 2 RTT if/once we have connection-level RTT data!
63 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
66 * Maximum number of skipped keys we keep in memory per tunnel.
68 #define MAX_SKIPPED_KEYS 64
71 * Maximum number of keys (and thus ratchet steps) we are willing to
72 * skip before we decide this is either a bogus packet or a DoS-attempt.
74 #define MAX_KEY_GAP 256
78 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
80 struct CadetTunnelSkippedKey
85 struct CadetTunnelSkippedKey *next;
90 struct CadetTunnelSkippedKey *prev;
93 * When was this key stored (for timeout).
95 struct GNUNET_TIME_Absolute timestamp;
100 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
105 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
108 * Key number for a given HK.
115 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
117 struct CadetTunnelAxolotl
120 * A (double linked) list of stored message keys and associated header keys
121 * for "skipped" messages, i.e. messages that have not been
122 * received despite the reception of more recent messages, (head).
124 struct CadetTunnelSkippedKey *skipped_head;
127 * Skipped messages' keys DLL, tail.
129 struct CadetTunnelSkippedKey *skipped_tail;
132 * 32-byte root key which gets updated by DH ratchet.
134 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
137 * 32-byte header key (currently used for sending).
139 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
142 * 32-byte header key (currently used for receiving)
144 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
147 * 32-byte next header key (for sending), used once the
148 * ratchet advances. We are sure that the sender has this
149 * key as well only after @e ratchet_allowed is #GNUNET_YES.
151 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
154 * 32-byte next header key (for receiving). To be tried
155 * when decrypting with @e HKr fails and thus the sender
156 * may have advanced the ratchet.
158 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
161 * 32-byte chain keys (used for forward-secrecy) for
162 * sending messages. Updated for every message.
164 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
167 * 32-byte chain keys (used for forward-secrecy) for
168 * receiving messages. Updated for every message. If
169 * messages are skipped, the respective derived MKs
170 * (and the current @HKr) are kept in the @e skipped_head DLL.
172 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
175 * ECDH for key exchange (A0 / B0).
177 struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
180 * ECDH Ratchet key (our private key in the current DH).
182 struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
185 * ECDH Ratchet key (other peer's public key in the current DH).
187 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
190 * Time when the current ratchet expires and a new one is triggered
191 * (if @e ratchet_allowed is #GNUNET_YES).
193 struct GNUNET_TIME_Absolute ratchet_expiration;
196 * Number of elements in @a skipped_head <-> @a skipped_tail.
198 unsigned int skipped;
201 * Message number (reset to 0 with each new ratchet, next message to send).
206 * Message number (reset to 0 with each new ratchet, next message to recv).
211 * Previous message numbers (# of msgs sent under prev ratchet)
216 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
221 * True (#GNUNET_YES) if we have received a message from the
222 * other peer that uses the keys from our last ratchet step.
223 * This implies that we are again allowed to advance the ratchet,
224 * otherwise we have to wait until the other peer sees our current
225 * ephemeral key and advances first.
227 * #GNUNET_NO if we have advanced the ratched but lack any evidence
228 * that the other peer has noticed this.
233 * Number of messages recieved since our last ratchet advance.
235 * If this counter = 0, we cannot send a new ratchet key in the next
238 * If this counter > 0, we could (but don't have to) send a new key.
240 * Once the @e ratchet_counter is larger than
241 * #ratchet_messages (or @e ratchet_expiration time has past), and
242 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
244 unsigned int ratchet_counter;
250 * Struct used to save messages in a non-ready tunnel to send once connected.
252 struct CadetTunnelQueueEntry
255 * We are entries in a DLL
257 struct CadetTunnelQueueEntry *next;
260 * We are entries in a DLL
262 struct CadetTunnelQueueEntry *prev;
265 * Tunnel these messages belong in.
267 struct CadetTunnel *t;
270 * Continuation to call once sent (on the channel layer).
272 GCT_SendContinuation cont;
275 * Closure for @c cont.
280 * Envelope of message to send follows.
282 struct GNUNET_MQ_Envelope *env;
285 * Where to put the connection identifier into the payload
286 * of the message in @e env once we have it?
288 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
293 * Struct containing all information regarding a tunnel to a peer.
298 * Destination of the tunnel.
300 struct CadetPeer *destination;
303 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
304 * ephemeral key changes.
306 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
309 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
311 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
314 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
316 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
321 struct CadetTunnelAxolotl ax;
324 * Unverified Axolotl info, used only if we got a fresh KX (not a
325 * KX_AUTH) while our end of the tunnel was still up. In this case,
326 * we keep the fresh KX around but do not put it into action until
327 * we got encrypted payload that assures us of the authenticity of
330 struct CadetTunnelAxolotl *unverified_ax;
333 * Task scheduled if there are no more channels using the tunnel.
335 struct GNUNET_SCHEDULER_Task *destroy_task;
338 * Task to trim connections if too many are present.
340 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
343 * Task to send messages from queue (if possible).
345 struct GNUNET_SCHEDULER_Task *send_task;
348 * Task to trigger KX.
350 struct GNUNET_SCHEDULER_Task *kx_task;
353 * Tokenizer for decrypted messages.
355 struct GNUNET_MessageStreamTokenizer *mst;
358 * Dispatcher for decrypted messages only (do NOT use for sending!).
360 struct GNUNET_MQ_Handle *mq;
363 * DLL of ready connections that are actively used to reach the destination peer.
365 struct CadetTConnection *connection_ready_head;
368 * DLL of ready connections that are actively used to reach the destination peer.
370 struct CadetTConnection *connection_ready_tail;
373 * DLL of connections that we maintain that might be used to reach the destination peer.
375 struct CadetTConnection *connection_busy_head;
378 * DLL of connections that we maintain that might be used to reach the destination peer.
380 struct CadetTConnection *connection_busy_tail;
383 * Channels inside this tunnel. Maps
384 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
386 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
389 * Channel ID for the next created channel in this tunnel.
391 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
394 * Queued messages, to transmit once tunnel gets connected.
396 struct CadetTunnelQueueEntry *tq_head;
399 * Queued messages, to transmit once tunnel gets connected.
401 struct CadetTunnelQueueEntry *tq_tail;
404 * Identification of the connection from which we are currently processing
405 * a message. Only valid (non-NULL) during #handle_decrypted() and the
406 * handle-*()-functions called from our @e mq during that function.
408 struct CadetTConnection *current_ct;
411 * How long do we wait until we retry the KX?
413 struct GNUNET_TIME_Relative kx_retry_delay;
416 * When do we try the next KX?
418 struct GNUNET_TIME_Absolute next_kx_attempt;
421 * Number of connections in the @e connection_ready_head DLL.
423 unsigned int num_ready_connections;
426 * Number of connections in the @e connection_busy_head DLL.
428 unsigned int num_busy_connections;
431 * How often have we tried and failed to decrypt a message using
432 * the unverified KX material from @e unverified_ax? Used to
433 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
435 unsigned int unverified_attempts;
438 * Number of entries in the @e tq_head DLL.
443 * State of the tunnel encryption.
445 enum CadetTunnelEState estate;
448 * Force triggering KX_AUTH independent of @e estate.
450 int kx_auth_requested;
456 * Connection @a ct is now unready, clear it's ready flag
457 * and move it from the ready DLL to the busy DLL.
459 * @param ct connection to move to unready status
462 mark_connection_unready (struct CadetTConnection *ct)
464 struct CadetTunnel *t = ct->t;
466 GNUNET_assert (GNUNET_YES == ct->is_ready);
467 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
468 t->connection_ready_tail,
470 GNUNET_assert (0 < t->num_ready_connections);
471 t->num_ready_connections--;
472 ct->is_ready = GNUNET_NO;
473 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
474 t->connection_busy_tail,
476 t->num_busy_connections++;
481 * Get the static string for the peer this tunnel is directed.
485 * @return Static string the destination peer's ID.
488 GCT_2s (const struct CadetTunnel *t)
493 return "Tunnel(NULL)";
494 GNUNET_snprintf (buf,
497 GNUNET_i2s (GCP_get_id (t->destination)));
503 * Get string description for tunnel encryption state.
505 * @param es Tunnel state.
507 * @return String representation.
510 estate2s (enum CadetTunnelEState es)
516 case CADET_TUNNEL_KEY_UNINITIALIZED:
517 return "CADET_TUNNEL_KEY_UNINITIALIZED";
518 case CADET_TUNNEL_KEY_AX_RECV:
519 return "CADET_TUNNEL_KEY_AX_RECV";
520 case CADET_TUNNEL_KEY_AX_SENT:
521 return "CADET_TUNNEL_KEY_AX_SENT";
522 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
523 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
524 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
525 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
526 case CADET_TUNNEL_KEY_OK:
527 return "CADET_TUNNEL_KEY_OK";
529 GNUNET_snprintf (buf,
531 "%u (UNKNOWN STATE)",
539 * Return the peer to which this tunnel goes.
542 * @return the destination of the tunnel
545 GCT_get_destination (struct CadetTunnel *t)
547 return t->destination;
552 * Count channels of a tunnel.
554 * @param t Tunnel on which to count.
556 * @return Number of channels.
559 GCT_count_channels (struct CadetTunnel *t)
561 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
566 * Lookup a channel by its @a ctn.
568 * @param t tunnel to look in
569 * @param ctn number of channel to find
570 * @return NULL if channel does not exist
572 struct CadetChannel *
573 lookup_channel (struct CadetTunnel *t,
574 struct GNUNET_CADET_ChannelTunnelNumber ctn)
576 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
582 * Count all created connections of a tunnel. Not necessarily ready connections!
584 * @param t Tunnel on which to count.
586 * @return Number of connections created, either being established or ready.
589 GCT_count_any_connections (const struct CadetTunnel *t)
591 return t->num_ready_connections + t->num_busy_connections;
596 * Find first connection that is ready in the list of
597 * our connections. Picks ready connections round-robin.
599 * @param t tunnel to search
600 * @return NULL if we have no connection that is ready
602 static struct CadetTConnection *
603 get_ready_connection (struct CadetTunnel *t)
605 struct CadetTConnection *hd = t->connection_ready_head;
607 GNUNET_assert ( (NULL == hd) ||
608 (GNUNET_YES == hd->is_ready) );
614 * Get the encryption state of a tunnel.
618 * @return Tunnel's encryption state.
620 enum CadetTunnelEState
621 GCT_get_estate (struct CadetTunnel *t)
628 * Called when either we have a new connection, or a new message in the
629 * queue, or some existing connection has transmission capacity. Looks
630 * at our message queue and if there is a message, picks a connection
633 * @param cls the `struct CadetTunnel` to process messages on
636 trigger_transmissions (void *cls);
639 /* ************************************** start core crypto ***************************** */
643 * Create a new Axolotl ephemeral (ratchet) key.
645 * @param ax key material to update
648 new_ephemeral (struct CadetTunnelAxolotl *ax)
650 LOG (GNUNET_ERROR_TYPE_DEBUG,
651 "Creating new ephemeral ratchet key (DHRs)\n");
652 GNUNET_assert (GNUNET_OK ==
653 GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
660 * @param plaintext Content to HMAC.
661 * @param size Size of @c plaintext.
662 * @param iv Initialization vector for the message.
663 * @param key Key to use.
664 * @param hmac[out] Destination to store the HMAC.
667 t_hmac (const void *plaintext,
670 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
671 struct GNUNET_ShortHashCode *hmac)
673 static const char ctx[] = "cadet authentication key";
674 struct GNUNET_CRYPTO_AuthKey auth_key;
675 struct GNUNET_HashCode hash;
677 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
683 /* Two step: GNUNET_ShortHash is only 256 bits,
684 GNUNET_HashCode is 512, so we truncate. */
685 GNUNET_CRYPTO_hmac (&auth_key,
698 * @param key Key to use.
699 * @param[out] hash Resulting HMAC.
700 * @param source Source key material (data to HMAC).
701 * @param len Length of @a source.
704 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
705 struct GNUNET_HashCode *hash,
709 static const char ctx[] = "axolotl HMAC-HASH";
710 struct GNUNET_CRYPTO_AuthKey auth_key;
712 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
716 GNUNET_CRYPTO_hmac (&auth_key,
724 * Derive a symmetric encryption key from an HMAC-HASH.
726 * @param key Key to use for the HMAC.
727 * @param[out] out Key to generate.
728 * @param source Source key material (data to HMAC).
729 * @param len Length of @a source.
732 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
733 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
737 static const char ctx[] = "axolotl derive key";
738 struct GNUNET_HashCode h;
744 GNUNET_CRYPTO_kdf (out, sizeof (*out),
752 * Encrypt data with the axolotl tunnel key.
754 * @param ax key material to use.
755 * @param dst Destination with @a size bytes for the encrypted data.
756 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
757 * @param size Size of the buffers at @a src and @a dst
760 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
765 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
766 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
769 ax->ratchet_counter++;
770 if ( (GNUNET_YES == ax->ratchet_allowed) &&
771 ( (ratchet_messages <= ax->ratchet_counter) ||
772 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
774 ax->ratchet_flag = GNUNET_YES;
776 if (GNUNET_YES == ax->ratchet_flag)
778 /* Advance ratchet */
779 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
780 struct GNUNET_HashCode dh;
781 struct GNUNET_HashCode hmac;
782 static const char ctx[] = "axolotl ratchet";
787 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
788 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
791 t_ax_hmac_hash (&ax->RK,
795 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
797 &hmac, sizeof (hmac),
805 ax->ratchet_flag = GNUNET_NO;
806 ax->ratchet_allowed = GNUNET_NO;
807 ax->ratchet_counter = 0;
808 ax->ratchet_expiration
809 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
813 t_hmac_derive_key (&ax->CKs,
817 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
822 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
827 GNUNET_assert (size == out_size);
828 t_hmac_derive_key (&ax->CKs,
836 * Decrypt data with the axolotl tunnel key.
838 * @param ax key material to use.
839 * @param dst Destination for the decrypted data, must contain @a size bytes.
840 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
841 * @param size Size of the @a src and @a dst buffers
844 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
849 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
850 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
853 t_hmac_derive_key (&ax->CKr,
857 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
861 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
862 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
867 GNUNET_assert (out_size == size);
868 t_hmac_derive_key (&ax->CKr,
876 * Encrypt header with the axolotl header key.
878 * @param ax key material to use.
879 * @param[in|out] msg Message whose header to encrypt.
882 t_h_encrypt (struct CadetTunnelAxolotl *ax,
883 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
885 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
888 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
892 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
893 sizeof (struct GNUNET_CADET_AxHeader),
897 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
902 * Decrypt header with the current axolotl header key.
904 * @param ax key material to use.
905 * @param src Message whose header to decrypt.
906 * @param dst Where to decrypt header to.
909 t_h_decrypt (struct CadetTunnelAxolotl *ax,
910 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
911 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
913 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
916 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
920 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
921 sizeof (struct GNUNET_CADET_AxHeader),
925 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
930 * Delete a key from the list of skipped keys.
932 * @param ax key material to delete @a key from.
933 * @param key Key to delete.
936 delete_skipped_key (struct CadetTunnelAxolotl *ax,
937 struct CadetTunnelSkippedKey *key)
939 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
948 * Decrypt and verify data with the appropriate tunnel key and verify that the
949 * data has not been altered since it was sent by the remote peer.
951 * @param ax key material to use.
952 * @param dst Destination for the plaintext.
953 * @param src Source of the message. Can overlap with @c dst.
954 * @param size Size of the message.
955 * @return Size of the decrypted data, -1 if an error was encountered.
958 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
960 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
963 struct CadetTunnelSkippedKey *key;
964 struct GNUNET_ShortHashCode *hmac;
965 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
966 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
967 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
973 LOG (GNUNET_ERROR_TYPE_DEBUG,
974 "Trying skipped keys\n");
975 hmac = &plaintext_header.hmac;
976 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
978 /* Find a correct Header Key */
980 for (key = ax->skipped_head; NULL != key; key = key->next)
982 t_hmac (&src->ax_header,
983 sizeof (struct GNUNET_CADET_AxHeader) + esize,
987 if (0 == memcmp (hmac,
998 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
999 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
1000 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1001 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1003 /* Decrypt header */
1004 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1008 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1009 sizeof (struct GNUNET_CADET_AxHeader),
1012 &plaintext_header.ax_header.Ns);
1013 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1015 /* Find the correct message key */
1016 N = ntohl (plaintext_header.ax_header.Ns);
1017 while ( (NULL != key) &&
1020 if ( (NULL == key) ||
1021 (0 != memcmp (&key->HK,
1023 sizeof (*valid_HK))) )
1026 /* Decrypt payload */
1027 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1032 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1037 delete_skipped_key (ax,
1044 * Delete a key from the list of skipped keys.
1046 * @param ax key material to delete from.
1047 * @param HKr Header Key to use.
1050 store_skipped_key (struct CadetTunnelAxolotl *ax,
1051 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1053 struct CadetTunnelSkippedKey *key;
1055 key = GNUNET_new (struct CadetTunnelSkippedKey);
1056 key->timestamp = GNUNET_TIME_absolute_get ();
1059 t_hmac_derive_key (&ax->CKr,
1063 t_hmac_derive_key (&ax->CKr,
1067 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1076 * Stage skipped AX keys and calculate the message key.
1077 * Stores each HK and MK for skipped messages.
1079 * @param ax key material to use
1080 * @param HKr Header key.
1081 * @param Np Received meesage number.
1082 * @return #GNUNET_OK if keys were stored.
1083 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1086 store_ax_keys (struct CadetTunnelAxolotl *ax,
1087 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1093 LOG (GNUNET_ERROR_TYPE_DEBUG,
1094 "Storing skipped keys [%u, %u)\n",
1097 if (MAX_KEY_GAP < gap)
1099 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1100 /* TODO: start new key exchange on return */
1101 GNUNET_break_op (0);
1102 LOG (GNUNET_ERROR_TYPE_WARNING,
1103 "Got message %u, expected %u+\n",
1106 return GNUNET_SYSERR;
1110 /* Delayed message: don't store keys, flag to try old keys. */
1111 return GNUNET_SYSERR;
1115 store_skipped_key (ax,
1118 while (ax->skipped > MAX_SKIPPED_KEYS)
1119 delete_skipped_key (ax,
1126 * Decrypt and verify data with the appropriate tunnel key and verify that the
1127 * data has not been altered since it was sent by the remote peer.
1129 * @param ax key material to use
1130 * @param dst Destination for the plaintext.
1131 * @param src Source of the message. Can overlap with @c dst.
1132 * @param size Size of the message.
1133 * @return Size of the decrypted data, -1 if an error was encountered.
1136 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1138 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1141 struct GNUNET_ShortHashCode msg_hmac;
1142 struct GNUNET_HashCode hmac;
1143 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1146 size_t esize; /* Size of encryped payload */
1148 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1150 /* Try current HK */
1151 t_hmac (&src->ax_header,
1152 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1155 if (0 != memcmp (&msg_hmac,
1159 static const char ctx[] = "axolotl ratchet";
1160 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1161 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1162 struct GNUNET_HashCode dh;
1163 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1166 t_hmac (&src->ax_header,
1167 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1171 if (0 != memcmp (&msg_hmac,
1175 /* Try the skipped keys, if that fails, we're out of luck. */
1176 return try_old_ax_keys (ax,
1186 Np = ntohl (plaintext_header.ax_header.Ns);
1187 PNp = ntohl (plaintext_header.ax_header.PNs);
1188 DHRp = &plaintext_header.ax_header.DHRs;
1193 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1194 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1197 t_ax_hmac_hash (&ax->RK,
1200 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1202 &hmac, sizeof (hmac),
1205 /* Commit "purported" keys */
1211 ax->ratchet_allowed = GNUNET_YES;
1218 Np = ntohl (plaintext_header.ax_header.Ns);
1219 PNp = ntohl (plaintext_header.ax_header.PNs);
1221 if ( (Np != ax->Nr) &&
1222 (GNUNET_OK != store_ax_keys (ax,
1226 /* Try the skipped keys, if that fails, we're out of luck. */
1227 return try_old_ax_keys (ax,
1243 * Our tunnel became ready for the first time, notify channels
1244 * that have been waiting.
1246 * @param cls our tunnel, not used
1247 * @param key unique ID of the channel, not used
1248 * @param value the `struct CadetChannel` to notify
1249 * @return #GNUNET_OK (continue to iterate)
1252 notify_tunnel_up_cb (void *cls,
1256 struct CadetChannel *ch = value;
1258 GCCH_tunnel_up (ch);
1264 * Change the tunnel encryption state.
1265 * If the encryption state changes to OK, stop the rekey task.
1267 * @param t Tunnel whose encryption state to change, or NULL.
1268 * @param state New encryption state.
1271 GCT_change_estate (struct CadetTunnel *t,
1272 enum CadetTunnelEState state)
1274 enum CadetTunnelEState old = t->estate;
1277 LOG (GNUNET_ERROR_TYPE_DEBUG,
1278 "%s estate changed from %s to %s\n",
1283 if ( (CADET_TUNNEL_KEY_OK != old) &&
1284 (CADET_TUNNEL_KEY_OK == t->estate) )
1286 if (NULL != t->kx_task)
1288 GNUNET_SCHEDULER_cancel (t->kx_task);
1291 /* notify all channels that have been waiting */
1292 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1293 ¬ify_tunnel_up_cb,
1295 if (NULL != t->send_task)
1296 GNUNET_SCHEDULER_cancel (t->send_task);
1297 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1304 * Send a KX message.
1306 * @param t tunnel on which to send the KX_AUTH
1307 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1308 * we are to find one that is ready.
1309 * @param ax axolotl key context to use
1312 send_kx (struct CadetTunnel *t,
1313 struct CadetTConnection *ct,
1314 struct CadetTunnelAxolotl *ax)
1316 struct CadetConnection *cc;
1317 struct GNUNET_MQ_Envelope *env;
1318 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1319 enum GNUNET_CADET_KX_Flags flags;
1321 if ( (NULL == ct) ||
1322 (GNUNET_NO == ct->is_ready) )
1323 ct = get_ready_connection (t);
1326 LOG (GNUNET_ERROR_TYPE_DEBUG,
1327 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1329 estate2s (t->estate));
1330 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1334 LOG (GNUNET_ERROR_TYPE_DEBUG,
1335 "Sending KX on %s via %s in state %s\n",
1338 estate2s (t->estate));
1339 env = GNUNET_MQ_msg (msg,
1340 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1341 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1342 msg->flags = htonl (flags);
1343 msg->cid = *GCC_get_id (cc);
1344 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1345 &msg->ephemeral_key);
1346 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1348 mark_connection_unready (ct);
1349 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1350 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1351 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1352 GCT_change_estate (t,
1353 CADET_TUNNEL_KEY_AX_SENT);
1354 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1355 GCT_change_estate (t,
1356 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1363 * Send a KX_AUTH message.
1365 * @param t tunnel on which to send the KX_AUTH
1366 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1367 * we are to find one that is ready.
1368 * @param ax axolotl key context to use
1369 * @param force_reply Force the other peer to reply with a KX_AUTH message
1370 * (set if we would like to transmit right now, but cannot)
1373 send_kx_auth (struct CadetTunnel *t,
1374 struct CadetTConnection *ct,
1375 struct CadetTunnelAxolotl *ax,
1378 struct CadetConnection *cc;
1379 struct GNUNET_MQ_Envelope *env;
1380 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1381 enum GNUNET_CADET_KX_Flags flags;
1383 if ( (NULL == ct) ||
1384 (GNUNET_NO == ct->is_ready) )
1385 ct = get_ready_connection (t);
1388 LOG (GNUNET_ERROR_TYPE_DEBUG,
1389 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1391 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1392 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1395 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1397 LOG (GNUNET_ERROR_TYPE_DEBUG,
1398 "Sending KX_AUTH on %s using %s\n",
1402 env = GNUNET_MQ_msg (msg,
1403 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1404 flags = GNUNET_CADET_KX_FLAG_NONE;
1405 if (GNUNET_YES == force_reply)
1406 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1407 msg->kx.flags = htonl (flags);
1408 msg->kx.cid = *GCC_get_id (cc);
1409 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1410 &msg->kx.ephemeral_key);
1411 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1412 &msg->kx.ratchet_key);
1413 /* Compute authenticator (this is the main difference to #send_kx()) */
1414 GNUNET_CRYPTO_hash (&ax->RK,
1418 /* Compute when to be triggered again; actual job will
1419 be scheduled via #connection_ready_cb() */
1421 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1423 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1425 /* Send via cc, mark it as unready */
1426 mark_connection_unready (ct);
1428 /* Update state machine, unless we are already OK */
1429 if (CADET_TUNNEL_KEY_OK != t->estate)
1430 GCT_change_estate (t,
1431 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1439 * Cleanup state used by @a ax.
1441 * @param ax state to free, but not memory of @a ax itself
1444 cleanup_ax (struct CadetTunnelAxolotl *ax)
1446 while (NULL != ax->skipped_head)
1447 delete_skipped_key (ax,
1449 GNUNET_assert (0 == ax->skipped);
1450 GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1451 GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1456 * Update our Axolotl key state based on the KX data we received.
1457 * Computes the new chain keys, and root keys, etc, and also checks
1458 * wether this is a replay of the current chain.
1460 * @param[in|out] axolotl chain key state to recompute
1461 * @param pid peer identity of the other peer
1462 * @param ephemeral_key ephemeral public key of the other peer
1463 * @param ratchet_key senders next ephemeral public key
1464 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1465 * root key is already in @a ax and thus the KX is useless;
1466 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1469 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1470 const struct GNUNET_PeerIdentity *pid,
1471 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1472 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1474 struct GNUNET_HashCode key_material[3];
1475 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1476 const char salt[] = "CADET Axolotl salt";
1479 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1481 am_I_alice = GNUNET_YES;
1482 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1484 am_I_alice = GNUNET_NO;
1487 GNUNET_break_op (0);
1488 return GNUNET_SYSERR;
1491 if (0 == memcmp (&ax->DHRr,
1493 sizeof (*ratchet_key)))
1495 LOG (GNUNET_ERROR_TYPE_DEBUG,
1496 "Ratchet key already known. Ignoring KX.\n");
1500 ax->DHRr = *ratchet_key;
1503 if (GNUNET_YES == am_I_alice)
1505 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1506 ephemeral_key, /* B0 */
1511 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* B0 */
1512 &pid->public_key, /* A */
1517 if (GNUNET_YES == am_I_alice)
1519 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* A0 */
1520 &pid->public_key, /* B */
1525 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1526 ephemeral_key, /* B0 */
1533 /* (This is the triple-DH, we could probably safely skip this,
1534 as A0/B0 are already in the key material.) */
1535 GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0, /* A0 or B0 */
1536 ephemeral_key, /* B0 or A0 */
1540 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1541 salt, sizeof (salt),
1542 &key_material, sizeof (key_material),
1545 if (0 == memcmp (&ax->RK,
1549 LOG (GNUNET_ERROR_TYPE_DEBUG,
1550 "Root key of handshake already known. Ignoring KX.\n");
1555 if (GNUNET_YES == am_I_alice)
1561 ax->ratchet_flag = GNUNET_YES;
1569 ax->ratchet_flag = GNUNET_NO;
1570 ax->ratchet_expiration
1571 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1579 * Try to redo the KX or KX_AUTH handshake, if we can.
1581 * @param cls the `struct CadetTunnel` to do KX for.
1584 retry_kx (void *cls)
1586 struct CadetTunnel *t = cls;
1587 struct CadetTunnelAxolotl *ax;
1590 LOG (GNUNET_ERROR_TYPE_DEBUG,
1591 "Trying to make KX progress on %s in state %s\n",
1593 estate2s (t->estate));
1596 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1597 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1602 case CADET_TUNNEL_KEY_AX_RECV:
1603 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1604 /* We are responding, so only require reply
1605 if WE have a channel waiting. */
1606 if (NULL != t->unverified_ax)
1608 /* Send AX_AUTH so we might get this one verified */
1609 ax = t->unverified_ax;
1613 /* How can this be? */
1620 (0 == GCT_count_channels (t))
1624 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1625 /* We are responding, so only require reply
1626 if WE have a channel waiting. */
1627 if (NULL != t->unverified_ax)
1629 /* Send AX_AUTH so we might get this one verified */
1630 ax = t->unverified_ax;
1634 /* How can this be? */
1641 (0 == GCT_count_channels (t))
1645 case CADET_TUNNEL_KEY_OK:
1646 /* Must have been the *other* peer asking us to
1647 respond with a KX_AUTH. */
1648 if (NULL != t->unverified_ax)
1650 /* Sending AX_AUTH in response to AX so we might get this one verified */
1651 ax = t->unverified_ax;
1655 /* Sending AX_AUTH in response to AX_AUTH */
1668 * Handle KX message that lacks authentication (and which will thus
1669 * only be considered authenticated after we respond with our own
1670 * KX_AUTH and finally successfully decrypt payload).
1672 * @param ct connection/tunnel combo that received encrypted message
1673 * @param msg the key exchange message
1676 GCT_handle_kx (struct CadetTConnection *ct,
1677 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1679 struct CadetTunnel *t = ct->t;
1680 struct CadetTunnelAxolotl *ax;
1684 memcmp (&t->ax.DHRr,
1686 sizeof (msg->ratchet_key)))
1688 LOG (GNUNET_ERROR_TYPE_DEBUG,
1689 "Got duplicate KX. Firing back KX_AUTH.\n");
1697 /* We only keep ONE unverified KX around, so if there is an existing one,
1699 if (NULL != t->unverified_ax)
1702 memcmp (&t->unverified_ax->DHRr,
1704 sizeof (msg->ratchet_key)))
1706 LOG (GNUNET_ERROR_TYPE_DEBUG,
1707 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1715 LOG (GNUNET_ERROR_TYPE_DEBUG,
1716 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1718 memset (t->unverified_ax,
1720 sizeof (struct CadetTunnelAxolotl));
1721 t->unverified_ax->DHRs = t->ax.DHRs;
1722 t->unverified_ax->kx_0 = t->ax.kx_0;
1726 LOG (GNUNET_ERROR_TYPE_DEBUG,
1727 "Creating fresh unverified KX for %s.\n",
1729 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1730 t->unverified_ax->DHRs = t->ax.DHRs;
1731 t->unverified_ax->kx_0 = t->ax.kx_0;
1733 /* Set as the 'current' RK/DHRr the one we are currently using,
1734 so that the duplicate-detection logic of
1735 #update_ax_by_kx can work. */
1736 t->unverified_ax->RK = t->ax.RK;
1737 t->unverified_ax->DHRr = t->ax.DHRr;
1738 t->unverified_attempts = 0;
1739 ax = t->unverified_ax;
1741 /* Update 'ax' by the new key material */
1742 ret = update_ax_by_kx (ax,
1743 GCP_get_id (t->destination),
1744 &msg->ephemeral_key,
1746 GNUNET_break (GNUNET_SYSERR != ret);
1747 if (GNUNET_OK != ret)
1748 return; /* duplicate KX, nothing to do */
1750 /* move ahead in our state machine */
1751 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1752 GCT_change_estate (t,
1753 CADET_TUNNEL_KEY_AX_RECV);
1754 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1755 GCT_change_estate (t,
1756 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1758 /* KX is still not done, try again our end. */
1759 if (CADET_TUNNEL_KEY_OK != t->estate)
1761 if (NULL != t->kx_task)
1762 GNUNET_SCHEDULER_cancel (t->kx_task);
1764 = GNUNET_SCHEDULER_add_now (&retry_kx,
1771 * Handle KX_AUTH message.
1773 * @param ct connection/tunnel combo that received encrypted message
1774 * @param msg the key exchange message
1777 GCT_handle_kx_auth (struct CadetTConnection *ct,
1778 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1780 struct CadetTunnel *t = ct->t;
1781 struct CadetTunnelAxolotl ax_tmp;
1782 struct GNUNET_HashCode kx_auth;
1785 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1786 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1788 /* Confusing, we got a KX_AUTH before we even send our own
1789 KX. This should not happen. We'll send our own KX ASAP anyway,
1790 so let's ignore this here. */
1791 GNUNET_break_op (0);
1794 LOG (GNUNET_ERROR_TYPE_DEBUG,
1795 "Handling KX_AUTH message for %s\n",
1798 /* We do everything in ax_tmp until we've checked the authentication
1799 so we don't clobber anything we care about by accident. */
1802 /* Update 'ax' by the new key material */
1803 ret = update_ax_by_kx (&ax_tmp,
1804 GCP_get_id (t->destination),
1805 &msg->kx.ephemeral_key,
1806 &msg->kx.ratchet_key);
1807 if (GNUNET_OK != ret)
1809 if (GNUNET_NO == ret)
1810 GNUNET_STATISTICS_update (stats,
1811 "# redundant KX_AUTH received",
1815 GNUNET_break (0); /* connect to self!? */
1818 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1821 if (0 != memcmp (&kx_auth,
1825 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1826 we transmitted to the sender, refuse it, try KX again. */
1827 GNUNET_STATISTICS_update (stats,
1828 "# KX_AUTH not using our last KX received (auth failure)",
1836 /* Yep, we're good. */
1838 if (NULL != t->unverified_ax)
1840 /* We got some "stale" KX before, drop that. */
1841 cleanup_ax (t->unverified_ax);
1842 GNUNET_free (t->unverified_ax);
1843 t->unverified_ax = NULL;
1846 /* move ahead in our state machine */
1849 case CADET_TUNNEL_KEY_UNINITIALIZED:
1850 case CADET_TUNNEL_KEY_AX_RECV:
1851 /* Checked above, this is impossible. */
1854 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1855 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1856 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1857 GCT_change_estate (t,
1858 CADET_TUNNEL_KEY_OK);
1860 case CADET_TUNNEL_KEY_OK:
1861 /* Did not expect another KX_AUTH, but so what, still acceptable.
1862 Nothing to do here. */
1869 /* ************************************** end core crypto ***************************** */
1873 * Compute the next free channel tunnel number for this tunnel.
1875 * @param t the tunnel
1876 * @return unused number that can uniquely identify a channel in the tunnel
1878 static struct GNUNET_CADET_ChannelTunnelNumber
1879 get_next_free_ctn (struct CadetTunnel *t)
1881 #define HIGH_BIT 0x8000000
1882 struct GNUNET_CADET_ChannelTunnelNumber ret;
1887 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1888 GCP_get_id (GCT_get_destination (t)));
1894 GNUNET_assert (0); // loopback must never go here!
1895 ctn = ntohl (t->next_ctn.cn);
1897 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1900 ctn = ((ctn + 1) & (~ HIGH_BIT));
1902 t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
1903 ret.cn = htonl (ctn | highbit);
1909 * Add a channel to a tunnel, and notify channel that we are ready
1910 * for transmission if we are already up. Otherwise that notification
1911 * will be done later in #notify_tunnel_up_cb().
1915 * @return unique number identifying @a ch within @a t
1917 struct GNUNET_CADET_ChannelTunnelNumber
1918 GCT_add_channel (struct CadetTunnel *t,
1919 struct CadetChannel *ch)
1921 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1923 ctn = get_next_free_ctn (t);
1924 if (NULL != t->destroy_task)
1926 GNUNET_SCHEDULER_cancel (t->destroy_task);
1927 t->destroy_task = NULL;
1929 GNUNET_assert (GNUNET_YES ==
1930 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1933 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1934 LOG (GNUNET_ERROR_TYPE_DEBUG,
1935 "Adding %s to %s\n",
1940 case CADET_TUNNEL_KEY_UNINITIALIZED:
1941 /* waiting for connection to start KX */
1943 case CADET_TUNNEL_KEY_AX_RECV:
1944 case CADET_TUNNEL_KEY_AX_SENT:
1945 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1946 /* we're currently waiting for KX to complete */
1948 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1949 /* waiting for OTHER peer to send us data,
1950 we might need to prompt more aggressively! */
1951 if (NULL == t->kx_task)
1953 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1957 case CADET_TUNNEL_KEY_OK:
1958 /* We are ready. Tell the new channel that we are up. */
1959 GCCH_tunnel_up (ch);
1967 * We lost a connection, remove it from our list and clean up
1968 * the connection object itself.
1970 * @param ct binding of connection to tunnel of the connection that was lost.
1973 GCT_connection_lost (struct CadetTConnection *ct)
1975 struct CadetTunnel *t = ct->t;
1977 if (GNUNET_YES == ct->is_ready)
1979 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
1980 t->connection_ready_tail,
1982 t->num_ready_connections--;
1986 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
1987 t->connection_busy_tail,
1989 t->num_busy_connections--;
1996 * Clean up connection @a ct of a tunnel.
1998 * @param cls the `struct CadetTunnel`
1999 * @param ct connection to clean up
2002 destroy_t_connection (void *cls,
2003 struct CadetTConnection *ct)
2005 struct CadetTunnel *t = cls;
2006 struct CadetConnection *cc = ct->cc;
2008 GNUNET_assert (ct->t == t);
2009 GCT_connection_lost (ct);
2010 GCC_destroy_without_tunnel (cc);
2015 * This tunnel is no longer used, destroy it.
2017 * @param cls the idle tunnel
2020 destroy_tunnel (void *cls)
2022 struct CadetTunnel *t = cls;
2023 struct CadetTunnelQueueEntry *tq;
2025 t->destroy_task = NULL;
2026 LOG (GNUNET_ERROR_TYPE_DEBUG,
2027 "Destroying idle %s\n",
2029 GNUNET_assert (0 == GCT_count_channels (t));
2030 GCT_iterate_connections (t,
2031 &destroy_t_connection,
2033 GNUNET_assert (NULL == t->connection_ready_head);
2034 GNUNET_assert (NULL == t->connection_busy_head);
2035 while (NULL != (tq = t->tq_head))
2037 if (NULL != tq->cont)
2038 tq->cont (tq->cont_cls,
2040 GCT_send_cancel (tq);
2042 GCP_drop_tunnel (t->destination,
2044 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2045 if (NULL != t->maintain_connections_task)
2047 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2048 t->maintain_connections_task = NULL;
2050 if (NULL != t->send_task)
2052 GNUNET_SCHEDULER_cancel (t->send_task);
2053 t->send_task = NULL;
2055 if (NULL != t->kx_task)
2057 GNUNET_SCHEDULER_cancel (t->kx_task);
2060 GNUNET_MST_destroy (t->mst);
2061 GNUNET_MQ_destroy (t->mq);
2062 if (NULL != t->unverified_ax)
2064 cleanup_ax (t->unverified_ax);
2065 GNUNET_free (t->unverified_ax);
2067 cleanup_ax (&t->ax);
2068 GNUNET_assert (NULL == t->destroy_task);
2074 * Remove a channel from a tunnel.
2078 * @param ctn unique number identifying @a ch within @a t
2081 GCT_remove_channel (struct CadetTunnel *t,
2082 struct CadetChannel *ch,
2083 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2085 LOG (GNUNET_ERROR_TYPE_DEBUG,
2086 "Removing %s from %s\n",
2089 GNUNET_assert (GNUNET_YES ==
2090 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2094 GCT_count_channels (t)) &&
2095 (NULL == t->destroy_task) )
2098 = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2106 * Destroy remaining channels during shutdown.
2108 * @param cls the `struct CadetTunnel` of the channel
2109 * @param key key of the channel
2110 * @param value the `struct CadetChannel`
2111 * @return #GNUNET_OK (continue to iterate)
2114 destroy_remaining_channels (void *cls,
2118 struct CadetChannel *ch = value;
2120 GCCH_handle_remote_destroy (ch,
2127 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2129 * @param t tunnel to destroy
2132 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2134 GNUNET_assert (GNUNET_YES == shutting_down);
2135 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2136 &destroy_remaining_channels,
2139 GCT_count_channels (t));
2140 if (NULL != t->destroy_task)
2142 GNUNET_SCHEDULER_cancel (t->destroy_task);
2143 t->destroy_task = NULL;
2150 * Send normal payload from queue in @a t via connection @a ct.
2151 * Does nothing if our payload queue is empty.
2153 * @param t tunnel to send data from
2154 * @param ct connection to use for transmission (is ready)
2157 try_send_normal_payload (struct CadetTunnel *t,
2158 struct CadetTConnection *ct)
2160 struct CadetTunnelQueueEntry *tq;
2162 GNUNET_assert (GNUNET_YES == ct->is_ready);
2166 /* no messages pending right now */
2167 LOG (GNUNET_ERROR_TYPE_DEBUG,
2168 "Not sending payload of %s on ready %s (nothing pending)\n",
2173 /* ready to send message 'tq' on tunnel 'ct' */
2174 GNUNET_assert (t == tq->t);
2175 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2178 if (NULL != tq->cid)
2179 *tq->cid = *GCC_get_id (ct->cc);
2180 mark_connection_unready (ct);
2181 LOG (GNUNET_ERROR_TYPE_DEBUG,
2182 "Sending payload of %s on %s\n",
2185 GCC_transmit (ct->cc,
2187 if (NULL != tq->cont)
2188 tq->cont (tq->cont_cls,
2189 GCC_get_id (ct->cc));
2195 * A connection is @a is_ready for transmission. Looks at our message
2196 * queue and if there is a message, sends it out via the connection.
2198 * @param cls the `struct CadetTConnection` that is @a is_ready
2199 * @param is_ready #GNUNET_YES if connection are now ready,
2200 * #GNUNET_NO if connection are no longer ready
2203 connection_ready_cb (void *cls,
2206 struct CadetTConnection *ct = cls;
2207 struct CadetTunnel *t = ct->t;
2209 if (GNUNET_NO == is_ready)
2211 LOG (GNUNET_ERROR_TYPE_DEBUG,
2212 "%s no longer ready for %s\n",
2215 mark_connection_unready (ct);
2218 GNUNET_assert (GNUNET_NO == ct->is_ready);
2219 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2220 t->connection_busy_tail,
2222 GNUNET_assert (0 < t->num_busy_connections);
2223 t->num_busy_connections--;
2224 ct->is_ready = GNUNET_YES;
2225 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2226 t->connection_ready_tail,
2228 t->num_ready_connections++;
2230 LOG (GNUNET_ERROR_TYPE_DEBUG,
2231 "%s now ready for %s in state %s\n",
2234 estate2s (t->estate));
2237 case CADET_TUNNEL_KEY_UNINITIALIZED:
2238 /* Do not begin KX if WE have no channels waiting! */
2239 if (0 == GCT_count_channels (t))
2241 /* We are uninitialized, just transmit immediately,
2242 without undue delay. */
2243 if (NULL != t->kx_task)
2245 GNUNET_SCHEDULER_cancel (t->kx_task);
2252 case CADET_TUNNEL_KEY_AX_RECV:
2253 case CADET_TUNNEL_KEY_AX_SENT:
2254 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2255 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2256 /* we're currently waiting for KX to complete, schedule job */
2257 if (NULL == t->kx_task)
2259 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2263 case CADET_TUNNEL_KEY_OK:
2264 if (GNUNET_YES == t->kx_auth_requested)
2266 if (NULL != t->kx_task)
2268 GNUNET_SCHEDULER_cancel (t->kx_task);
2277 try_send_normal_payload (t,
2285 * Called when either we have a new connection, or a new message in the
2286 * queue, or some existing connection has transmission capacity. Looks
2287 * at our message queue and if there is a message, picks a connection
2290 * @param cls the `struct CadetTunnel` to process messages on
2293 trigger_transmissions (void *cls)
2295 struct CadetTunnel *t = cls;
2296 struct CadetTConnection *ct;
2298 t->send_task = NULL;
2299 if (NULL == t->tq_head)
2300 return; /* no messages pending right now */
2301 ct = get_ready_connection (t);
2303 return; /* no connections ready */
2304 try_send_normal_payload (t,
2310 * Closure for #evaluate_connection. Used to assemble summary information
2311 * about the existing connections so we can evaluate a new path.
2313 struct EvaluationSummary
2317 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2319 unsigned int min_length;
2322 * Maximum length of any of our connections, 0 if we have none.
2324 unsigned int max_length;
2327 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2329 GNUNET_CONTAINER_HeapCostType min_desire;
2332 * Maximum desirability of any of our connections, 0 if we have none.
2334 GNUNET_CONTAINER_HeapCostType max_desire;
2337 * Path we are comparing against for #evaluate_connection, can be NULL.
2339 struct CadetPeerPath *path;
2342 * Connection deemed the "worst" so far encountered by #evaluate_connection,
2343 * NULL if we did not yet encounter any connections.
2345 struct CadetTConnection *worst;
2348 * Numeric score of @e worst, only set if @e worst is non-NULL.
2353 * Set to #GNUNET_YES if we have a connection over @e path already.
2361 * Evaluate a connection, updating our summary information in @a cls about
2362 * what kinds of connections we have.
2364 * @param cls the `struct EvaluationSummary *` to update
2365 * @param ct a connection to include in the summary
2368 evaluate_connection (void *cls,
2369 struct CadetTConnection *ct)
2371 struct EvaluationSummary *es = cls;
2372 struct CadetConnection *cc = ct->cc;
2373 struct CadetPeerPath *ps = GCC_get_path (cc);
2374 const struct CadetConnectionMetrics *metrics;
2375 GNUNET_CONTAINER_HeapCostType ct_desirability;
2376 struct GNUNET_TIME_Relative uptime;
2377 struct GNUNET_TIME_Relative last_use;
2380 double success_rate;
2384 LOG (GNUNET_ERROR_TYPE_DEBUG,
2385 "Ignoring duplicate path %s.\n",
2386 GCPP_2s (es->path));
2387 es->duplicate = GNUNET_YES;
2390 ct_desirability = GCPP_get_desirability (ps);
2391 ct_length = GCPP_get_length (ps);
2392 metrics = GCC_get_metrics (cc);
2393 uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2394 last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2395 /* We add 1.0 here to avoid division by zero. */
2396 success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2399 + 100.0 / (1.0 + ct_length) /* longer paths = better */
2400 + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2401 - last_use.rel_value_us / 1000L; /* longer idle = worse */
2402 score *= success_rate; /* weigh overall by success rate */
2404 if ( (NULL == es->worst) ||
2405 (score < es->worst_score) )
2408 es->worst_score = score;
2410 es->min_length = GNUNET_MIN (es->min_length,
2412 es->max_length = GNUNET_MAX (es->max_length,
2414 es->min_desire = GNUNET_MIN (es->min_desire,
2416 es->max_desire = GNUNET_MAX (es->max_desire,
2422 * Consider using the path @a p for the tunnel @a t.
2423 * The tunnel destination is at offset @a off in path @a p.
2425 * @param cls our tunnel
2426 * @param path a path to our destination
2427 * @param off offset of the destination on path @a path
2428 * @return #GNUNET_YES (should keep iterating)
2431 consider_path_cb (void *cls,
2432 struct CadetPeerPath *path,
2435 struct CadetTunnel *t = cls;
2436 struct EvaluationSummary es;
2437 struct CadetTConnection *ct;
2439 GNUNET_assert (off < GCPP_get_length (path));
2440 es.min_length = UINT_MAX;
2443 es.min_desire = UINT64_MAX;
2445 es.duplicate = GNUNET_NO;
2448 /* Compute evaluation summary over existing connections. */
2449 GCT_iterate_connections (t,
2450 &evaluate_connection,
2452 if (GNUNET_YES == es.duplicate)
2455 /* FIXME: not sure we should really just count
2456 'num_connections' here, as they may all have
2457 consistently failed to connect. */
2459 /* We iterate by increasing path length; if we have enough paths and
2460 this one is more than twice as long than what we are currently
2461 using, then ignore all of these super-long ones! */
2462 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2463 (es.min_length * 2 < off) &&
2464 (es.max_length < off) )
2466 LOG (GNUNET_ERROR_TYPE_DEBUG,
2467 "Ignoring paths of length %u, they are way too long.\n",
2471 /* If we have enough paths and this one looks no better, ignore it. */
2472 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2473 (es.min_length < GCPP_get_length (path)) &&
2474 (es.min_desire > GCPP_get_desirability (path)) &&
2475 (es.max_length < off) )
2477 LOG (GNUNET_ERROR_TYPE_DEBUG,
2478 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2479 GCPP_get_length (path),
2480 (unsigned long long) GCPP_get_desirability (path),
2481 GCP_2s (t->destination));
2485 /* Path is interesting (better by some metric, or we don't have
2486 enough paths yet). */
2487 ct = GNUNET_new (struct CadetTConnection);
2488 ct->created = GNUNET_TIME_absolute_get ();
2490 ct->cc = GCC_create (t->destination,
2493 GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2495 &connection_ready_cb,
2498 /* FIXME: schedule job to kill connection (and path?) if it takes
2499 too long to get ready! (And track performance data on how long
2500 other connections took with the tunnel!)
2501 => Note: to be done within 'connection'-logic! */
2502 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2503 t->connection_busy_tail,
2505 t->num_busy_connections++;
2506 LOG (GNUNET_ERROR_TYPE_DEBUG,
2507 "Found interesting path %s for %s, created %s\n",
2516 * Function called to maintain the connections underlying our tunnel.
2517 * Tries to maintain (incl. tear down) connections for the tunnel, and
2518 * if there is a significant change, may trigger transmissions.
2520 * Basically, needs to check if there are connections that perform
2521 * badly, and if so eventually kill them and trigger a replacement.
2522 * The strategy is to open one more connection than
2523 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2524 * least-performing one, and then inquire for new ones.
2526 * @param cls the `struct CadetTunnel`
2529 maintain_connections_cb (void *cls)
2531 struct CadetTunnel *t = cls;
2532 struct GNUNET_TIME_Relative delay;
2533 struct EvaluationSummary es;
2535 t->maintain_connections_task = NULL;
2536 LOG (GNUNET_ERROR_TYPE_DEBUG,
2537 "Performing connection maintenance for %s.\n",
2540 es.min_length = UINT_MAX;
2543 es.min_desire = UINT64_MAX;
2546 es.duplicate = GNUNET_NO;
2547 GCT_iterate_connections (t,
2548 &evaluate_connection,
2550 if ( (NULL != es.worst) &&
2551 (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2553 /* Clear out worst-performing connection 'es.worst'. */
2554 destroy_t_connection (t,
2558 /* Consider additional paths */
2559 (void) GCP_iterate_paths (t->destination,
2563 /* FIXME: calculate when to try again based on how well we are doing;
2564 in particular, if we have to few connections, we might be able
2565 to do without this (as PATHS should tell us whenever a new path
2566 is available instantly; however, need to make sure this job is
2567 restarted after that happens).
2568 Furthermore, if the paths we do know are in a reasonably narrow
2569 quality band and are plentyful, we might also consider us stabilized
2570 and then reduce the frequency accordingly. */
2571 delay = GNUNET_TIME_UNIT_MINUTES;
2572 t->maintain_connections_task
2573 = GNUNET_SCHEDULER_add_delayed (delay,
2574 &maintain_connections_cb,
2580 * Consider using the path @a p for the tunnel @a t.
2581 * The tunnel destination is at offset @a off in path @a p.
2583 * @param cls our tunnel
2584 * @param path a path to our destination
2585 * @param off offset of the destination on path @a path
2588 GCT_consider_path (struct CadetTunnel *t,
2589 struct CadetPeerPath *p,
2592 LOG (GNUNET_ERROR_TYPE_DEBUG,
2593 "Considering %s for %s\n",
2596 (void) consider_path_cb (t,
2603 * We got a keepalive. Track in statistics.
2605 * @param cls the `struct CadetTunnel` for which we decrypted the message
2606 * @param msg the message we received on the tunnel
2609 handle_plaintext_keepalive (void *cls,
2610 const struct GNUNET_MessageHeader *msg)
2612 struct CadetTunnel *t = cls;
2614 LOG (GNUNET_ERROR_TYPE_DEBUG,
2615 "Received KEEPALIVE on %s\n",
2617 GNUNET_STATISTICS_update (stats,
2618 "# keepalives received",
2625 * Check that @a msg is well-formed.
2627 * @param cls the `struct CadetTunnel` for which we decrypted the message
2628 * @param msg the message we received on the tunnel
2629 * @return #GNUNET_OK (any variable-size payload goes)
2632 check_plaintext_data (void *cls,
2633 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2640 * We received payload data for a channel. Locate the channel
2641 * and process the data, or return an error if the channel is unknown.
2643 * @param cls the `struct CadetTunnel` for which we decrypted the message
2644 * @param msg the message we received on the tunnel
2647 handle_plaintext_data (void *cls,
2648 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2650 struct CadetTunnel *t = cls;
2651 struct CadetChannel *ch;
2653 ch = lookup_channel (t,
2657 /* We don't know about such a channel, might have been destroyed on our
2658 end in the meantime, or never existed. Send back a DESTROY. */
2659 LOG (GNUNET_ERROR_TYPE_DEBUG,
2660 "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2661 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2662 ntohl (msg->ctn.cn));
2663 GCT_send_channel_destroy (t,
2667 GCCH_handle_channel_plaintext_data (ch,
2668 GCC_get_id (t->current_ct->cc),
2674 * We received an acknowledgement for data we sent on a channel.
2675 * Locate the channel and process it, or return an error if the
2676 * channel is unknown.
2678 * @param cls the `struct CadetTunnel` for which we decrypted the message
2679 * @param ack the message we received on the tunnel
2682 handle_plaintext_data_ack (void *cls,
2683 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2685 struct CadetTunnel *t = cls;
2686 struct CadetChannel *ch;
2688 ch = lookup_channel (t,
2692 /* We don't know about such a channel, might have been destroyed on our
2693 end in the meantime, or never existed. Send back a DESTROY. */
2694 LOG (GNUNET_ERROR_TYPE_DEBUG,
2695 "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2696 ntohl (ack->ctn.cn));
2697 GCT_send_channel_destroy (t,
2701 GCCH_handle_channel_plaintext_data_ack (ch,
2702 GCC_get_id (t->current_ct->cc),
2708 * We have received a request to open a channel to a port from
2709 * another peer. Creates the incoming channel.
2711 * @param cls the `struct CadetTunnel` for which we decrypted the message
2712 * @param copen the message we received on the tunnel
2715 handle_plaintext_channel_open (void *cls,
2716 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2718 struct CadetTunnel *t = cls;
2719 struct CadetChannel *ch;
2721 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2722 ntohl (copen->ctn.cn));
2725 LOG (GNUNET_ERROR_TYPE_DEBUG,
2726 "Received duplicate channel CHANNEL_OPEN on port %s from %s (%s), resending ACK\n",
2727 GNUNET_h2s (&copen->port),
2730 GCCH_handle_duplicate_open (ch,
2731 GCC_get_id (t->current_ct->cc));
2734 LOG (GNUNET_ERROR_TYPE_DEBUG,
2735 "Received CHANNEL_OPEN on port %s from %s\n",
2736 GNUNET_h2s (&copen->port),
2738 ch = GCCH_channel_incoming_new (t,
2741 ntohl (copen->opt));
2742 if (NULL != t->destroy_task)
2744 GNUNET_SCHEDULER_cancel (t->destroy_task);
2745 t->destroy_task = NULL;
2747 GNUNET_assert (GNUNET_OK ==
2748 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2749 ntohl (copen->ctn.cn),
2751 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2756 * Send a DESTROY message via the tunnel.
2758 * @param t the tunnel to transmit over
2759 * @param ctn ID of the channel to destroy
2762 GCT_send_channel_destroy (struct CadetTunnel *t,
2763 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2765 struct GNUNET_CADET_ChannelManageMessage msg;
2767 LOG (GNUNET_ERROR_TYPE_DEBUG,
2768 "Sending DESTORY message for channel ID %u\n",
2770 msg.header.size = htons (sizeof (msg));
2771 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2772 msg.reserved = htonl (0);
2782 * We have received confirmation from the target peer that the
2783 * given channel could be established (the port is open).
2786 * @param cls the `struct CadetTunnel` for which we decrypted the message
2787 * @param cm the message we received on the tunnel
2790 handle_plaintext_channel_open_ack (void *cls,
2791 const struct GNUNET_CADET_ChannelManageMessage *cm)
2793 struct CadetTunnel *t = cls;
2794 struct CadetChannel *ch;
2796 ch = lookup_channel (t,
2800 /* We don't know about such a channel, might have been destroyed on our
2801 end in the meantime, or never existed. Send back a DESTROY. */
2802 LOG (GNUNET_ERROR_TYPE_DEBUG,
2803 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2804 ntohl (cm->ctn.cn));
2805 GCT_send_channel_destroy (t,
2809 LOG (GNUNET_ERROR_TYPE_DEBUG,
2810 "Received channel OPEN_ACK on channel %s from %s\n",
2813 GCCH_handle_channel_open_ack (ch,
2814 GCC_get_id (t->current_ct->cc));
2819 * We received a message saying that a channel should be destroyed.
2820 * Pass it on to the correct channel.
2822 * @param cls the `struct CadetTunnel` for which we decrypted the message
2823 * @param cm the message we received on the tunnel
2826 handle_plaintext_channel_destroy (void *cls,
2827 const struct GNUNET_CADET_ChannelManageMessage *cm)
2829 struct CadetTunnel *t = cls;
2830 struct CadetChannel *ch;
2832 ch = lookup_channel (t,
2836 /* We don't know about such a channel, might have been destroyed on our
2837 end in the meantime, or never existed. */
2838 LOG (GNUNET_ERROR_TYPE_DEBUG,
2839 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2840 ntohl (cm->ctn.cn));
2843 LOG (GNUNET_ERROR_TYPE_DEBUG,
2844 "Received channel DESTROY on %s from %s\n",
2847 GCCH_handle_remote_destroy (ch,
2848 GCC_get_id (t->current_ct->cc));
2853 * Handles a message we decrypted, by injecting it into
2854 * our message queue (which will do the dispatching).
2856 * @param cls the `struct CadetTunnel` that got the message
2857 * @param msg the message
2858 * @return #GNUNET_OK (continue to process)
2861 handle_decrypted (void *cls,
2862 const struct GNUNET_MessageHeader *msg)
2864 struct CadetTunnel *t = cls;
2866 GNUNET_assert (NULL != t->current_ct);
2867 GNUNET_MQ_inject_message (t->mq,
2874 * Function called if we had an error processing
2875 * an incoming decrypted message.
2877 * @param cls the `struct CadetTunnel`
2878 * @param error error code
2881 decrypted_error_cb (void *cls,
2882 enum GNUNET_MQ_Error error)
2884 GNUNET_break_op (0);
2889 * Create a tunnel to @a destionation. Must only be called
2890 * from within #GCP_get_tunnel().
2892 * @param destination where to create the tunnel to
2893 * @return new tunnel to @a destination
2895 struct CadetTunnel *
2896 GCT_create_tunnel (struct CadetPeer *destination)
2898 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2899 struct GNUNET_MQ_MessageHandler handlers[] = {
2900 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2901 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2902 struct GNUNET_MessageHeader,
2904 GNUNET_MQ_hd_var_size (plaintext_data,
2905 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2906 struct GNUNET_CADET_ChannelAppDataMessage,
2908 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2909 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2910 struct GNUNET_CADET_ChannelDataAckMessage,
2912 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2913 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2914 struct GNUNET_CADET_ChannelOpenMessage,
2916 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2917 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2918 struct GNUNET_CADET_ChannelManageMessage,
2920 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2921 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2922 struct GNUNET_CADET_ChannelManageMessage,
2924 GNUNET_MQ_handler_end ()
2927 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2928 new_ephemeral (&t->ax);
2929 GNUNET_assert (GNUNET_OK ==
2930 GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2931 t->destination = destination;
2932 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2933 t->maintain_connections_task
2934 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2936 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2941 &decrypted_error_cb,
2943 t->mst = GNUNET_MST_create (&handle_decrypted,
2950 * Add a @a connection to the @a tunnel.
2953 * @param cid connection identifer to use for the connection
2954 * @param options options for the connection
2955 * @param path path to use for the connection
2956 * @return #GNUNET_OK on success,
2957 * #GNUNET_SYSERR on failure (duplicate connection)
2960 GCT_add_inbound_connection (struct CadetTunnel *t,
2961 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2962 enum GNUNET_CADET_ChannelOption options,
2963 struct CadetPeerPath *path)
2965 struct CadetTConnection *ct;
2967 ct = GNUNET_new (struct CadetTConnection);
2968 ct->created = GNUNET_TIME_absolute_get ();
2970 ct->cc = GCC_create_inbound (t->destination,
2975 &connection_ready_cb,
2979 LOG (GNUNET_ERROR_TYPE_DEBUG,
2980 "%s refused inbound %s (duplicate)\n",
2984 return GNUNET_SYSERR;
2986 /* FIXME: schedule job to kill connection (and path?) if it takes
2987 too long to get ready! (And track performance data on how long
2988 other connections took with the tunnel!)
2989 => Note: to be done within 'connection'-logic! */
2990 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2991 t->connection_busy_tail,
2993 t->num_busy_connections++;
2994 LOG (GNUNET_ERROR_TYPE_DEBUG,
3003 * Handle encrypted message.
3005 * @param ct connection/tunnel combo that received encrypted message
3006 * @param msg the encrypted message to decrypt
3009 GCT_handle_encrypted (struct CadetTConnection *ct,
3010 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3012 struct CadetTunnel *t = ct->t;
3013 uint16_t size = ntohs (msg->header.size);
3014 char cbuf [size] GNUNET_ALIGN;
3015 ssize_t decrypted_size;
3017 LOG (GNUNET_ERROR_TYPE_DEBUG,
3018 "%s received %u bytes of encrypted data in state %d\n",
3020 (unsigned int) size,
3025 case CADET_TUNNEL_KEY_UNINITIALIZED:
3026 case CADET_TUNNEL_KEY_AX_RECV:
3027 /* We did not even SEND our KX, how can the other peer
3028 send us encrypted data? Must have been that we went
3029 down and the other peer still things we are up.
3030 Let's send it KX back. */
3031 GNUNET_STATISTICS_update (stats,
3032 "# received encrypted without any KX",
3035 if (NULL != t->kx_task)
3037 GNUNET_SCHEDULER_cancel (t->kx_task);
3044 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3045 /* We send KX, and other peer send KX to us at the same time.
3046 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3047 GNUNET_STATISTICS_update (stats,
3048 "# received encrypted without KX_AUTH",
3051 if (NULL != t->kx_task)
3053 GNUNET_SCHEDULER_cancel (t->kx_task);
3061 case CADET_TUNNEL_KEY_AX_SENT:
3062 /* We did not get the KX of the other peer, but that
3063 might have been lost. Send our KX again immediately. */
3064 GNUNET_STATISTICS_update (stats,
3065 "# received encrypted without KX",
3068 if (NULL != t->kx_task)
3070 GNUNET_SCHEDULER_cancel (t->kx_task);
3077 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3078 /* Great, first payload, we might graduate to OK! */
3079 case CADET_TUNNEL_KEY_OK:
3080 /* We are up and running, all good. */
3084 decrypted_size = -1;
3085 if (CADET_TUNNEL_KEY_OK == t->estate)
3087 /* We have well-established key material available,
3088 try that. (This is the common case.) */
3089 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3095 if ( (-1 == decrypted_size) &&
3096 (NULL != t->unverified_ax) )
3098 /* We have un-authenticated KX material available. We should try
3099 this as a back-up option, in case the sender crashed and
3101 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3105 if (-1 != decrypted_size)
3107 /* It worked! Treat this as authentication of the AX data! */
3108 cleanup_ax (&t->ax);
3109 t->ax = *t->unverified_ax;
3110 GNUNET_free (t->unverified_ax);
3111 t->unverified_ax = NULL;
3113 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3115 /* First time it worked, move tunnel into production! */
3116 GCT_change_estate (t,
3117 CADET_TUNNEL_KEY_OK);
3118 if (NULL != t->send_task)
3119 GNUNET_SCHEDULER_cancel (t->send_task);
3120 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3124 if (NULL != t->unverified_ax)
3126 /* We had unverified KX material that was useless; so increment
3127 counter and eventually move to ignore it. Note that we even do
3128 this increment if we successfully decrypted with the old KX
3129 material and thus didn't even both with the new one. This is
3130 the ideal case, as a malicious injection of bogus KX data
3131 basically only causes us to increment a counter a few times. */
3132 t->unverified_attempts++;
3133 LOG (GNUNET_ERROR_TYPE_DEBUG,
3134 "Failed to decrypt message with unverified KX data %u times\n",
3135 t->unverified_attempts);
3136 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3138 cleanup_ax (t->unverified_ax);
3139 GNUNET_free (t->unverified_ax);
3140 t->unverified_ax = NULL;
3144 if (-1 == decrypted_size)
3146 /* Decryption failed for good, complain. */
3147 LOG (GNUNET_ERROR_TYPE_WARNING,
3148 "%s failed to decrypt and validate encrypted data, retrying KX\n",
3150 GNUNET_STATISTICS_update (stats,
3151 "# unable to decrypt",
3154 if (NULL != t->kx_task)
3156 GNUNET_SCHEDULER_cancel (t->kx_task);
3164 GNUNET_STATISTICS_update (stats,
3165 "# decrypted bytes",
3169 /* The MST will ultimately call #handle_decrypted() on each message. */
3171 GNUNET_break_op (GNUNET_OK ==
3172 GNUNET_MST_from_buffer (t->mst,
3177 t->current_ct = NULL;
3182 * Sends an already built message on a tunnel, encrypting it and
3183 * choosing the best connection if not provided.
3185 * @param message Message to send. Function modifies it.
3186 * @param t Tunnel on which this message is transmitted.
3187 * @param cont Continuation to call once message is really sent.
3188 * @param cont_cls Closure for @c cont.
3189 * @return Handle to cancel message
3191 struct CadetTunnelQueueEntry *
3192 GCT_send (struct CadetTunnel *t,
3193 const struct GNUNET_MessageHeader *message,
3194 GCT_SendContinuation cont,
3197 struct CadetTunnelQueueEntry *tq;
3198 uint16_t payload_size;
3199 struct GNUNET_MQ_Envelope *env;
3200 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3202 if (CADET_TUNNEL_KEY_OK != t->estate)
3207 payload_size = ntohs (message->size);
3208 LOG (GNUNET_ERROR_TYPE_DEBUG,
3209 "Encrypting %u bytes for %s\n",
3210 (unsigned int) payload_size,
3212 env = GNUNET_MQ_msg_extra (ax_msg,
3214 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3215 t_ax_encrypt (&t->ax,
3219 GNUNET_STATISTICS_update (stats,
3220 "# encrypted bytes",
3223 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3224 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3225 /* FIXME: we should do this once, not once per message;
3226 this is a point multiplication, and DHRs does not
3227 change all the time. */
3228 GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3229 &ax_msg->ax_header.DHRs);
3230 t_h_encrypt (&t->ax,
3232 t_hmac (&ax_msg->ax_header,
3233 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3238 tq = GNUNET_malloc (sizeof (*tq));
3241 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3243 tq->cont_cls = cont_cls;
3244 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3247 if (NULL != t->send_task)
3248 GNUNET_SCHEDULER_cancel (t->send_task);
3250 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3257 * Cancel a previously sent message while it's in the queue.
3259 * ONLY can be called before the continuation given to the send
3260 * function is called. Once the continuation is called, the message is
3261 * no longer in the queue!
3263 * @param tq Handle to the queue entry to cancel.
3266 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3268 struct CadetTunnel *t = tq->t;
3270 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3273 GNUNET_MQ_discard (tq->env);
3279 * Iterate over all connections of a tunnel.
3281 * @param t Tunnel whose connections to iterate.
3282 * @param iter Iterator.
3283 * @param iter_cls Closure for @c iter.
3286 GCT_iterate_connections (struct CadetTunnel *t,
3287 GCT_ConnectionIterator iter,
3290 struct CadetTConnection *n;
3291 for (struct CadetTConnection *ct = t->connection_ready_head;
3299 for (struct CadetTConnection *ct = t->connection_busy_head;
3311 * Closure for #iterate_channels_cb.
3318 GCT_ChannelIterator iter;
3321 * Closure for @e iter.
3328 * Helper function for #GCT_iterate_channels.
3330 * @param cls the `struct ChanIterCls`
3332 * @param value a `struct CadetChannel`
3333 * @return #GNUNET_OK
3336 iterate_channels_cb (void *cls,
3340 struct ChanIterCls *ctx = cls;
3341 struct CadetChannel *ch = value;
3343 ctx->iter (ctx->iter_cls,
3350 * Iterate over all channels of a tunnel.
3352 * @param t Tunnel whose channels to iterate.
3353 * @param iter Iterator.
3354 * @param iter_cls Closure for @c iter.
3357 GCT_iterate_channels (struct CadetTunnel *t,
3358 GCT_ChannelIterator iter,
3361 struct ChanIterCls ctx;
3364 ctx.iter_cls = iter_cls;
3365 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3366 &iterate_channels_cb,
3373 * Call #GCCH_debug() on a channel.
3375 * @param cls points to the log level to use
3377 * @param value the `struct CadetChannel` to dump
3378 * @return #GNUNET_OK (continue iteration)
3381 debug_channel (void *cls,
3385 const enum GNUNET_ErrorType *level = cls;
3386 struct CadetChannel *ch = value;
3388 GCCH_debug (ch, *level);
3393 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3397 * Log all possible info about the tunnel state.
3399 * @param t Tunnel to debug.
3400 * @param level Debug level to use.
3403 GCT_debug (const struct CadetTunnel *t,
3404 enum GNUNET_ErrorType level)
3406 struct CadetTConnection *iter_c;
3409 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3411 __FILE__, __FUNCTION__, __LINE__);
3416 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3418 estate2s (t->estate),
3420 GCT_count_any_connections (t));
3423 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3427 "TTT connections:\n");
3428 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3429 GCC_debug (iter_c->cc,
3431 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3432 GCC_debug (iter_c->cc,
3436 "TTT TUNNEL END\n");
3440 /* end of gnunet-service-cadet-new_tunnels.c */