2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
27 * - connection management
28 * + properly (evaluate, kill old ones, search for new ones)
29 * + when managing connections, distinguish those that
30 * have (recently) had traffic from those that were
31 * never ready (or not recently)
34 #include "gnunet_util_lib.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet-service-cadet-new.h"
38 #include "cadet_protocol.h"
39 #include "gnunet-service-cadet-new_channel.h"
40 #include "gnunet-service-cadet-new_connection.h"
41 #include "gnunet-service-cadet-new_tunnels.h"
42 #include "gnunet-service-cadet-new_peer.h"
43 #include "gnunet-service-cadet-new_paths.h"
46 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
49 * How often do we try to decrypt payload with unverified key
50 * material? Used to limit CPU increase upon receiving bogus
53 #define MAX_UNVERIFIED_ATTEMPTS 16
56 * How long do we wait until tearing down an idle tunnel?
58 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
61 * How long do we wait initially before retransmitting the KX?
62 * TODO: replace by 2 RTT if/once we have connection-level RTT data!
64 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
67 * Maximum number of skipped keys we keep in memory per tunnel.
69 #define MAX_SKIPPED_KEYS 64
72 * Maximum number of keys (and thus ratchet steps) we are willing to
73 * skip before we decide this is either a bogus packet or a DoS-attempt.
75 #define MAX_KEY_GAP 256
79 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
81 struct CadetTunnelSkippedKey
86 struct CadetTunnelSkippedKey *next;
91 struct CadetTunnelSkippedKey *prev;
94 * When was this key stored (for timeout).
96 struct GNUNET_TIME_Absolute timestamp;
101 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
106 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
109 * Key number for a given HK.
116 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
118 struct CadetTunnelAxolotl
121 * A (double linked) list of stored message keys and associated header keys
122 * for "skipped" messages, i.e. messages that have not been
123 * received despite the reception of more recent messages, (head).
125 struct CadetTunnelSkippedKey *skipped_head;
128 * Skipped messages' keys DLL, tail.
130 struct CadetTunnelSkippedKey *skipped_tail;
133 * 32-byte root key which gets updated by DH ratchet.
135 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
138 * 32-byte header key (currently used for sending).
140 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
143 * 32-byte header key (currently used for receiving)
145 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
148 * 32-byte next header key (for sending), used once the
149 * ratchet advances. We are sure that the sender has this
150 * key as well only after @e ratchet_allowed is #GNUNET_YES.
152 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
155 * 32-byte next header key (for receiving). To be tried
156 * when decrypting with @e HKr fails and thus the sender
157 * may have advanced the ratchet.
159 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
162 * 32-byte chain keys (used for forward-secrecy) for
163 * sending messages. Updated for every message.
165 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
168 * 32-byte chain keys (used for forward-secrecy) for
169 * receiving messages. Updated for every message. If
170 * messages are skipped, the respective derived MKs
171 * (and the current @HKr) are kept in the @e skipped_head DLL.
173 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
176 * ECDH for key exchange (A0 / B0). Note that for the
177 * 'unverified_ax', this member is an alias with the main
178 * 't->ax.kx_0' value, so do not free it!
180 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
183 * ECDH Ratchet key (our private key in the current DH). Note that
184 * for the 'unverified_ax', this member is an alias with the main
185 * 't->ax.kx_0' value, so do not free it!
187 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
190 * ECDH Ratchet key (other peer's public key in the current DH).
192 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
195 * Time when the current ratchet expires and a new one is triggered
196 * (if @e ratchet_allowed is #GNUNET_YES).
198 struct GNUNET_TIME_Absolute ratchet_expiration;
201 * Number of elements in @a skipped_head <-> @a skipped_tail.
203 unsigned int skipped;
206 * Message number (reset to 0 with each new ratchet, next message to send).
211 * Message number (reset to 0 with each new ratchet, next message to recv).
216 * Previous message numbers (# of msgs sent under prev ratchet)
221 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
226 * True (#GNUNET_YES) if we have received a message from the
227 * other peer that uses the keys from our last ratchet step.
228 * This implies that we are again allowed to advance the ratchet,
229 * otherwise we have to wait until the other peer sees our current
230 * ephemeral key and advances first.
232 * #GNUNET_NO if we have advanced the ratched but lack any evidence
233 * that the other peer has noticed this.
238 * Number of messages recieved since our last ratchet advance.
240 * If this counter = 0, we cannot send a new ratchet key in the next
243 * If this counter > 0, we could (but don't have to) send a new key.
245 * Once the @e ratchet_counter is larger than
246 * #ratchet_messages (or @e ratchet_expiration time has past), and
247 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
249 unsigned int ratchet_counter;
255 * Struct used to save messages in a non-ready tunnel to send once connected.
257 struct CadetTunnelQueueEntry
260 * We are entries in a DLL
262 struct CadetTunnelQueueEntry *next;
265 * We are entries in a DLL
267 struct CadetTunnelQueueEntry *prev;
270 * Tunnel these messages belong in.
272 struct CadetTunnel *t;
275 * Continuation to call once sent (on the channel layer).
277 GNUNET_SCHEDULER_TaskCallback cont;
280 * Closure for @c cont.
285 * Envelope of message to send follows.
287 struct GNUNET_MQ_Envelope *env;
290 * Where to put the connection identifier into the payload
291 * of the message in @e env once we have it?
293 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
298 * Struct containing all information regarding a tunnel to a peer.
303 * Destination of the tunnel.
305 struct CadetPeer *destination;
308 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
309 * ephemeral key changes.
311 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
314 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
316 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
319 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
321 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
326 struct CadetTunnelAxolotl ax;
329 * Unverified Axolotl info, used only if we got a fresh KX (not a
330 * KX_AUTH) while our end of the tunnel was still up. In this case,
331 * we keep the fresh KX around but do not put it into action until
332 * we got encrypted payload that assures us of the authenticity of
335 struct CadetTunnelAxolotl *unverified_ax;
338 * Task scheduled if there are no more channels using the tunnel.
340 struct GNUNET_SCHEDULER_Task *destroy_task;
343 * Task to trim connections if too many are present.
345 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
348 * Task to send messages from queue (if possible).
350 struct GNUNET_SCHEDULER_Task *send_task;
353 * Task to trigger KX.
355 struct GNUNET_SCHEDULER_Task *kx_task;
358 * Tokenizer for decrypted messages.
360 struct GNUNET_MessageStreamTokenizer *mst;
363 * Dispatcher for decrypted messages only (do NOT use for sending!).
365 struct GNUNET_MQ_Handle *mq;
368 * DLL of ready connections that are actively used to reach the destination peer.
370 struct CadetTConnection *connection_ready_head;
373 * DLL of ready connections that are actively used to reach the destination peer.
375 struct CadetTConnection *connection_ready_tail;
378 * DLL of connections that we maintain that might be used to reach the destination peer.
380 struct CadetTConnection *connection_busy_head;
383 * DLL of connections that we maintain that might be used to reach the destination peer.
385 struct CadetTConnection *connection_busy_tail;
388 * Channels inside this tunnel. Maps
389 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
391 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
394 * Channel ID for the next created channel in this tunnel.
396 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
399 * Queued messages, to transmit once tunnel gets connected.
401 struct CadetTunnelQueueEntry *tq_head;
404 * Queued messages, to transmit once tunnel gets connected.
406 struct CadetTunnelQueueEntry *tq_tail;
409 * How long do we wait until we retry the KX?
411 struct GNUNET_TIME_Relative kx_retry_delay;
414 * When do we try the next KX?
416 struct GNUNET_TIME_Absolute next_kx_attempt;
419 * Number of connections in the @e connection_ready_head DLL.
421 unsigned int num_ready_connections;
424 * Number of connections in the @e connection_busy_head DLL.
426 unsigned int num_busy_connections;
429 * How often have we tried and failed to decrypt a message using
430 * the unverified KX material from @e unverified_ax? Used to
431 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
433 unsigned int unverified_attempts;
436 * Number of entries in the @e tq_head DLL.
441 * State of the tunnel encryption.
443 enum CadetTunnelEState estate;
446 * Force triggering KX_AUTH independent of @e estate.
448 int kx_auth_requested;
454 * Connection @a ct is now unready, clear it's ready flag
455 * and move it from the ready DLL to the busy DLL.
457 * @param ct connection to move to unready status
460 mark_connection_unready (struct CadetTConnection *ct)
462 struct CadetTunnel *t = ct->t;
464 GNUNET_assert (GNUNET_YES == ct->is_ready);
465 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
466 t->connection_ready_tail,
468 GNUNET_assert (0 < t->num_ready_connections);
469 t->num_ready_connections--;
470 ct->is_ready = GNUNET_NO;
471 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
472 t->connection_busy_tail,
474 t->num_busy_connections++;
479 * Get the static string for the peer this tunnel is directed.
483 * @return Static string the destination peer's ID.
486 GCT_2s (const struct CadetTunnel *t)
491 return "Tunnel(NULL)";
492 GNUNET_snprintf (buf,
495 GNUNET_i2s (GCP_get_id (t->destination)));
501 * Get string description for tunnel encryption state.
503 * @param es Tunnel state.
505 * @return String representation.
508 estate2s (enum CadetTunnelEState es)
514 case CADET_TUNNEL_KEY_UNINITIALIZED:
515 return "CADET_TUNNEL_KEY_UNINITIALIZED";
516 case CADET_TUNNEL_KEY_AX_RECV:
517 return "CADET_TUNNEL_KEY_AX_RECV";
518 case CADET_TUNNEL_KEY_AX_SENT:
519 return "CADET_TUNNEL_KEY_AX_SENT";
520 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
521 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
522 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
523 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
524 case CADET_TUNNEL_KEY_OK:
525 return "CADET_TUNNEL_KEY_OK";
527 GNUNET_snprintf (buf,
529 "%u (UNKNOWN STATE)",
537 * Return the peer to which this tunnel goes.
540 * @return the destination of the tunnel
543 GCT_get_destination (struct CadetTunnel *t)
545 return t->destination;
550 * Count channels of a tunnel.
552 * @param t Tunnel on which to count.
554 * @return Number of channels.
557 GCT_count_channels (struct CadetTunnel *t)
559 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
564 * Lookup a channel by its @a ctn.
566 * @param t tunnel to look in
567 * @param ctn number of channel to find
568 * @return NULL if channel does not exist
570 struct CadetChannel *
571 lookup_channel (struct CadetTunnel *t,
572 struct GNUNET_CADET_ChannelTunnelNumber ctn)
574 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
580 * Count all created connections of a tunnel. Not necessarily ready connections!
582 * @param t Tunnel on which to count.
584 * @return Number of connections created, either being established or ready.
587 GCT_count_any_connections (const struct CadetTunnel *t)
589 return t->num_ready_connections + t->num_busy_connections;
594 * Find first connection that is ready in the list of
595 * our connections. Picks ready connections round-robin.
597 * @param t tunnel to search
598 * @return NULL if we have no connection that is ready
600 static struct CadetTConnection *
601 get_ready_connection (struct CadetTunnel *t)
603 return t->connection_ready_head;
608 * Get the encryption state of a tunnel.
612 * @return Tunnel's encryption state.
614 enum CadetTunnelEState
615 GCT_get_estate (struct CadetTunnel *t)
622 * Called when either we have a new connection, or a new message in the
623 * queue, or some existing connection has transmission capacity. Looks
624 * at our message queue and if there is a message, picks a connection
627 * @param cls the `struct CadetTunnel` to process messages on
630 trigger_transmissions (void *cls);
633 /* ************************************** start core crypto ***************************** */
637 * Create a new Axolotl ephemeral (ratchet) key.
639 * @param ax key material to update
642 new_ephemeral (struct CadetTunnelAxolotl *ax)
644 GNUNET_free_non_null (ax->DHRs);
645 LOG (GNUNET_ERROR_TYPE_DEBUG,
646 "Creating new ephemeral ratchet key (DHRs)\n");
647 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
654 * @param plaintext Content to HMAC.
655 * @param size Size of @c plaintext.
656 * @param iv Initialization vector for the message.
657 * @param key Key to use.
658 * @param hmac[out] Destination to store the HMAC.
661 t_hmac (const void *plaintext,
664 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
665 struct GNUNET_ShortHashCode *hmac)
667 static const char ctx[] = "cadet authentication key";
668 struct GNUNET_CRYPTO_AuthKey auth_key;
669 struct GNUNET_HashCode hash;
671 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
677 /* Two step: GNUNET_ShortHash is only 256 bits,
678 GNUNET_HashCode is 512, so we truncate. */
679 GNUNET_CRYPTO_hmac (&auth_key,
692 * @param key Key to use.
693 * @param[out] hash Resulting HMAC.
694 * @param source Source key material (data to HMAC).
695 * @param len Length of @a source.
698 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
699 struct GNUNET_HashCode *hash,
703 static const char ctx[] = "axolotl HMAC-HASH";
704 struct GNUNET_CRYPTO_AuthKey auth_key;
706 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
710 GNUNET_CRYPTO_hmac (&auth_key,
718 * Derive a symmetric encryption key from an HMAC-HASH.
720 * @param key Key to use for the HMAC.
721 * @param[out] out Key to generate.
722 * @param source Source key material (data to HMAC).
723 * @param len Length of @a source.
726 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
727 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
731 static const char ctx[] = "axolotl derive key";
732 struct GNUNET_HashCode h;
738 GNUNET_CRYPTO_kdf (out, sizeof (*out),
746 * Encrypt data with the axolotl tunnel key.
748 * @param ax key material to use.
749 * @param dst Destination with @a size bytes for the encrypted data.
750 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
751 * @param size Size of the buffers at @a src and @a dst
754 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
759 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
760 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
763 ax->ratchet_counter++;
764 if ( (GNUNET_YES == ax->ratchet_allowed) &&
765 ( (ratchet_messages <= ax->ratchet_counter) ||
766 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
768 ax->ratchet_flag = GNUNET_YES;
770 if (GNUNET_YES == ax->ratchet_flag)
772 /* Advance ratchet */
773 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
774 struct GNUNET_HashCode dh;
775 struct GNUNET_HashCode hmac;
776 static const char ctx[] = "axolotl ratchet";
781 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
782 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
785 t_ax_hmac_hash (&ax->RK,
789 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
791 &hmac, sizeof (hmac),
799 ax->ratchet_flag = GNUNET_NO;
800 ax->ratchet_allowed = GNUNET_NO;
801 ax->ratchet_counter = 0;
802 ax->ratchet_expiration
803 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
807 t_hmac_derive_key (&ax->CKs,
811 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
816 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
821 GNUNET_assert (size == out_size);
822 t_hmac_derive_key (&ax->CKs,
830 * Decrypt data with the axolotl tunnel key.
832 * @param ax key material to use.
833 * @param dst Destination for the decrypted data, must contain @a size bytes.
834 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
835 * @param size Size of the @a src and @a dst buffers
838 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
843 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
844 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
847 t_hmac_derive_key (&ax->CKr,
851 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
855 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
856 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
861 GNUNET_assert (out_size == size);
862 t_hmac_derive_key (&ax->CKr,
870 * Encrypt header with the axolotl header key.
872 * @param ax key material to use.
873 * @param[in|out] msg Message whose header to encrypt.
876 t_h_encrypt (struct CadetTunnelAxolotl *ax,
877 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
879 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
882 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
886 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
887 sizeof (struct GNUNET_CADET_AxHeader),
891 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
896 * Decrypt header with the current axolotl header key.
898 * @param ax key material to use.
899 * @param src Message whose header to decrypt.
900 * @param dst Where to decrypt header to.
903 t_h_decrypt (struct CadetTunnelAxolotl *ax,
904 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
905 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
907 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
910 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
914 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
915 sizeof (struct GNUNET_CADET_AxHeader),
919 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
924 * Delete a key from the list of skipped keys.
926 * @param ax key material to delete @a key from.
927 * @param key Key to delete.
930 delete_skipped_key (struct CadetTunnelAxolotl *ax,
931 struct CadetTunnelSkippedKey *key)
933 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
942 * Decrypt and verify data with the appropriate tunnel key and verify that the
943 * data has not been altered since it was sent by the remote peer.
945 * @param ax key material to use.
946 * @param dst Destination for the plaintext.
947 * @param src Source of the message. Can overlap with @c dst.
948 * @param size Size of the message.
949 * @return Size of the decrypted data, -1 if an error was encountered.
952 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
954 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
957 struct CadetTunnelSkippedKey *key;
958 struct GNUNET_ShortHashCode *hmac;
959 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
960 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
961 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
967 LOG (GNUNET_ERROR_TYPE_DEBUG,
968 "Trying skipped keys\n");
969 hmac = &plaintext_header.hmac;
970 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
972 /* Find a correct Header Key */
974 for (key = ax->skipped_head; NULL != key; key = key->next)
976 t_hmac (&src->ax_header,
977 sizeof (struct GNUNET_CADET_AxHeader) + esize,
981 if (0 == memcmp (hmac,
992 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
993 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
994 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
995 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
998 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1002 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1003 sizeof (struct GNUNET_CADET_AxHeader),
1006 &plaintext_header.ax_header.Ns);
1007 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1009 /* Find the correct message key */
1010 N = ntohl (plaintext_header.ax_header.Ns);
1011 while ( (NULL != key) &&
1014 if ( (NULL == key) ||
1015 (0 != memcmp (&key->HK,
1017 sizeof (*valid_HK))) )
1020 /* Decrypt payload */
1021 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1026 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1031 delete_skipped_key (ax,
1038 * Delete a key from the list of skipped keys.
1040 * @param ax key material to delete from.
1041 * @param HKr Header Key to use.
1044 store_skipped_key (struct CadetTunnelAxolotl *ax,
1045 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1047 struct CadetTunnelSkippedKey *key;
1049 key = GNUNET_new (struct CadetTunnelSkippedKey);
1050 key->timestamp = GNUNET_TIME_absolute_get ();
1053 t_hmac_derive_key (&ax->CKr,
1057 t_hmac_derive_key (&ax->CKr,
1061 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1070 * Stage skipped AX keys and calculate the message key.
1071 * Stores each HK and MK for skipped messages.
1073 * @param ax key material to use
1074 * @param HKr Header key.
1075 * @param Np Received meesage number.
1076 * @return #GNUNET_OK if keys were stored.
1077 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1080 store_ax_keys (struct CadetTunnelAxolotl *ax,
1081 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1087 LOG (GNUNET_ERROR_TYPE_DEBUG,
1088 "Storing skipped keys [%u, %u)\n",
1091 if (MAX_KEY_GAP < gap)
1093 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1094 /* TODO: start new key exchange on return */
1095 GNUNET_break_op (0);
1096 LOG (GNUNET_ERROR_TYPE_WARNING,
1097 "Got message %u, expected %u+\n",
1100 return GNUNET_SYSERR;
1104 /* Delayed message: don't store keys, flag to try old keys. */
1105 return GNUNET_SYSERR;
1109 store_skipped_key (ax,
1112 while (ax->skipped > MAX_SKIPPED_KEYS)
1113 delete_skipped_key (ax,
1120 * Decrypt and verify data with the appropriate tunnel key and verify that the
1121 * data has not been altered since it was sent by the remote peer.
1123 * @param ax key material to use
1124 * @param dst Destination for the plaintext.
1125 * @param src Source of the message. Can overlap with @c dst.
1126 * @param size Size of the message.
1127 * @return Size of the decrypted data, -1 if an error was encountered.
1130 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1132 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1135 struct GNUNET_ShortHashCode msg_hmac;
1136 struct GNUNET_HashCode hmac;
1137 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1140 size_t esize; /* Size of encryped payload */
1142 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1144 /* Try current HK */
1145 t_hmac (&src->ax_header,
1146 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1149 if (0 != memcmp (&msg_hmac,
1153 static const char ctx[] = "axolotl ratchet";
1154 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1155 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1156 struct GNUNET_HashCode dh;
1157 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1160 t_hmac (&src->ax_header,
1161 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1165 if (0 != memcmp (&msg_hmac,
1169 /* Try the skipped keys, if that fails, we're out of luck. */
1170 return try_old_ax_keys (ax,
1180 Np = ntohl (plaintext_header.ax_header.Ns);
1181 PNp = ntohl (plaintext_header.ax_header.PNs);
1182 DHRp = &plaintext_header.ax_header.DHRs;
1187 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1188 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1191 t_ax_hmac_hash (&ax->RK,
1194 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1196 &hmac, sizeof (hmac),
1199 /* Commit "purported" keys */
1205 ax->ratchet_allowed = GNUNET_YES;
1212 Np = ntohl (plaintext_header.ax_header.Ns);
1213 PNp = ntohl (plaintext_header.ax_header.PNs);
1215 if ( (Np != ax->Nr) &&
1216 (GNUNET_OK != store_ax_keys (ax,
1220 /* Try the skipped keys, if that fails, we're out of luck. */
1221 return try_old_ax_keys (ax,
1237 * Our tunnel became ready for the first time, notify channels
1238 * that have been waiting.
1240 * @param cls our tunnel, not used
1241 * @param key unique ID of the channel, not used
1242 * @param value the `struct CadetChannel` to notify
1243 * @return #GNUNET_OK (continue to iterate)
1246 notify_tunnel_up_cb (void *cls,
1250 struct CadetChannel *ch = value;
1252 GCCH_tunnel_up (ch);
1258 * Change the tunnel encryption state.
1259 * If the encryption state changes to OK, stop the rekey task.
1261 * @param t Tunnel whose encryption state to change, or NULL.
1262 * @param state New encryption state.
1265 GCT_change_estate (struct CadetTunnel *t,
1266 enum CadetTunnelEState state)
1268 enum CadetTunnelEState old = t->estate;
1271 LOG (GNUNET_ERROR_TYPE_DEBUG,
1272 "%s estate changed from %s to %s\n",
1277 if ( (CADET_TUNNEL_KEY_OK != old) &&
1278 (CADET_TUNNEL_KEY_OK == t->estate) )
1280 if (NULL != t->kx_task)
1282 GNUNET_SCHEDULER_cancel (t->kx_task);
1285 /* notify all channels that have been waiting */
1286 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1287 ¬ify_tunnel_up_cb,
1289 if (NULL != t->send_task)
1290 GNUNET_SCHEDULER_cancel (t->send_task);
1291 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1298 * Send a KX message.
1300 * @param t tunnel on which to send the KX_AUTH
1301 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1302 * we are to find one that is ready.
1303 * @param ax axolotl key context to use
1306 send_kx (struct CadetTunnel *t,
1307 struct CadetTConnection *ct,
1308 struct CadetTunnelAxolotl *ax)
1310 struct CadetConnection *cc;
1311 struct GNUNET_MQ_Envelope *env;
1312 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1313 enum GNUNET_CADET_KX_Flags flags;
1316 ct = get_ready_connection (t);
1319 LOG (GNUNET_ERROR_TYPE_DEBUG,
1320 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1322 estate2s (t->estate));
1323 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1327 LOG (GNUNET_ERROR_TYPE_DEBUG,
1328 "Sending KX on %s via %s using %s in state %s\n",
1331 estate2s (t->estate));
1332 env = GNUNET_MQ_msg (msg,
1333 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1334 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1335 msg->flags = htonl (flags);
1336 msg->cid = *GCC_get_id (cc);
1337 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1338 &msg->ephemeral_key);
1339 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1341 mark_connection_unready (ct);
1342 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1343 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1344 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1345 GCT_change_estate (t,
1346 CADET_TUNNEL_KEY_AX_SENT);
1347 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1348 GCT_change_estate (t,
1349 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1356 * Send a KX_AUTH message.
1358 * @param t tunnel on which to send the KX_AUTH
1359 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1360 * we are to find one that is ready.
1361 * @param ax axolotl key context to use
1362 * @param force_reply Force the other peer to reply with a KX_AUTH message
1363 * (set if we would like to transmit right now, but cannot)
1366 send_kx_auth (struct CadetTunnel *t,
1367 struct CadetTConnection *ct,
1368 struct CadetTunnelAxolotl *ax,
1371 struct CadetConnection *cc;
1372 struct GNUNET_MQ_Envelope *env;
1373 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1374 enum GNUNET_CADET_KX_Flags flags;
1376 if ( (NULL == ct) ||
1377 (GNUNET_NO == ct->is_ready) )
1378 ct = get_ready_connection (t);
1381 LOG (GNUNET_ERROR_TYPE_DEBUG,
1382 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1384 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1385 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1388 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1390 LOG (GNUNET_ERROR_TYPE_DEBUG,
1391 "Sending KX_AUTH on %s using %s\n",
1395 env = GNUNET_MQ_msg (msg,
1396 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1397 flags = GNUNET_CADET_KX_FLAG_NONE;
1398 if (GNUNET_YES == force_reply)
1399 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1400 msg->kx.flags = htonl (flags);
1401 msg->kx.cid = *GCC_get_id (cc);
1402 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1403 &msg->kx.ephemeral_key);
1404 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1405 &msg->kx.ratchet_key);
1406 /* Compute authenticator (this is the main difference to #send_kx()) */
1407 GNUNET_CRYPTO_hash (&ax->RK,
1411 /* Compute when to be triggered again; actual job will
1412 be scheduled via #connection_ready_cb() */
1414 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1416 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1418 /* Send via cc, mark it as unready */
1419 mark_connection_unready (ct);
1421 /* Update state machine, unless we are already OK */
1422 if (CADET_TUNNEL_KEY_OK != t->estate)
1423 GCT_change_estate (t,
1424 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1432 * Cleanup state used by @a ax.
1434 * @param ax state to free, but not memory of @a ax itself
1437 cleanup_ax (struct CadetTunnelAxolotl *ax)
1439 while (NULL != ax->skipped_head)
1440 delete_skipped_key (ax,
1442 GNUNET_assert (0 == ax->skipped);
1443 GNUNET_free_non_null (ax->kx_0);
1444 GNUNET_free_non_null (ax->DHRs);
1449 * Update our Axolotl key state based on the KX data we received.
1450 * Computes the new chain keys, and root keys, etc, and also checks
1451 * wether this is a replay of the current chain.
1453 * @param[in|out] axolotl chain key state to recompute
1454 * @param pid peer identity of the other peer
1455 * @param ephemeral_key ephemeral public key of the other peer
1456 * @param ratchet_key senders next ephemeral public key
1457 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1458 * root key is already in @a ax and thus the KX is useless;
1459 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1462 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1463 const struct GNUNET_PeerIdentity *pid,
1464 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1465 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1467 struct GNUNET_HashCode key_material[3];
1468 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1469 const char salt[] = "CADET Axolotl salt";
1472 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1474 am_I_alice = GNUNET_YES;
1475 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1477 am_I_alice = GNUNET_NO;
1480 GNUNET_break_op (0);
1481 return GNUNET_SYSERR;
1484 if (0 == memcmp (&ax->DHRr,
1486 sizeof (*ratchet_key)))
1488 LOG (GNUNET_ERROR_TYPE_DEBUG,
1489 "Ratchet key already known. Ignoring KX.\n");
1493 ax->DHRr = *ratchet_key;
1496 if (GNUNET_YES == am_I_alice)
1498 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1499 ephemeral_key, /* B0 */
1504 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1505 &pid->public_key, /* A */
1510 if (GNUNET_YES == am_I_alice)
1512 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1513 &pid->public_key, /* B */
1518 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1519 ephemeral_key, /* B0 */
1526 /* (This is the triple-DH, we could probably safely skip this,
1527 as A0/B0 are already in the key material.) */
1528 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1529 ephemeral_key, /* B0 or A0 */
1533 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1534 salt, sizeof (salt),
1535 &key_material, sizeof (key_material),
1538 if (0 == memcmp (&ax->RK,
1542 LOG (GNUNET_ERROR_TYPE_DEBUG,
1543 "Root key of handshake already known. Ignoring KX.\n");
1548 if (GNUNET_YES == am_I_alice)
1554 ax->ratchet_flag = GNUNET_YES;
1562 ax->ratchet_flag = GNUNET_NO;
1563 ax->ratchet_expiration
1564 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1572 * Try to redo the KX or KX_AUTH handshake, if we can.
1574 * @param cls the `struct CadetTunnel` to do KX for.
1577 retry_kx (void *cls)
1579 struct CadetTunnel *t = cls;
1580 struct CadetTunnelAxolotl *ax;
1583 LOG (GNUNET_ERROR_TYPE_DEBUG,
1584 "Trying to make KX progress on %s in state %s\n",
1586 estate2s (t->estate));
1589 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1590 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1595 case CADET_TUNNEL_KEY_AX_RECV:
1596 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1597 /* We are responding, so only require reply
1598 if WE have a channel waiting. */
1599 if (NULL != t->unverified_ax)
1601 /* Send AX_AUTH so we might get this one verified */
1602 ax = t->unverified_ax;
1606 /* How can this be? */
1613 (0 == GCT_count_channels (t))
1617 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1618 /* We are responding, so only require reply
1619 if WE have a channel waiting. */
1620 if (NULL != t->unverified_ax)
1622 /* Send AX_AUTH so we might get this one verified */
1623 ax = t->unverified_ax;
1627 /* How can this be? */
1634 (0 == GCT_count_channels (t))
1638 case CADET_TUNNEL_KEY_OK:
1639 /* Must have been the *other* peer asking us to
1640 respond with a KX_AUTH. */
1641 if (NULL != t->unverified_ax)
1643 /* Sending AX_AUTH in response to AX so we might get this one verified */
1644 ax = t->unverified_ax;
1648 /* Sending AX_AUTH in response to AX_AUTH */
1661 * Handle KX message that lacks authentication (and which will thus
1662 * only be considered authenticated after we respond with our own
1663 * KX_AUTH and finally successfully decrypt payload).
1665 * @param ct connection/tunnel combo that received encrypted message
1666 * @param msg the key exchange message
1669 GCT_handle_kx (struct CadetTConnection *ct,
1670 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1672 struct CadetTunnel *t = ct->t;
1673 struct CadetTunnelAxolotl *ax;
1677 memcmp (&t->ax.DHRr,
1679 sizeof (msg->ratchet_key)))
1681 LOG (GNUNET_ERROR_TYPE_DEBUG,
1682 "Got duplicate KX. Firing back KX_AUTH.\n");
1690 /* We only keep ONE unverified KX around, so if there is an existing one,
1692 if (NULL != t->unverified_ax)
1695 memcmp (&t->unverified_ax->DHRr,
1697 sizeof (msg->ratchet_key)))
1699 LOG (GNUNET_ERROR_TYPE_DEBUG,
1700 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1708 LOG (GNUNET_ERROR_TYPE_DEBUG,
1709 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1711 memset (t->unverified_ax,
1713 sizeof (struct CadetTunnelAxolotl));
1714 t->unverified_ax->DHRs = t->ax.DHRs;
1715 t->unverified_ax->kx_0 = t->ax.kx_0;
1719 LOG (GNUNET_ERROR_TYPE_DEBUG,
1720 "Creating fresh unverified KX for %s.\n",
1722 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1723 t->unverified_ax->DHRs = t->ax.DHRs;
1724 t->unverified_ax->kx_0 = t->ax.kx_0;
1726 /* Set as the 'current' RK/DHRr the one we are currently using,
1727 so that the duplicate-detection logic of
1728 #update_ax_by_kx can work. */
1729 t->unverified_ax->RK = t->ax.RK;
1730 t->unverified_ax->DHRr = t->ax.DHRr;
1731 t->unverified_attempts = 0;
1732 ax = t->unverified_ax;
1734 /* Update 'ax' by the new key material */
1735 ret = update_ax_by_kx (ax,
1736 GCP_get_id (t->destination),
1737 &msg->ephemeral_key,
1739 GNUNET_break (GNUNET_SYSERR != ret);
1740 if (GNUNET_OK != ret)
1741 return; /* duplicate KX, nothing to do */
1743 /* move ahead in our state machine */
1744 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1745 GCT_change_estate (t,
1746 CADET_TUNNEL_KEY_AX_RECV);
1747 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1748 GCT_change_estate (t,
1749 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1751 /* KX is still not done, try again our end. */
1752 if (CADET_TUNNEL_KEY_OK != t->estate)
1754 if (NULL != t->kx_task)
1755 GNUNET_SCHEDULER_cancel (t->kx_task);
1757 = GNUNET_SCHEDULER_add_now (&retry_kx,
1764 * Handle KX_AUTH message.
1766 * @param ct connection/tunnel combo that received encrypted message
1767 * @param msg the key exchange message
1770 GCT_handle_kx_auth (struct CadetTConnection *ct,
1771 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1773 struct CadetTunnel *t = ct->t;
1774 struct CadetTunnelAxolotl ax_tmp;
1775 struct GNUNET_HashCode kx_auth;
1778 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1779 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1781 /* Confusing, we got a KX_AUTH before we even send our own
1782 KX. This should not happen. We'll send our own KX ASAP anyway,
1783 so let's ignore this here. */
1784 GNUNET_break_op (0);
1787 LOG (GNUNET_ERROR_TYPE_DEBUG,
1788 "Handling KX_AUTH message for %s\n",
1791 /* We do everything in ax_tmp until we've checked the authentication
1792 so we don't clobber anything we care about by accident. */
1795 /* Update 'ax' by the new key material */
1796 ret = update_ax_by_kx (&ax_tmp,
1797 GCP_get_id (t->destination),
1798 &msg->kx.ephemeral_key,
1799 &msg->kx.ratchet_key);
1800 GNUNET_break (GNUNET_OK == ret);
1801 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1804 if (0 != memcmp (&kx_auth,
1808 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1809 we transmitted to the sender, refuse it! */
1810 GNUNET_break_op (0);
1813 /* Yep, we're good. */
1815 if (NULL != t->unverified_ax)
1817 /* We got some "stale" KX before, drop that. */
1818 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1819 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1820 cleanup_ax (t->unverified_ax);
1821 GNUNET_free (t->unverified_ax);
1822 t->unverified_ax = NULL;
1825 /* move ahead in our state machine */
1828 case CADET_TUNNEL_KEY_UNINITIALIZED:
1829 case CADET_TUNNEL_KEY_AX_RECV:
1830 /* Checked above, this is impossible. */
1833 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1834 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1835 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1836 GCT_change_estate (t,
1837 CADET_TUNNEL_KEY_OK);
1839 case CADET_TUNNEL_KEY_OK:
1840 /* Did not expect another KX_AUTH, but so what, still acceptable.
1841 Nothing to do here. */
1848 /* ************************************** end core crypto ***************************** */
1852 * Compute the next free channel tunnel number for this tunnel.
1854 * @param t the tunnel
1855 * @return unused number that can uniquely identify a channel in the tunnel
1857 static struct GNUNET_CADET_ChannelTunnelNumber
1858 get_next_free_ctn (struct CadetTunnel *t)
1860 #define HIGH_BIT 0x8000000
1861 struct GNUNET_CADET_ChannelTunnelNumber ret;
1866 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1867 GCP_get_id (GCT_get_destination (t)));
1873 GNUNET_assert (0); // loopback must never go here!
1874 ctn = ntohl (t->next_ctn.cn);
1876 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1879 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1881 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1882 ret.cn = ntohl (ctn);
1888 * Add a channel to a tunnel, and notify channel that we are ready
1889 * for transmission if we are already up. Otherwise that notification
1890 * will be done later in #notify_tunnel_up_cb().
1894 * @return unique number identifying @a ch within @a t
1896 struct GNUNET_CADET_ChannelTunnelNumber
1897 GCT_add_channel (struct CadetTunnel *t,
1898 struct CadetChannel *ch)
1900 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1902 ctn = get_next_free_ctn (t);
1903 GNUNET_assert (GNUNET_YES ==
1904 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1907 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1908 LOG (GNUNET_ERROR_TYPE_DEBUG,
1909 "Adding %s to %s\n",
1914 case CADET_TUNNEL_KEY_UNINITIALIZED:
1915 /* waiting for connection to start KX */
1917 case CADET_TUNNEL_KEY_AX_RECV:
1918 case CADET_TUNNEL_KEY_AX_SENT:
1919 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1920 /* we're currently waiting for KX to complete */
1922 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1923 /* waiting for OTHER peer to send us data,
1924 we might need to prompt more aggressively! */
1925 if (NULL == t->kx_task)
1927 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1931 case CADET_TUNNEL_KEY_OK:
1932 /* We are ready. Tell the new channel that we are up. */
1933 GCCH_tunnel_up (ch);
1941 * We lost a connection, remove it from our list and clean up
1942 * the connection object itself.
1944 * @param ct binding of connection to tunnel of the connection that was lost.
1947 GCT_connection_lost (struct CadetTConnection *ct)
1949 struct CadetTunnel *t = ct->t;
1951 if (GNUNET_YES == ct->is_ready)
1952 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
1953 t->connection_ready_tail,
1956 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
1957 t->connection_busy_tail,
1964 * This tunnel is no longer used, destroy it.
1966 * @param cls the idle tunnel
1969 destroy_tunnel (void *cls)
1971 struct CadetTunnel *t = cls;
1972 struct CadetTConnection *ct;
1973 struct CadetTunnelQueueEntry *tq;
1975 t->destroy_task = NULL;
1976 LOG (GNUNET_ERROR_TYPE_DEBUG,
1977 "Destroying idle %s\n",
1979 GNUNET_assert (0 == GCT_count_channels (t));
1980 while (NULL != (ct = t->connection_ready_head))
1982 struct CadetConnection *cc;
1984 GNUNET_assert (ct->t == t);
1986 GCT_connection_lost (ct);
1987 GCC_destroy_without_tunnel (cc);
1989 while (NULL != (ct = t->connection_busy_head))
1991 struct CadetConnection *cc;
1993 GNUNET_assert (ct->t == t);
1995 GCT_connection_lost (ct);
1996 GCC_destroy_without_tunnel (cc);
1998 while (NULL != (tq = t->tq_head))
2000 if (NULL != tq->cont)
2001 tq->cont (tq->cont_cls);
2002 GCT_send_cancel (tq);
2004 GCP_drop_tunnel (t->destination,
2006 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2007 if (NULL != t->maintain_connections_task)
2009 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2010 t->maintain_connections_task = NULL;
2012 if (NULL != t->send_task)
2014 GNUNET_SCHEDULER_cancel (t->send_task);
2015 t->send_task = NULL;
2017 if (NULL != t->kx_task)
2019 GNUNET_SCHEDULER_cancel (t->kx_task);
2022 GNUNET_MST_destroy (t->mst);
2023 GNUNET_MQ_destroy (t->mq);
2024 if (NULL != t->unverified_ax)
2026 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
2027 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
2028 cleanup_ax (t->unverified_ax);
2029 GNUNET_free (t->unverified_ax);
2031 cleanup_ax (&t->ax);
2037 * Remove a channel from a tunnel.
2041 * @param ctn unique number identifying @a ch within @a t
2044 GCT_remove_channel (struct CadetTunnel *t,
2045 struct CadetChannel *ch,
2046 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2048 LOG (GNUNET_ERROR_TYPE_DEBUG,
2049 "Removing %s from %s\n",
2052 GNUNET_assert (GNUNET_YES ==
2053 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2057 GCT_count_channels (t))
2059 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2067 * Destroy remaining channels during shutdown.
2069 * @param cls the `struct CadetTunnel` of the channel
2070 * @param key key of the channel
2071 * @param value the `struct CadetChannel`
2072 * @return #GNUNET_OK (continue to iterate)
2075 destroy_remaining_channels (void *cls,
2079 struct CadetChannel *ch = value;
2081 GCCH_handle_remote_destroy (ch);
2087 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2089 * @param t tunnel to destroy
2092 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2094 GNUNET_assert (GNUNET_YES == shutting_down);
2095 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2096 &destroy_remaining_channels,
2099 GCT_count_channels (t));
2100 if (NULL != t->destroy_task)
2102 GNUNET_SCHEDULER_cancel (t->destroy_task);
2103 t->destroy_task = NULL;
2110 * Send normal payload from queue in @a t via connection @a ct.
2111 * Does nothing if our payload queue is empty.
2113 * @param t tunnel to send data from
2114 * @param ct connection to use for transmission (is ready)
2117 try_send_normal_payload (struct CadetTunnel *t,
2118 struct CadetTConnection *ct)
2120 struct CadetTunnelQueueEntry *tq;
2122 GNUNET_assert (GNUNET_YES == ct->is_ready);
2126 /* no messages pending right now */
2127 LOG (GNUNET_ERROR_TYPE_DEBUG,
2128 "Not sending payload of %s on ready %s (nothing pending)\n",
2133 /* ready to send message 'tq' on tunnel 'ct' */
2134 GNUNET_assert (t == tq->t);
2135 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2138 if (NULL != tq->cid)
2139 *tq->cid = *GCC_get_id (ct->cc);
2140 mark_connection_unready (ct);
2141 LOG (GNUNET_ERROR_TYPE_DEBUG,
2142 "Sending payload of %s on %s\n",
2145 GCC_transmit (ct->cc,
2147 if (NULL != tq->cont)
2148 tq->cont (tq->cont_cls);
2154 * A connection is @a is_ready for transmission. Looks at our message
2155 * queue and if there is a message, sends it out via the connection.
2157 * @param cls the `struct CadetTConnection` that is @a is_ready
2158 * @param is_ready #GNUNET_YES if connection are now ready,
2159 * #GNUNET_NO if connection are no longer ready
2162 connection_ready_cb (void *cls,
2165 struct CadetTConnection *ct = cls;
2166 struct CadetTunnel *t = ct->t;
2168 if (GNUNET_NO == is_ready)
2170 LOG (GNUNET_ERROR_TYPE_DEBUG,
2171 "%s no longer ready for %s\n",
2174 mark_connection_unready (ct);
2177 GNUNET_assert (GNUNET_NO == ct->is_ready);
2178 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2179 t->connection_busy_tail,
2181 GNUNET_assert (0 < t->num_busy_connections);
2182 t->num_busy_connections--;
2183 ct->is_ready = GNUNET_YES;
2184 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2185 t->connection_ready_tail,
2187 t->num_ready_connections++;
2189 LOG (GNUNET_ERROR_TYPE_DEBUG,
2190 "%s now ready for %s in state %s\n",
2193 estate2s (t->estate));
2196 case CADET_TUNNEL_KEY_UNINITIALIZED:
2197 /* Do not begin KX if WE have no channels waiting! */
2198 if (0 == GCT_count_channels (t))
2200 /* We are uninitialized, just transmit immediately,
2201 without undue delay. */
2202 if (NULL != t->kx_task)
2204 GNUNET_SCHEDULER_cancel (t->kx_task);
2211 case CADET_TUNNEL_KEY_AX_RECV:
2212 case CADET_TUNNEL_KEY_AX_SENT:
2213 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2214 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2215 /* we're currently waiting for KX to complete, schedule job */
2216 if (NULL == t->kx_task)
2218 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2222 case CADET_TUNNEL_KEY_OK:
2223 if (GNUNET_YES == t->kx_auth_requested)
2225 if (NULL != t->kx_task)
2227 GNUNET_SCHEDULER_cancel (t->kx_task);
2236 try_send_normal_payload (t,
2244 * Called when either we have a new connection, or a new message in the
2245 * queue, or some existing connection has transmission capacity. Looks
2246 * at our message queue and if there is a message, picks a connection
2249 * @param cls the `struct CadetTunnel` to process messages on
2252 trigger_transmissions (void *cls)
2254 struct CadetTunnel *t = cls;
2255 struct CadetTConnection *ct;
2257 t->send_task = NULL;
2258 if (NULL == t->tq_head)
2259 return; /* no messages pending right now */
2260 ct = get_ready_connection (t);
2262 return; /* no connections ready */
2263 try_send_normal_payload (t,
2269 * Closure for #evaluate_connection. Used to assemble summary information
2270 * about the existing connections so we can evaluate a new path.
2272 struct EvaluationSummary
2276 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2278 unsigned int min_length;
2281 * Maximum length of any of our connections, 0 if we have none.
2283 unsigned int max_length;
2286 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2288 GNUNET_CONTAINER_HeapCostType min_desire;
2291 * Maximum desirability of any of our connections, 0 if we have none.
2293 GNUNET_CONTAINER_HeapCostType max_desire;
2296 * Path we are comparing against.
2298 struct CadetPeerPath *path;
2301 * Set to #GNUNET_YES if we have a connection over @e path already.
2309 * Evaluate a connection, updating our summary information in @a cls about
2310 * what kinds of connections we have.
2312 * @param cls the `struct EvaluationSummary *` to update
2313 * @param cc a connection to include in the summary
2316 evaluate_connection (void *cls,
2317 struct CadetConnection *cc)
2319 struct EvaluationSummary *es = cls;
2320 struct CadetPeerPath *ps = GCC_get_path (cc);
2324 LOG (GNUNET_ERROR_TYPE_DEBUG,
2325 "Ignoring duplicate path %s.\n",
2326 GCPP_2s (es->path));
2327 es->duplicate = GNUNET_YES;
2330 es->min_length = GNUNET_MIN (es->min_length,
2331 GCPP_get_length (ps));
2332 es->max_length = GNUNET_MAX (es->max_length,
2333 GCPP_get_length (ps));
2334 es->min_desire = GNUNET_MIN (es->min_desire,
2335 GCPP_get_desirability (ps));
2336 es->max_desire = GNUNET_MAX (es->max_desire,
2337 GCPP_get_desirability (ps));
2342 * Consider using the path @a p for the tunnel @a t.
2343 * The tunnel destination is at offset @a off in path @a p.
2345 * @param cls our tunnel
2346 * @param path a path to our destination
2347 * @param off offset of the destination on path @a path
2348 * @return #GNUNET_YES (should keep iterating)
2351 consider_path_cb (void *cls,
2352 struct CadetPeerPath *path,
2355 struct CadetTunnel *t = cls;
2356 struct EvaluationSummary es;
2357 struct CadetTConnection *ct;
2359 es.min_length = UINT_MAX;
2362 es.min_desire = UINT64_MAX;
2364 es.duplicate = GNUNET_NO;
2366 /* Compute evaluation summary over existing connections. */
2367 GCT_iterate_connections (t,
2368 &evaluate_connection,
2370 if (GNUNET_YES == es.duplicate)
2373 /* FIXME: not sure we should really just count
2374 'num_connections' here, as they may all have
2375 consistently failed to connect. */
2377 /* We iterate by increasing path length; if we have enough paths and
2378 this one is more than twice as long than what we are currently
2379 using, then ignore all of these super-long ones! */
2380 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2381 (es.min_length * 2 < off) )
2383 LOG (GNUNET_ERROR_TYPE_DEBUG,
2384 "Ignoring paths of length %u, they are way too long.\n",
2388 /* If we have enough paths and this one looks no better, ignore it. */
2389 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2390 (es.min_length < GCPP_get_length (path)) &&
2391 (es.max_desire > GCPP_get_desirability (path)) )
2393 LOG (GNUNET_ERROR_TYPE_DEBUG,
2394 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2395 GCPP_get_length (path),
2396 (unsigned long long) GCPP_get_desirability (path),
2397 GCP_2s (t->destination));
2401 /* Path is interesting (better by some metric, or we don't have
2402 enough paths yet). */
2403 ct = GNUNET_new (struct CadetTConnection);
2404 ct->created = GNUNET_TIME_absolute_get ();
2406 ct->cc = GCC_create (t->destination,
2409 &connection_ready_cb,
2411 /* FIXME: schedule job to kill connection (and path?) if it takes
2412 too long to get ready! (And track performance data on how long
2413 other connections took with the tunnel!)
2414 => Note: to be done within 'connection'-logic! */
2415 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2416 t->connection_busy_tail,
2418 t->num_busy_connections++;
2419 LOG (GNUNET_ERROR_TYPE_DEBUG,
2420 "Found interesting path %s for %s, created %s\n",
2429 * Function called to maintain the connections underlying our tunnel.
2430 * Tries to maintain (incl. tear down) connections for the tunnel, and
2431 * if there is a significant change, may trigger transmissions.
2433 * Basically, needs to check if there are connections that perform
2434 * badly, and if so eventually kill them and trigger a replacement.
2435 * The strategy is to open one more connection than
2436 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2437 * least-performing one, and then inquire for new ones.
2439 * @param cls the `struct CadetTunnel`
2442 maintain_connections_cb (void *cls)
2444 struct CadetTunnel *t = cls;
2446 t->maintain_connections_task = NULL;
2447 LOG (GNUNET_ERROR_TYPE_DEBUG,
2448 "Performing connection maintenance for %s.\n",
2451 (void) GCP_iterate_paths (t->destination,
2455 GNUNET_break (0); // FIXME: implement!
2460 * Consider using the path @a p for the tunnel @a t.
2461 * The tunnel destination is at offset @a off in path @a p.
2463 * @param cls our tunnel
2464 * @param path a path to our destination
2465 * @param off offset of the destination on path @a path
2468 GCT_consider_path (struct CadetTunnel *t,
2469 struct CadetPeerPath *p,
2472 (void) consider_path_cb (t,
2479 * We got a keepalive. Track in statistics.
2481 * @param cls the `struct CadetTunnel` for which we decrypted the message
2482 * @param msg the message we received on the tunnel
2485 handle_plaintext_keepalive (void *cls,
2486 const struct GNUNET_MessageHeader *msg)
2488 struct CadetTunnel *t = cls;
2490 LOG (GNUNET_ERROR_TYPE_DEBUG,
2491 "Received KEEPALIVE on %s\n",
2493 GNUNET_STATISTICS_update (stats,
2494 "# keepalives received",
2501 * Check that @a msg is well-formed.
2503 * @param cls the `struct CadetTunnel` for which we decrypted the message
2504 * @param msg the message we received on the tunnel
2505 * @return #GNUNET_OK (any variable-size payload goes)
2508 check_plaintext_data (void *cls,
2509 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2516 * We received payload data for a channel. Locate the channel
2517 * and process the data, or return an error if the channel is unknown.
2519 * @param cls the `struct CadetTunnel` for which we decrypted the message
2520 * @param msg the message we received on the tunnel
2523 handle_plaintext_data (void *cls,
2524 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2526 struct CadetTunnel *t = cls;
2527 struct CadetChannel *ch;
2529 ch = lookup_channel (t,
2533 /* We don't know about such a channel, might have been destroyed on our
2534 end in the meantime, or never existed. Send back a DESTROY. */
2535 LOG (GNUNET_ERROR_TYPE_DEBUG,
2536 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2537 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2538 ntohl (msg->ctn.cn));
2539 GCT_send_channel_destroy (t,
2543 GCCH_handle_channel_plaintext_data (ch,
2549 * We received an acknowledgement for data we sent on a channel.
2550 * Locate the channel and process it, or return an error if the
2551 * channel is unknown.
2553 * @param cls the `struct CadetTunnel` for which we decrypted the message
2554 * @param ack the message we received on the tunnel
2557 handle_plaintext_data_ack (void *cls,
2558 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2560 struct CadetTunnel *t = cls;
2561 struct CadetChannel *ch;
2563 ch = lookup_channel (t,
2567 /* We don't know about such a channel, might have been destroyed on our
2568 end in the meantime, or never existed. Send back a DESTROY. */
2569 LOG (GNUNET_ERROR_TYPE_DEBUG,
2570 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2571 ntohl (ack->ctn.cn));
2572 GCT_send_channel_destroy (t,
2576 GCCH_handle_channel_plaintext_data_ack (ch,
2582 * We have received a request to open a channel to a port from
2583 * another peer. Creates the incoming channel.
2585 * @param cls the `struct CadetTunnel` for which we decrypted the message
2586 * @param copen the message we received on the tunnel
2589 handle_plaintext_channel_open (void *cls,
2590 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2592 struct CadetTunnel *t = cls;
2593 struct CadetChannel *ch;
2595 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2596 ntohl (copen->ctn.cn));
2599 LOG (GNUNET_ERROR_TYPE_DEBUG,
2600 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2601 GNUNET_h2s (&copen->port),
2604 GCCH_handle_duplicate_open (ch);
2607 LOG (GNUNET_ERROR_TYPE_DEBUG,
2608 "Receicved channel OPEN on port %s from %s\n",
2609 GNUNET_h2s (&copen->port),
2611 ch = GCCH_channel_incoming_new (t,
2614 ntohl (copen->opt));
2615 GNUNET_assert (GNUNET_OK ==
2616 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2617 ntohl (copen->ctn.cn),
2619 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2624 * Send a DESTROY message via the tunnel.
2626 * @param t the tunnel to transmit over
2627 * @param ctn ID of the channel to destroy
2630 GCT_send_channel_destroy (struct CadetTunnel *t,
2631 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2633 struct GNUNET_CADET_ChannelManageMessage msg;
2635 LOG (GNUNET_ERROR_TYPE_DEBUG,
2636 "Sending DESTORY message for channel ID %u\n",
2638 msg.header.size = htons (sizeof (msg));
2639 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2640 msg.reserved = htonl (0);
2650 * We have received confirmation from the target peer that the
2651 * given channel could be established (the port is open).
2654 * @param cls the `struct CadetTunnel` for which we decrypted the message
2655 * @param cm the message we received on the tunnel
2658 handle_plaintext_channel_open_ack (void *cls,
2659 const struct GNUNET_CADET_ChannelManageMessage *cm)
2661 struct CadetTunnel *t = cls;
2662 struct CadetChannel *ch;
2664 ch = lookup_channel (t,
2668 /* We don't know about such a channel, might have been destroyed on our
2669 end in the meantime, or never existed. Send back a DESTROY. */
2670 LOG (GNUNET_ERROR_TYPE_DEBUG,
2671 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2672 ntohl (cm->ctn.cn));
2673 GCT_send_channel_destroy (t,
2677 LOG (GNUNET_ERROR_TYPE_DEBUG,
2678 "Received channel OPEN_ACK on channel %s from %s\n",
2681 GCCH_handle_channel_open_ack (ch);
2686 * We received a message saying that a channel should be destroyed.
2687 * Pass it on to the correct channel.
2689 * @param cls the `struct CadetTunnel` for which we decrypted the message
2690 * @param cm the message we received on the tunnel
2693 handle_plaintext_channel_destroy (void *cls,
2694 const struct GNUNET_CADET_ChannelManageMessage *cm)
2696 struct CadetTunnel *t = cls;
2697 struct CadetChannel *ch;
2699 ch = lookup_channel (t,
2703 /* We don't know about such a channel, might have been destroyed on our
2704 end in the meantime, or never existed. */
2705 LOG (GNUNET_ERROR_TYPE_DEBUG,
2706 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2707 ntohl (cm->ctn.cn));
2710 LOG (GNUNET_ERROR_TYPE_DEBUG,
2711 "Receicved channel DESTROY on %s from %s\n",
2714 GCCH_handle_remote_destroy (ch);
2719 * Handles a message we decrypted, by injecting it into
2720 * our message queue (which will do the dispatching).
2722 * @param cls the `struct CadetTunnel` that got the message
2723 * @param msg the message
2724 * @return #GNUNET_OK (continue to process)
2727 handle_decrypted (void *cls,
2728 const struct GNUNET_MessageHeader *msg)
2730 struct CadetTunnel *t = cls;
2732 GNUNET_MQ_inject_message (t->mq,
2739 * Function called if we had an error processing
2740 * an incoming decrypted message.
2742 * @param cls the `struct CadetTunnel`
2743 * @param error error code
2746 decrypted_error_cb (void *cls,
2747 enum GNUNET_MQ_Error error)
2749 GNUNET_break_op (0);
2754 * Create a tunnel to @a destionation. Must only be called
2755 * from within #GCP_get_tunnel().
2757 * @param destination where to create the tunnel to
2758 * @return new tunnel to @a destination
2760 struct CadetTunnel *
2761 GCT_create_tunnel (struct CadetPeer *destination)
2763 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2764 struct GNUNET_MQ_MessageHandler handlers[] = {
2765 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2766 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2767 struct GNUNET_MessageHeader,
2769 GNUNET_MQ_hd_var_size (plaintext_data,
2770 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2771 struct GNUNET_CADET_ChannelAppDataMessage,
2773 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2774 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2775 struct GNUNET_CADET_ChannelDataAckMessage,
2777 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2778 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2779 struct GNUNET_CADET_ChannelOpenMessage,
2781 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2782 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2783 struct GNUNET_CADET_ChannelManageMessage,
2785 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2786 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2787 struct GNUNET_CADET_ChannelManageMessage,
2789 GNUNET_MQ_handler_end ()
2792 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2793 new_ephemeral (&t->ax);
2794 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2795 t->destination = destination;
2796 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2797 t->maintain_connections_task
2798 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2800 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2805 &decrypted_error_cb,
2807 t->mst = GNUNET_MST_create (&handle_decrypted,
2814 * Add a @a connection to the @a tunnel.
2817 * @param cid connection identifer to use for the connection
2818 * @param path path to use for the connection
2819 * @return #GNUNET_OK on success,
2820 * #GNUNET_SYSERR on failure (duplicate connection)
2823 GCT_add_inbound_connection (struct CadetTunnel *t,
2824 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2825 struct CadetPeerPath *path)
2827 struct CadetTConnection *ct;
2829 ct = GNUNET_new (struct CadetTConnection);
2830 ct->created = GNUNET_TIME_absolute_get ();
2832 ct->cc = GCC_create_inbound (t->destination,
2836 &connection_ready_cb,
2840 LOG (GNUNET_ERROR_TYPE_DEBUG,
2841 "%s refused inbound %s (duplicate)\n",
2845 return GNUNET_SYSERR;
2847 /* FIXME: schedule job to kill connection (and path?) if it takes
2848 too long to get ready! (And track performance data on how long
2849 other connections took with the tunnel!)
2850 => Note: to be done within 'connection'-logic! */
2851 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2852 t->connection_busy_tail,
2854 t->num_busy_connections++;
2855 LOG (GNUNET_ERROR_TYPE_DEBUG,
2864 * Handle encrypted message.
2866 * @param ct connection/tunnel combo that received encrypted message
2867 * @param msg the encrypted message to decrypt
2870 GCT_handle_encrypted (struct CadetTConnection *ct,
2871 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2873 struct CadetTunnel *t = ct->t;
2874 uint16_t size = ntohs (msg->header.size);
2875 char cbuf [size] GNUNET_ALIGN;
2876 ssize_t decrypted_size;
2878 LOG (GNUNET_ERROR_TYPE_DEBUG,
2879 "%s received %u bytes of encrypted data in state %d\n",
2881 (unsigned int) size,
2886 case CADET_TUNNEL_KEY_UNINITIALIZED:
2887 case CADET_TUNNEL_KEY_AX_RECV:
2888 /* We did not even SEND our KX, how can the other peer
2889 send us encrypted data? */
2890 GNUNET_break_op (0);
2892 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2893 /* We send KX, and other peer send KX to us at the same time.
2894 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
2895 GNUNET_STATISTICS_update (stats,
2896 "# received encrypted without KX_AUTH",
2899 if (NULL != t->kx_task)
2901 GNUNET_SCHEDULER_cancel (t->kx_task);
2909 case CADET_TUNNEL_KEY_AX_SENT:
2910 /* We did not get the KX of the other peer, but that
2911 might have been lost. Send our KX again immediately. */
2912 GNUNET_STATISTICS_update (stats,
2913 "# received encrypted without KX",
2916 if (NULL != t->kx_task)
2918 GNUNET_SCHEDULER_cancel (t->kx_task);
2925 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2926 /* Great, first payload, we might graduate to OK! */
2927 case CADET_TUNNEL_KEY_OK:
2928 /* We are up and running, all good. */
2932 GNUNET_STATISTICS_update (stats,
2933 "# received encrypted",
2936 decrypted_size = -1;
2937 if (CADET_TUNNEL_KEY_OK == t->estate)
2939 /* We have well-established key material available,
2940 try that. (This is the common case.) */
2941 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2947 if ( (-1 == decrypted_size) &&
2948 (NULL != t->unverified_ax) )
2950 /* We have un-authenticated KX material available. We should try
2951 this as a back-up option, in case the sender crashed and
2953 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2957 if (-1 != decrypted_size)
2959 /* It worked! Treat this as authentication of the AX data! */
2960 t->ax.DHRs = NULL; /* aliased with ax.DHRs */
2961 t->ax.kx_0 = NULL; /* aliased with ax.DHRs */
2962 cleanup_ax (&t->ax);
2963 t->ax = *t->unverified_ax;
2964 GNUNET_free (t->unverified_ax);
2965 t->unverified_ax = NULL;
2967 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
2969 /* First time it worked, move tunnel into production! */
2970 GCT_change_estate (t,
2971 CADET_TUNNEL_KEY_OK);
2972 if (NULL != t->send_task)
2973 GNUNET_SCHEDULER_cancel (t->send_task);
2974 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2978 if (NULL != t->unverified_ax)
2980 /* We had unverified KX material that was useless; so increment
2981 counter and eventually move to ignore it. Note that we even do
2982 this increment if we successfully decrypted with the old KX
2983 material and thus didn't even both with the new one. This is
2984 the ideal case, as a malicious injection of bogus KX data
2985 basically only causes us to increment a counter a few times. */
2986 t->unverified_attempts++;
2987 LOG (GNUNET_ERROR_TYPE_DEBUG,
2988 "Failed to decrypt message with unverified KX data %u times\n",
2989 t->unverified_attempts);
2990 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2992 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
2993 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
2994 cleanup_ax (t->unverified_ax);
2995 GNUNET_free (t->unverified_ax);
2996 t->unverified_ax = NULL;
3000 if (-1 == decrypted_size)
3002 /* Decryption failed for good, complain. */
3003 GNUNET_break_op (0);
3004 LOG (GNUNET_ERROR_TYPE_WARNING,
3005 "%s failed to decrypt and validate encrypted data\n",
3007 GNUNET_STATISTICS_update (stats,
3008 "# unable to decrypt",
3014 /* The MST will ultimately call #handle_decrypted() on each message. */
3015 GNUNET_break_op (GNUNET_OK ==
3016 GNUNET_MST_from_buffer (t->mst,
3025 * Sends an already built message on a tunnel, encrypting it and
3026 * choosing the best connection if not provided.
3028 * @param message Message to send. Function modifies it.
3029 * @param t Tunnel on which this message is transmitted.
3030 * @param cont Continuation to call once message is really sent.
3031 * @param cont_cls Closure for @c cont.
3032 * @return Handle to cancel message
3034 struct CadetTunnelQueueEntry *
3035 GCT_send (struct CadetTunnel *t,
3036 const struct GNUNET_MessageHeader *message,
3037 GNUNET_SCHEDULER_TaskCallback cont,
3040 struct CadetTunnelQueueEntry *tq;
3041 uint16_t payload_size;
3042 struct GNUNET_MQ_Envelope *env;
3043 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3045 if (CADET_TUNNEL_KEY_OK != t->estate)
3050 payload_size = ntohs (message->size);
3051 LOG (GNUNET_ERROR_TYPE_DEBUG,
3052 "Encrypting %u bytes for %s\n",
3053 (unsigned int) payload_size,
3055 env = GNUNET_MQ_msg_extra (ax_msg,
3057 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3058 t_ax_encrypt (&t->ax,
3062 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3063 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3064 /* FIXME: we should do this once, not once per message;
3065 this is a point multiplication, and DHRs does not
3066 change all the time. */
3067 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
3068 &ax_msg->ax_header.DHRs);
3069 t_h_encrypt (&t->ax,
3071 t_hmac (&ax_msg->ax_header,
3072 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3077 tq = GNUNET_malloc (sizeof (*tq));
3080 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3082 tq->cont_cls = cont_cls;
3083 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3086 if (NULL != t->send_task)
3087 GNUNET_SCHEDULER_cancel (t->send_task);
3089 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3096 * Cancel a previously sent message while it's in the queue.
3098 * ONLY can be called before the continuation given to the send
3099 * function is called. Once the continuation is called, the message is
3100 * no longer in the queue!
3102 * @param tq Handle to the queue entry to cancel.
3105 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3107 struct CadetTunnel *t = tq->t;
3109 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3112 GNUNET_MQ_discard (tq->env);
3118 * Iterate over all connections of a tunnel.
3120 * @param t Tunnel whose connections to iterate.
3121 * @param iter Iterator.
3122 * @param iter_cls Closure for @c iter.
3125 GCT_iterate_connections (struct CadetTunnel *t,
3126 GCT_ConnectionIterator iter,
3129 struct CadetTConnection *n;
3130 for (struct CadetTConnection *ct = t->connection_ready_head;
3138 for (struct CadetTConnection *ct = t->connection_busy_head;
3150 * Closure for #iterate_channels_cb.
3157 GCT_ChannelIterator iter;
3160 * Closure for @e iter.
3167 * Helper function for #GCT_iterate_channels.
3169 * @param cls the `struct ChanIterCls`
3171 * @param value a `struct CadetChannel`
3172 * @return #GNUNET_OK
3175 iterate_channels_cb (void *cls,
3179 struct ChanIterCls *ctx = cls;
3180 struct CadetChannel *ch = value;
3182 ctx->iter (ctx->iter_cls,
3189 * Iterate over all channels of a tunnel.
3191 * @param t Tunnel whose channels to iterate.
3192 * @param iter Iterator.
3193 * @param iter_cls Closure for @c iter.
3196 GCT_iterate_channels (struct CadetTunnel *t,
3197 GCT_ChannelIterator iter,
3200 struct ChanIterCls ctx;
3203 ctx.iter_cls = iter_cls;
3204 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3205 &iterate_channels_cb,
3212 * Call #GCCH_debug() on a channel.
3214 * @param cls points to the log level to use
3216 * @param value the `struct CadetChannel` to dump
3217 * @return #GNUNET_OK (continue iteration)
3220 debug_channel (void *cls,
3224 const enum GNUNET_ErrorType *level = cls;
3225 struct CadetChannel *ch = value;
3227 GCCH_debug (ch, *level);
3232 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3236 * Log all possible info about the tunnel state.
3238 * @param t Tunnel to debug.
3239 * @param level Debug level to use.
3242 GCT_debug (const struct CadetTunnel *t,
3243 enum GNUNET_ErrorType level)
3245 struct CadetTConnection *iter_c;
3248 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3250 __FILE__, __FUNCTION__, __LINE__);
3255 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3257 estate2s (t->estate),
3259 GCT_count_any_connections (t));
3262 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3266 "TTT connections:\n");
3267 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3268 GCC_debug (iter_c->cc,
3270 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3271 GCC_debug (iter_c->cc,
3275 "TTT TUNNEL END\n");
3279 /* end of gnunet-service-cadet-new_tunnels.c */