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 * Last ephemeral public key received from the other peer,
191 * for duplicate detection.
193 struct GNUNET_CRYPTO_EcdhePublicKey last_ephemeral;
196 * Time when the current ratchet expires and a new one is triggered
197 * (if @e ratchet_allowed is #GNUNET_YES).
199 struct GNUNET_TIME_Absolute ratchet_expiration;
202 * Number of elements in @a skipped_head <-> @a skipped_tail.
204 unsigned int skipped;
207 * Message number (reset to 0 with each new ratchet, next message to send).
212 * Message number (reset to 0 with each new ratchet, next message to recv).
217 * Previous message numbers (# of msgs sent under prev ratchet)
222 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
227 * True (#GNUNET_YES) if we have received a message from the
228 * other peer that uses the keys from our last ratchet step.
229 * This implies that we are again allowed to advance the ratchet,
230 * otherwise we have to wait until the other peer sees our current
231 * ephemeral key and advances first.
233 * #GNUNET_NO if we have advanced the ratched but lack any evidence
234 * that the other peer has noticed this.
239 * Number of messages recieved since our last ratchet advance.
241 * If this counter = 0, we cannot send a new ratchet key in the next
244 * If this counter > 0, we could (but don't have to) send a new key.
246 * Once the @e ratchet_counter is larger than
247 * #ratchet_messages (or @e ratchet_expiration time has past), and
248 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
250 unsigned int ratchet_counter;
256 * Struct used to save messages in a non-ready tunnel to send once connected.
258 struct CadetTunnelQueueEntry
261 * We are entries in a DLL
263 struct CadetTunnelQueueEntry *next;
266 * We are entries in a DLL
268 struct CadetTunnelQueueEntry *prev;
271 * Tunnel these messages belong in.
273 struct CadetTunnel *t;
276 * Continuation to call once sent (on the channel layer).
278 GCT_SendContinuation cont;
281 * Closure for @c cont.
286 * Envelope of message to send follows.
288 struct GNUNET_MQ_Envelope *env;
291 * Where to put the connection identifier into the payload
292 * of the message in @e env once we have it?
294 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
299 * Struct containing all information regarding a tunnel to a peer.
304 * Destination of the tunnel.
306 struct CadetPeer *destination;
309 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
310 * ephemeral key changes.
312 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
315 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
317 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
320 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
322 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
327 struct CadetTunnelAxolotl ax;
330 * Unverified Axolotl info, used only if we got a fresh KX (not a
331 * KX_AUTH) while our end of the tunnel was still up. In this case,
332 * we keep the fresh KX around but do not put it into action until
333 * we got encrypted payload that assures us of the authenticity of
336 struct CadetTunnelAxolotl *unverified_ax;
339 * Task scheduled if there are no more channels using the tunnel.
341 struct GNUNET_SCHEDULER_Task *destroy_task;
344 * Task to trim connections if too many are present.
346 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
349 * Task to send messages from queue (if possible).
351 struct GNUNET_SCHEDULER_Task *send_task;
354 * Task to trigger KX.
356 struct GNUNET_SCHEDULER_Task *kx_task;
359 * Tokenizer for decrypted messages.
361 struct GNUNET_MessageStreamTokenizer *mst;
364 * Dispatcher for decrypted messages only (do NOT use for sending!).
366 struct GNUNET_MQ_Handle *mq;
369 * DLL of ready connections that are actively used to reach the destination peer.
371 struct CadetTConnection *connection_ready_head;
374 * DLL of ready connections that are actively used to reach the destination peer.
376 struct CadetTConnection *connection_ready_tail;
379 * DLL of connections that we maintain that might be used to reach the destination peer.
381 struct CadetTConnection *connection_busy_head;
384 * DLL of connections that we maintain that might be used to reach the destination peer.
386 struct CadetTConnection *connection_busy_tail;
389 * Channels inside this tunnel. Maps
390 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
392 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
395 * Channel ID for the next created channel in this tunnel.
397 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
400 * Queued messages, to transmit once tunnel gets connected.
402 struct CadetTunnelQueueEntry *tq_head;
405 * Queued messages, to transmit once tunnel gets connected.
407 struct CadetTunnelQueueEntry *tq_tail;
410 * Identification of the connection from which we are currently processing
411 * a message. Only valid (non-NULL) during #handle_decrypted() and the
412 * handle-*()-functions called from our @e mq during that function.
414 struct CadetTConnection *current_ct;
417 * How long do we wait until we retry the KX?
419 struct GNUNET_TIME_Relative kx_retry_delay;
422 * When do we try the next KX?
424 struct GNUNET_TIME_Absolute next_kx_attempt;
427 * Number of connections in the @e connection_ready_head DLL.
429 unsigned int num_ready_connections;
432 * Number of connections in the @e connection_busy_head DLL.
434 unsigned int num_busy_connections;
437 * How often have we tried and failed to decrypt a message using
438 * the unverified KX material from @e unverified_ax? Used to
439 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
441 unsigned int unverified_attempts;
444 * Number of entries in the @e tq_head DLL.
449 * State of the tunnel encryption.
451 enum CadetTunnelEState estate;
454 * Force triggering KX_AUTH independent of @e estate.
456 int kx_auth_requested;
462 * Connection @a ct is now unready, clear it's ready flag
463 * and move it from the ready DLL to the busy DLL.
465 * @param ct connection to move to unready status
468 mark_connection_unready (struct CadetTConnection *ct)
470 struct CadetTunnel *t = ct->t;
472 GNUNET_assert (GNUNET_YES == ct->is_ready);
473 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
474 t->connection_ready_tail,
476 GNUNET_assert (0 < t->num_ready_connections);
477 t->num_ready_connections--;
478 ct->is_ready = GNUNET_NO;
479 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
480 t->connection_busy_tail,
482 t->num_busy_connections++;
487 * Get the static string for the peer this tunnel is directed.
491 * @return Static string the destination peer's ID.
494 GCT_2s (const struct CadetTunnel *t)
499 return "Tunnel(NULL)";
500 GNUNET_snprintf (buf,
503 GNUNET_i2s (GCP_get_id (t->destination)));
509 * Get string description for tunnel encryption state.
511 * @param es Tunnel state.
513 * @return String representation.
516 estate2s (enum CadetTunnelEState es)
522 case CADET_TUNNEL_KEY_UNINITIALIZED:
523 return "CADET_TUNNEL_KEY_UNINITIALIZED";
524 case CADET_TUNNEL_KEY_AX_RECV:
525 return "CADET_TUNNEL_KEY_AX_RECV";
526 case CADET_TUNNEL_KEY_AX_SENT:
527 return "CADET_TUNNEL_KEY_AX_SENT";
528 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
529 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
530 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
531 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
532 case CADET_TUNNEL_KEY_OK:
533 return "CADET_TUNNEL_KEY_OK";
535 GNUNET_snprintf (buf,
537 "%u (UNKNOWN STATE)",
545 * Return the peer to which this tunnel goes.
548 * @return the destination of the tunnel
551 GCT_get_destination (struct CadetTunnel *t)
553 return t->destination;
558 * Count channels of a tunnel.
560 * @param t Tunnel on which to count.
562 * @return Number of channels.
565 GCT_count_channels (struct CadetTunnel *t)
567 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
572 * Lookup a channel by its @a ctn.
574 * @param t tunnel to look in
575 * @param ctn number of channel to find
576 * @return NULL if channel does not exist
578 struct CadetChannel *
579 lookup_channel (struct CadetTunnel *t,
580 struct GNUNET_CADET_ChannelTunnelNumber ctn)
582 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
588 * Count all created connections of a tunnel. Not necessarily ready connections!
590 * @param t Tunnel on which to count.
592 * @return Number of connections created, either being established or ready.
595 GCT_count_any_connections (const struct CadetTunnel *t)
597 return t->num_ready_connections + t->num_busy_connections;
602 * Find first connection that is ready in the list of
603 * our connections. Picks ready connections round-robin.
605 * @param t tunnel to search
606 * @return NULL if we have no connection that is ready
608 static struct CadetTConnection *
609 get_ready_connection (struct CadetTunnel *t)
611 struct CadetTConnection *hd = t->connection_ready_head;
613 GNUNET_assert ( (NULL == hd) ||
614 (GNUNET_YES == hd->is_ready) );
620 * Get the encryption state of a tunnel.
624 * @return Tunnel's encryption state.
626 enum CadetTunnelEState
627 GCT_get_estate (struct CadetTunnel *t)
634 * Called when either we have a new connection, or a new message in the
635 * queue, or some existing connection has transmission capacity. Looks
636 * at our message queue and if there is a message, picks a connection
639 * @param cls the `struct CadetTunnel` to process messages on
642 trigger_transmissions (void *cls);
645 /* ************************************** start core crypto ***************************** */
649 * Create a new Axolotl ephemeral (ratchet) key.
651 * @param ax key material to update
654 new_ephemeral (struct CadetTunnelAxolotl *ax)
656 LOG (GNUNET_ERROR_TYPE_DEBUG,
657 "Creating new ephemeral ratchet key (DHRs)\n");
658 GNUNET_assert (GNUNET_OK ==
659 GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
666 * @param plaintext Content to HMAC.
667 * @param size Size of @c plaintext.
668 * @param iv Initialization vector for the message.
669 * @param key Key to use.
670 * @param hmac[out] Destination to store the HMAC.
673 t_hmac (const void *plaintext,
676 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
677 struct GNUNET_ShortHashCode *hmac)
679 static const char ctx[] = "cadet authentication key";
680 struct GNUNET_CRYPTO_AuthKey auth_key;
681 struct GNUNET_HashCode hash;
683 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
689 /* Two step: GNUNET_ShortHash is only 256 bits,
690 GNUNET_HashCode is 512, so we truncate. */
691 GNUNET_CRYPTO_hmac (&auth_key,
704 * @param key Key to use.
705 * @param[out] hash Resulting HMAC.
706 * @param source Source key material (data to HMAC).
707 * @param len Length of @a source.
710 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
711 struct GNUNET_HashCode *hash,
715 static const char ctx[] = "axolotl HMAC-HASH";
716 struct GNUNET_CRYPTO_AuthKey auth_key;
718 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
722 GNUNET_CRYPTO_hmac (&auth_key,
730 * Derive a symmetric encryption key from an HMAC-HASH.
732 * @param key Key to use for the HMAC.
733 * @param[out] out Key to generate.
734 * @param source Source key material (data to HMAC).
735 * @param len Length of @a source.
738 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
739 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
743 static const char ctx[] = "axolotl derive key";
744 struct GNUNET_HashCode h;
750 GNUNET_CRYPTO_kdf (out, sizeof (*out),
758 * Encrypt data with the axolotl tunnel key.
760 * @param ax key material to use.
761 * @param dst Destination with @a size bytes for the encrypted data.
762 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
763 * @param size Size of the buffers at @a src and @a dst
766 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
771 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
772 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
775 ax->ratchet_counter++;
776 if ( (GNUNET_YES == ax->ratchet_allowed) &&
777 ( (ratchet_messages <= ax->ratchet_counter) ||
778 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
780 ax->ratchet_flag = GNUNET_YES;
782 if (GNUNET_YES == ax->ratchet_flag)
784 /* Advance ratchet */
785 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
786 struct GNUNET_HashCode dh;
787 struct GNUNET_HashCode hmac;
788 static const char ctx[] = "axolotl ratchet";
793 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
794 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
797 t_ax_hmac_hash (&ax->RK,
801 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
803 &hmac, sizeof (hmac),
811 ax->ratchet_flag = GNUNET_NO;
812 ax->ratchet_allowed = GNUNET_NO;
813 ax->ratchet_counter = 0;
814 ax->ratchet_expiration
815 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
819 t_hmac_derive_key (&ax->CKs,
823 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
828 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
833 GNUNET_assert (size == out_size);
834 t_hmac_derive_key (&ax->CKs,
842 * Decrypt data with the axolotl tunnel key.
844 * @param ax key material to use.
845 * @param dst Destination for the decrypted data, must contain @a size bytes.
846 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
847 * @param size Size of the @a src and @a dst buffers
850 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
855 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
856 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
859 t_hmac_derive_key (&ax->CKr,
863 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
867 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
868 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
873 GNUNET_assert (out_size == size);
874 t_hmac_derive_key (&ax->CKr,
882 * Encrypt header with the axolotl header key.
884 * @param ax key material to use.
885 * @param[in|out] msg Message whose header to encrypt.
888 t_h_encrypt (struct CadetTunnelAxolotl *ax,
889 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
891 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
894 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
898 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
899 sizeof (struct GNUNET_CADET_AxHeader),
903 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
908 * Decrypt header with the current axolotl header key.
910 * @param ax key material to use.
911 * @param src Message whose header to decrypt.
912 * @param dst Where to decrypt header to.
915 t_h_decrypt (struct CadetTunnelAxolotl *ax,
916 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
917 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
919 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
922 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
926 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
927 sizeof (struct GNUNET_CADET_AxHeader),
931 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
936 * Delete a key from the list of skipped keys.
938 * @param ax key material to delete @a key from.
939 * @param key Key to delete.
942 delete_skipped_key (struct CadetTunnelAxolotl *ax,
943 struct CadetTunnelSkippedKey *key)
945 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
954 * Decrypt and verify data with the appropriate tunnel key and verify that the
955 * data has not been altered since it was sent by the remote peer.
957 * @param ax key material to use.
958 * @param dst Destination for the plaintext.
959 * @param src Source of the message. Can overlap with @c dst.
960 * @param size Size of the message.
961 * @return Size of the decrypted data, -1 if an error was encountered.
964 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
966 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
969 struct CadetTunnelSkippedKey *key;
970 struct GNUNET_ShortHashCode *hmac;
971 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
972 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
973 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
979 LOG (GNUNET_ERROR_TYPE_DEBUG,
980 "Trying skipped keys\n");
981 hmac = &plaintext_header.hmac;
982 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
984 /* Find a correct Header Key */
986 for (key = ax->skipped_head; NULL != key; key = key->next)
988 t_hmac (&src->ax_header,
989 sizeof (struct GNUNET_CADET_AxHeader) + esize,
993 if (0 == memcmp (hmac,
1004 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
1005 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
1006 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1007 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1009 /* Decrypt header */
1010 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1014 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1015 sizeof (struct GNUNET_CADET_AxHeader),
1018 &plaintext_header.ax_header.Ns);
1019 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1021 /* Find the correct message key */
1022 N = ntohl (plaintext_header.ax_header.Ns);
1023 while ( (NULL != key) &&
1026 if ( (NULL == key) ||
1027 (0 != memcmp (&key->HK,
1029 sizeof (*valid_HK))) )
1032 /* Decrypt payload */
1033 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1038 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1043 delete_skipped_key (ax,
1050 * Delete a key from the list of skipped keys.
1052 * @param ax key material to delete from.
1053 * @param HKr Header Key to use.
1056 store_skipped_key (struct CadetTunnelAxolotl *ax,
1057 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1059 struct CadetTunnelSkippedKey *key;
1061 key = GNUNET_new (struct CadetTunnelSkippedKey);
1062 key->timestamp = GNUNET_TIME_absolute_get ();
1065 t_hmac_derive_key (&ax->CKr,
1069 t_hmac_derive_key (&ax->CKr,
1073 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1082 * Stage skipped AX keys and calculate the message key.
1083 * Stores each HK and MK for skipped messages.
1085 * @param ax key material to use
1086 * @param HKr Header key.
1087 * @param Np Received meesage number.
1088 * @return #GNUNET_OK if keys were stored.
1089 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1092 store_ax_keys (struct CadetTunnelAxolotl *ax,
1093 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1099 LOG (GNUNET_ERROR_TYPE_DEBUG,
1100 "Storing skipped keys [%u, %u)\n",
1103 if (MAX_KEY_GAP < gap)
1105 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1106 /* TODO: start new key exchange on return */
1107 GNUNET_break_op (0);
1108 LOG (GNUNET_ERROR_TYPE_WARNING,
1109 "Got message %u, expected %u+\n",
1112 return GNUNET_SYSERR;
1116 /* Delayed message: don't store keys, flag to try old keys. */
1117 return GNUNET_SYSERR;
1121 store_skipped_key (ax,
1124 while (ax->skipped > MAX_SKIPPED_KEYS)
1125 delete_skipped_key (ax,
1132 * Decrypt and verify data with the appropriate tunnel key and verify that the
1133 * data has not been altered since it was sent by the remote peer.
1135 * @param ax key material to use
1136 * @param dst Destination for the plaintext.
1137 * @param src Source of the message. Can overlap with @c dst.
1138 * @param size Size of the message.
1139 * @return Size of the decrypted data, -1 if an error was encountered.
1142 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1144 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1147 struct GNUNET_ShortHashCode msg_hmac;
1148 struct GNUNET_HashCode hmac;
1149 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1152 size_t esize; /* Size of encryped payload */
1154 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1156 /* Try current HK */
1157 t_hmac (&src->ax_header,
1158 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1161 if (0 != memcmp (&msg_hmac,
1165 static const char ctx[] = "axolotl ratchet";
1166 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1167 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1168 struct GNUNET_HashCode dh;
1169 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1172 t_hmac (&src->ax_header,
1173 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1177 if (0 != memcmp (&msg_hmac,
1181 /* Try the skipped keys, if that fails, we're out of luck. */
1182 return try_old_ax_keys (ax,
1192 Np = ntohl (plaintext_header.ax_header.Ns);
1193 PNp = ntohl (plaintext_header.ax_header.PNs);
1194 DHRp = &plaintext_header.ax_header.DHRs;
1199 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1200 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1203 t_ax_hmac_hash (&ax->RK,
1206 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1208 &hmac, sizeof (hmac),
1211 /* Commit "purported" keys */
1217 ax->ratchet_allowed = GNUNET_YES;
1224 Np = ntohl (plaintext_header.ax_header.Ns);
1225 PNp = ntohl (plaintext_header.ax_header.PNs);
1227 if ( (Np != ax->Nr) &&
1228 (GNUNET_OK != store_ax_keys (ax,
1232 /* Try the skipped keys, if that fails, we're out of luck. */
1233 return try_old_ax_keys (ax,
1249 * Our tunnel became ready for the first time, notify channels
1250 * that have been waiting.
1252 * @param cls our tunnel, not used
1253 * @param key unique ID of the channel, not used
1254 * @param value the `struct CadetChannel` to notify
1255 * @return #GNUNET_OK (continue to iterate)
1258 notify_tunnel_up_cb (void *cls,
1262 struct CadetChannel *ch = value;
1264 GCCH_tunnel_up (ch);
1270 * Change the tunnel encryption state.
1271 * If the encryption state changes to OK, stop the rekey task.
1273 * @param t Tunnel whose encryption state to change, or NULL.
1274 * @param state New encryption state.
1277 GCT_change_estate (struct CadetTunnel *t,
1278 enum CadetTunnelEState state)
1280 enum CadetTunnelEState old = t->estate;
1283 LOG (GNUNET_ERROR_TYPE_DEBUG,
1284 "%s estate changed from %s to %s\n",
1289 if ( (CADET_TUNNEL_KEY_OK != old) &&
1290 (CADET_TUNNEL_KEY_OK == t->estate) )
1292 if (NULL != t->kx_task)
1294 GNUNET_SCHEDULER_cancel (t->kx_task);
1297 /* notify all channels that have been waiting */
1298 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1299 ¬ify_tunnel_up_cb,
1301 if (NULL != t->send_task)
1302 GNUNET_SCHEDULER_cancel (t->send_task);
1303 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1310 * Send a KX message.
1312 * @param t tunnel on which to send the KX_AUTH
1313 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1314 * we are to find one that is ready.
1315 * @param ax axolotl key context to use
1318 send_kx (struct CadetTunnel *t,
1319 struct CadetTConnection *ct,
1320 struct CadetTunnelAxolotl *ax)
1322 struct CadetConnection *cc;
1323 struct GNUNET_MQ_Envelope *env;
1324 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1325 enum GNUNET_CADET_KX_Flags flags;
1327 if ( (NULL == ct) ||
1328 (GNUNET_NO == ct->is_ready) )
1329 ct = get_ready_connection (t);
1332 LOG (GNUNET_ERROR_TYPE_DEBUG,
1333 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1335 estate2s (t->estate));
1336 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1340 LOG (GNUNET_ERROR_TYPE_DEBUG,
1341 "Sending KX on %s via %s in state %s\n",
1344 estate2s (t->estate));
1345 env = GNUNET_MQ_msg (msg,
1346 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1347 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1348 msg->flags = htonl (flags);
1349 msg->cid = *GCC_get_id (cc);
1350 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1351 &msg->ephemeral_key);
1352 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1354 mark_connection_unready (ct);
1355 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1356 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1357 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1358 GCT_change_estate (t,
1359 CADET_TUNNEL_KEY_AX_SENT);
1360 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1361 GCT_change_estate (t,
1362 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1365 GNUNET_STATISTICS_update (stats,
1373 * Send a KX_AUTH message.
1375 * @param t tunnel on which to send the KX_AUTH
1376 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1377 * we are to find one that is ready.
1378 * @param ax axolotl key context to use
1379 * @param force_reply Force the other peer to reply with a KX_AUTH message
1380 * (set if we would like to transmit right now, but cannot)
1383 send_kx_auth (struct CadetTunnel *t,
1384 struct CadetTConnection *ct,
1385 struct CadetTunnelAxolotl *ax,
1388 struct CadetConnection *cc;
1389 struct GNUNET_MQ_Envelope *env;
1390 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1391 enum GNUNET_CADET_KX_Flags flags;
1393 if ( (NULL == ct) ||
1394 (GNUNET_NO == ct->is_ready) )
1395 ct = get_ready_connection (t);
1398 LOG (GNUNET_ERROR_TYPE_DEBUG,
1399 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1401 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1402 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1405 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1407 LOG (GNUNET_ERROR_TYPE_DEBUG,
1408 "Sending KX_AUTH on %s using %s\n",
1412 env = GNUNET_MQ_msg (msg,
1413 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1414 flags = GNUNET_CADET_KX_FLAG_NONE;
1415 if (GNUNET_YES == force_reply)
1416 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1417 msg->kx.flags = htonl (flags);
1418 msg->kx.cid = *GCC_get_id (cc);
1419 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1420 &msg->kx.ephemeral_key);
1421 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1422 &msg->kx.ratchet_key);
1423 /* Compute authenticator (this is the main difference to #send_kx()) */
1424 GNUNET_CRYPTO_hash (&ax->RK,
1428 /* Compute when to be triggered again; actual job will
1429 be scheduled via #connection_ready_cb() */
1431 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1433 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1435 /* Send via cc, mark it as unready */
1436 mark_connection_unready (ct);
1438 /* Update state machine, unless we are already OK */
1439 if (CADET_TUNNEL_KEY_OK != t->estate)
1440 GCT_change_estate (t,
1441 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1444 GNUNET_STATISTICS_update (stats,
1445 "# KX_AUTH transmitted",
1452 * Cleanup state used by @a ax.
1454 * @param ax state to free, but not memory of @a ax itself
1457 cleanup_ax (struct CadetTunnelAxolotl *ax)
1459 while (NULL != ax->skipped_head)
1460 delete_skipped_key (ax,
1462 GNUNET_assert (0 == ax->skipped);
1463 GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1464 GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1469 * Update our Axolotl key state based on the KX data we received.
1470 * Computes the new chain keys, and root keys, etc, and also checks
1471 * wether this is a replay of the current chain.
1473 * @param[in|out] axolotl chain key state to recompute
1474 * @param pid peer identity of the other peer
1475 * @param ephemeral_key ephemeral public key of the other peer
1476 * @param ratchet_key senders next ephemeral public key
1477 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1478 * root key is already in @a ax and thus the KX is useless;
1479 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1482 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1483 const struct GNUNET_PeerIdentity *pid,
1484 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1485 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1487 struct GNUNET_HashCode key_material[3];
1488 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1489 const char salt[] = "CADET Axolotl salt";
1492 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1494 am_I_alice = GNUNET_YES;
1495 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1497 am_I_alice = GNUNET_NO;
1500 GNUNET_break_op (0);
1501 return GNUNET_SYSERR;
1504 if (0 == memcmp (&ax->DHRr,
1506 sizeof (*ratchet_key)))
1508 GNUNET_STATISTICS_update (stats,
1509 "# Ratchet key already known",
1512 LOG (GNUNET_ERROR_TYPE_DEBUG,
1513 "Ratchet key already known. Ignoring KX.\n");
1517 ax->DHRr = *ratchet_key;
1518 ax->last_ephemeral = *ephemeral_key;
1520 if (GNUNET_YES == am_I_alice)
1522 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1523 ephemeral_key, /* B0 */
1528 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* B0 */
1529 &pid->public_key, /* A */
1534 if (GNUNET_YES == am_I_alice)
1536 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* A0 */
1537 &pid->public_key, /* B */
1542 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1543 ephemeral_key, /* B0 */
1548 GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0, /* A0 or B0 */
1549 ephemeral_key, /* B0 or A0 */
1553 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1554 salt, sizeof (salt),
1555 &key_material, sizeof (key_material),
1558 if (0 == memcmp (&ax->RK,
1562 LOG (GNUNET_ERROR_TYPE_DEBUG,
1563 "Root key of handshake already known. Ignoring KX.\n");
1564 GNUNET_STATISTICS_update (stats,
1565 "# Root key already known",
1572 if (GNUNET_YES == am_I_alice)
1578 ax->ratchet_flag = GNUNET_YES;
1586 ax->ratchet_flag = GNUNET_NO;
1587 ax->ratchet_expiration
1588 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1596 * Try to redo the KX or KX_AUTH handshake, if we can.
1598 * @param cls the `struct CadetTunnel` to do KX for.
1601 retry_kx (void *cls)
1603 struct CadetTunnel *t = cls;
1604 struct CadetTunnelAxolotl *ax;
1607 LOG (GNUNET_ERROR_TYPE_DEBUG,
1608 "Trying to make KX progress on %s in state %s\n",
1610 estate2s (t->estate));
1613 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1614 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1619 case CADET_TUNNEL_KEY_AX_RECV:
1620 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1621 /* We are responding, so only require reply
1622 if WE have a channel waiting. */
1623 if (NULL != t->unverified_ax)
1625 /* Send AX_AUTH so we might get this one verified */
1626 ax = t->unverified_ax;
1630 /* How can this be? */
1637 (0 == GCT_count_channels (t))
1641 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1642 /* We are responding, so only require reply
1643 if WE have a channel waiting. */
1644 if (NULL != t->unverified_ax)
1646 /* Send AX_AUTH so we might get this one verified */
1647 ax = t->unverified_ax;
1651 /* How can this be? */
1658 (0 == GCT_count_channels (t))
1662 case CADET_TUNNEL_KEY_OK:
1663 /* Must have been the *other* peer asking us to
1664 respond with a KX_AUTH. */
1665 if (NULL != t->unverified_ax)
1667 /* Sending AX_AUTH in response to AX so we might get this one verified */
1668 ax = t->unverified_ax;
1672 /* Sending AX_AUTH in response to AX_AUTH */
1685 * Handle KX message that lacks authentication (and which will thus
1686 * only be considered authenticated after we respond with our own
1687 * KX_AUTH and finally successfully decrypt payload).
1689 * @param ct connection/tunnel combo that received encrypted message
1690 * @param msg the key exchange message
1693 GCT_handle_kx (struct CadetTConnection *ct,
1694 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1696 struct CadetTunnel *t = ct->t;
1697 struct CadetTunnelAxolotl *ax;
1700 GNUNET_STATISTICS_update (stats,
1705 memcmp (&t->ax.DHRr,
1707 sizeof (msg->ratchet_key))) &&
1709 memcmp (&t->ax.last_ephemeral,
1710 &msg->ephemeral_key,
1711 sizeof (msg->ephemeral_key))) )
1714 LOG (GNUNET_ERROR_TYPE_DEBUG,
1715 "Got duplicate KX. Firing back KX_AUTH.\n");
1716 GNUNET_STATISTICS_update (stats,
1717 "# Duplicate KX received",
1727 /* We only keep ONE unverified KX around, so if there is an existing one,
1729 if (NULL != t->unverified_ax)
1732 memcmp (&t->unverified_ax->DHRr,
1734 sizeof (msg->ratchet_key))) &&
1736 memcmp (&t->unverified_ax->last_ephemeral,
1737 &msg->ephemeral_key,
1738 sizeof (msg->ephemeral_key))) )
1740 LOG (GNUNET_ERROR_TYPE_DEBUG,
1741 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1743 GNUNET_STATISTICS_update (stats,
1744 "# Duplicate unverified KX received",
1755 LOG (GNUNET_ERROR_TYPE_DEBUG,
1756 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1758 GNUNET_STATISTICS_update (stats,
1759 "# Unverified KX dropped for fresh KX",
1762 memset (t->unverified_ax,
1764 sizeof (struct CadetTunnelAxolotl));
1765 t->unverified_ax->DHRs = t->ax.DHRs;
1766 t->unverified_ax->kx_0 = t->ax.kx_0;
1770 LOG (GNUNET_ERROR_TYPE_DEBUG,
1771 "Creating fresh unverified KX for %s.\n",
1773 GNUNET_STATISTICS_update (stats,
1777 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1778 t->unverified_ax->DHRs = t->ax.DHRs;
1779 t->unverified_ax->kx_0 = t->ax.kx_0;
1781 /* Set as the 'current' RK/DHRr the one we are currently using,
1782 so that the duplicate-detection logic of
1783 #update_ax_by_kx can work. */
1784 t->unverified_ax->RK = t->ax.RK;
1785 t->unverified_ax->DHRr = t->ax.DHRr;
1786 t->unverified_attempts = 0;
1787 ax = t->unverified_ax;
1789 /* Update 'ax' by the new key material */
1790 ret = update_ax_by_kx (ax,
1791 GCP_get_id (t->destination),
1792 &msg->ephemeral_key,
1794 GNUNET_break (GNUNET_SYSERR != ret);
1795 if (GNUNET_OK != ret)
1797 GNUNET_STATISTICS_update (stats,
1801 return; /* duplicate KX, nothing to do */
1803 /* move ahead in our state machine */
1804 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1805 GCT_change_estate (t,
1806 CADET_TUNNEL_KEY_AX_RECV);
1807 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1808 GCT_change_estate (t,
1809 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1811 /* KX is still not done, try again our end. */
1812 if (CADET_TUNNEL_KEY_OK != t->estate)
1814 if (NULL != t->kx_task)
1815 GNUNET_SCHEDULER_cancel (t->kx_task);
1817 = GNUNET_SCHEDULER_add_now (&retry_kx,
1824 * Handle KX_AUTH message.
1826 * @param ct connection/tunnel combo that received encrypted message
1827 * @param msg the key exchange message
1830 GCT_handle_kx_auth (struct CadetTConnection *ct,
1831 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1833 struct CadetTunnel *t = ct->t;
1834 struct CadetTunnelAxolotl ax_tmp;
1835 struct GNUNET_HashCode kx_auth;
1838 GNUNET_STATISTICS_update (stats,
1839 "# KX_AUTH received",
1842 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1843 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1845 /* Confusing, we got a KX_AUTH before we even send our own
1846 KX. This should not happen. We'll send our own KX ASAP anyway,
1847 so let's ignore this here. */
1848 GNUNET_break_op (0);
1851 LOG (GNUNET_ERROR_TYPE_DEBUG,
1852 "Handling KX_AUTH message for %s\n",
1855 /* We do everything in ax_tmp until we've checked the authentication
1856 so we don't clobber anything we care about by accident. */
1859 /* Update 'ax' by the new key material */
1860 ret = update_ax_by_kx (&ax_tmp,
1861 GCP_get_id (t->destination),
1862 &msg->kx.ephemeral_key,
1863 &msg->kx.ratchet_key);
1864 if (GNUNET_OK != ret)
1866 if (GNUNET_NO == ret)
1867 GNUNET_STATISTICS_update (stats,
1868 "# redundant KX_AUTH received",
1872 GNUNET_break (0); /* connect to self!? */
1875 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1878 if (0 != memcmp (&kx_auth,
1882 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1883 we transmitted to the sender, refuse it, try KX again. */
1884 GNUNET_STATISTICS_update (stats,
1885 "# KX_AUTH not using our last KX received (auth failure)",
1893 /* Yep, we're good. */
1895 if (NULL != t->unverified_ax)
1897 /* We got some "stale" KX before, drop that. */
1898 cleanup_ax (t->unverified_ax);
1899 GNUNET_free (t->unverified_ax);
1900 t->unverified_ax = NULL;
1903 /* move ahead in our state machine */
1906 case CADET_TUNNEL_KEY_UNINITIALIZED:
1907 case CADET_TUNNEL_KEY_AX_RECV:
1908 /* Checked above, this is impossible. */
1911 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1912 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1913 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1914 GCT_change_estate (t,
1915 CADET_TUNNEL_KEY_OK);
1917 case CADET_TUNNEL_KEY_OK:
1918 /* Did not expect another KX_AUTH, but so what, still acceptable.
1919 Nothing to do here. */
1926 /* ************************************** end core crypto ***************************** */
1930 * Compute the next free channel tunnel number for this tunnel.
1932 * @param t the tunnel
1933 * @return unused number that can uniquely identify a channel in the tunnel
1935 static struct GNUNET_CADET_ChannelTunnelNumber
1936 get_next_free_ctn (struct CadetTunnel *t)
1938 #define HIGH_BIT 0x8000000
1939 struct GNUNET_CADET_ChannelTunnelNumber ret;
1944 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1945 GCP_get_id (GCT_get_destination (t)));
1951 GNUNET_assert (0); // loopback must never go here!
1952 ctn = ntohl (t->next_ctn.cn);
1954 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1957 ctn = ((ctn + 1) & (~ HIGH_BIT));
1959 t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
1960 ret.cn = htonl (ctn | highbit);
1966 * Add a channel to a tunnel, and notify channel that we are ready
1967 * for transmission if we are already up. Otherwise that notification
1968 * will be done later in #notify_tunnel_up_cb().
1972 * @return unique number identifying @a ch within @a t
1974 struct GNUNET_CADET_ChannelTunnelNumber
1975 GCT_add_channel (struct CadetTunnel *t,
1976 struct CadetChannel *ch)
1978 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1980 ctn = get_next_free_ctn (t);
1981 if (NULL != t->destroy_task)
1983 GNUNET_SCHEDULER_cancel (t->destroy_task);
1984 t->destroy_task = NULL;
1986 GNUNET_assert (GNUNET_YES ==
1987 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1990 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1991 LOG (GNUNET_ERROR_TYPE_DEBUG,
1992 "Adding %s to %s\n",
1997 case CADET_TUNNEL_KEY_UNINITIALIZED:
1998 /* waiting for connection to start KX */
2000 case CADET_TUNNEL_KEY_AX_RECV:
2001 case CADET_TUNNEL_KEY_AX_SENT:
2002 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2003 /* we're currently waiting for KX to complete */
2005 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2006 /* waiting for OTHER peer to send us data,
2007 we might need to prompt more aggressively! */
2008 if (NULL == t->kx_task)
2010 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2014 case CADET_TUNNEL_KEY_OK:
2015 /* We are ready. Tell the new channel that we are up. */
2016 GCCH_tunnel_up (ch);
2024 * We lost a connection, remove it from our list and clean up
2025 * the connection object itself.
2027 * @param ct binding of connection to tunnel of the connection that was lost.
2030 GCT_connection_lost (struct CadetTConnection *ct)
2032 struct CadetTunnel *t = ct->t;
2034 if (GNUNET_YES == ct->is_ready)
2036 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
2037 t->connection_ready_tail,
2039 t->num_ready_connections--;
2043 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2044 t->connection_busy_tail,
2046 t->num_busy_connections--;
2053 * Clean up connection @a ct of a tunnel.
2055 * @param cls the `struct CadetTunnel`
2056 * @param ct connection to clean up
2059 destroy_t_connection (void *cls,
2060 struct CadetTConnection *ct)
2062 struct CadetTunnel *t = cls;
2063 struct CadetConnection *cc = ct->cc;
2065 GNUNET_assert (ct->t == t);
2066 GCT_connection_lost (ct);
2067 GCC_destroy_without_tunnel (cc);
2072 * This tunnel is no longer used, destroy it.
2074 * @param cls the idle tunnel
2077 destroy_tunnel (void *cls)
2079 struct CadetTunnel *t = cls;
2080 struct CadetTunnelQueueEntry *tq;
2082 t->destroy_task = NULL;
2083 LOG (GNUNET_ERROR_TYPE_DEBUG,
2084 "Destroying idle %s\n",
2086 GNUNET_assert (0 == GCT_count_channels (t));
2087 GCT_iterate_connections (t,
2088 &destroy_t_connection,
2090 GNUNET_assert (NULL == t->connection_ready_head);
2091 GNUNET_assert (NULL == t->connection_busy_head);
2092 while (NULL != (tq = t->tq_head))
2094 if (NULL != tq->cont)
2095 tq->cont (tq->cont_cls,
2097 GCT_send_cancel (tq);
2099 GCP_drop_tunnel (t->destination,
2101 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2102 if (NULL != t->maintain_connections_task)
2104 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2105 t->maintain_connections_task = NULL;
2107 if (NULL != t->send_task)
2109 GNUNET_SCHEDULER_cancel (t->send_task);
2110 t->send_task = NULL;
2112 if (NULL != t->kx_task)
2114 GNUNET_SCHEDULER_cancel (t->kx_task);
2117 GNUNET_MST_destroy (t->mst);
2118 GNUNET_MQ_destroy (t->mq);
2119 if (NULL != t->unverified_ax)
2121 cleanup_ax (t->unverified_ax);
2122 GNUNET_free (t->unverified_ax);
2124 cleanup_ax (&t->ax);
2125 GNUNET_assert (NULL == t->destroy_task);
2131 * Remove a channel from a tunnel.
2135 * @param ctn unique number identifying @a ch within @a t
2138 GCT_remove_channel (struct CadetTunnel *t,
2139 struct CadetChannel *ch,
2140 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2142 LOG (GNUNET_ERROR_TYPE_DEBUG,
2143 "Removing %s from %s\n",
2146 GNUNET_assert (GNUNET_YES ==
2147 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2151 GCT_count_channels (t)) &&
2152 (NULL == t->destroy_task) )
2155 = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2163 * Destroy remaining channels during shutdown.
2165 * @param cls the `struct CadetTunnel` of the channel
2166 * @param key key of the channel
2167 * @param value the `struct CadetChannel`
2168 * @return #GNUNET_OK (continue to iterate)
2171 destroy_remaining_channels (void *cls,
2175 struct CadetChannel *ch = value;
2177 GCCH_handle_remote_destroy (ch,
2184 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2186 * @param t tunnel to destroy
2189 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2191 GNUNET_assert (GNUNET_YES == shutting_down);
2192 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2193 &destroy_remaining_channels,
2196 GCT_count_channels (t));
2197 if (NULL != t->destroy_task)
2199 GNUNET_SCHEDULER_cancel (t->destroy_task);
2200 t->destroy_task = NULL;
2207 * Send normal payload from queue in @a t via connection @a ct.
2208 * Does nothing if our payload queue is empty.
2210 * @param t tunnel to send data from
2211 * @param ct connection to use for transmission (is ready)
2214 try_send_normal_payload (struct CadetTunnel *t,
2215 struct CadetTConnection *ct)
2217 struct CadetTunnelQueueEntry *tq;
2219 GNUNET_assert (GNUNET_YES == ct->is_ready);
2223 /* no messages pending right now */
2224 LOG (GNUNET_ERROR_TYPE_DEBUG,
2225 "Not sending payload of %s on ready %s (nothing pending)\n",
2230 /* ready to send message 'tq' on tunnel 'ct' */
2231 GNUNET_assert (t == tq->t);
2232 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2235 if (NULL != tq->cid)
2236 *tq->cid = *GCC_get_id (ct->cc);
2237 mark_connection_unready (ct);
2238 LOG (GNUNET_ERROR_TYPE_DEBUG,
2239 "Sending payload of %s on %s\n",
2242 GCC_transmit (ct->cc,
2244 if (NULL != tq->cont)
2245 tq->cont (tq->cont_cls,
2246 GCC_get_id (ct->cc));
2252 * A connection is @a is_ready for transmission. Looks at our message
2253 * queue and if there is a message, sends it out via the connection.
2255 * @param cls the `struct CadetTConnection` that is @a is_ready
2256 * @param is_ready #GNUNET_YES if connection are now ready,
2257 * #GNUNET_NO if connection are no longer ready
2260 connection_ready_cb (void *cls,
2263 struct CadetTConnection *ct = cls;
2264 struct CadetTunnel *t = ct->t;
2266 if (GNUNET_NO == is_ready)
2268 LOG (GNUNET_ERROR_TYPE_DEBUG,
2269 "%s no longer ready for %s\n",
2272 mark_connection_unready (ct);
2275 GNUNET_assert (GNUNET_NO == ct->is_ready);
2276 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2277 t->connection_busy_tail,
2279 GNUNET_assert (0 < t->num_busy_connections);
2280 t->num_busy_connections--;
2281 ct->is_ready = GNUNET_YES;
2282 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2283 t->connection_ready_tail,
2285 t->num_ready_connections++;
2287 LOG (GNUNET_ERROR_TYPE_DEBUG,
2288 "%s now ready for %s in state %s\n",
2291 estate2s (t->estate));
2294 case CADET_TUNNEL_KEY_UNINITIALIZED:
2295 /* Do not begin KX if WE have no channels waiting! */
2296 if (0 == GCT_count_channels (t))
2298 /* We are uninitialized, just transmit immediately,
2299 without undue delay. */
2300 if (NULL != t->kx_task)
2302 GNUNET_SCHEDULER_cancel (t->kx_task);
2309 case CADET_TUNNEL_KEY_AX_RECV:
2310 case CADET_TUNNEL_KEY_AX_SENT:
2311 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2312 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2313 /* we're currently waiting for KX to complete, schedule job */
2314 if (NULL == t->kx_task)
2316 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2320 case CADET_TUNNEL_KEY_OK:
2321 if (GNUNET_YES == t->kx_auth_requested)
2323 if (NULL != t->kx_task)
2325 GNUNET_SCHEDULER_cancel (t->kx_task);
2334 try_send_normal_payload (t,
2342 * Called when either we have a new connection, or a new message in the
2343 * queue, or some existing connection has transmission capacity. Looks
2344 * at our message queue and if there is a message, picks a connection
2347 * @param cls the `struct CadetTunnel` to process messages on
2350 trigger_transmissions (void *cls)
2352 struct CadetTunnel *t = cls;
2353 struct CadetTConnection *ct;
2355 t->send_task = NULL;
2356 if (NULL == t->tq_head)
2357 return; /* no messages pending right now */
2358 ct = get_ready_connection (t);
2360 return; /* no connections ready */
2361 try_send_normal_payload (t,
2367 * Closure for #evaluate_connection. Used to assemble summary information
2368 * about the existing connections so we can evaluate a new path.
2370 struct EvaluationSummary
2374 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2376 unsigned int min_length;
2379 * Maximum length of any of our connections, 0 if we have none.
2381 unsigned int max_length;
2384 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2386 GNUNET_CONTAINER_HeapCostType min_desire;
2389 * Maximum desirability of any of our connections, 0 if we have none.
2391 GNUNET_CONTAINER_HeapCostType max_desire;
2394 * Path we are comparing against for #evaluate_connection, can be NULL.
2396 struct CadetPeerPath *path;
2399 * Connection deemed the "worst" so far encountered by #evaluate_connection,
2400 * NULL if we did not yet encounter any connections.
2402 struct CadetTConnection *worst;
2405 * Numeric score of @e worst, only set if @e worst is non-NULL.
2410 * Set to #GNUNET_YES if we have a connection over @e path already.
2418 * Evaluate a connection, updating our summary information in @a cls about
2419 * what kinds of connections we have.
2421 * @param cls the `struct EvaluationSummary *` to update
2422 * @param ct a connection to include in the summary
2425 evaluate_connection (void *cls,
2426 struct CadetTConnection *ct)
2428 struct EvaluationSummary *es = cls;
2429 struct CadetConnection *cc = ct->cc;
2430 struct CadetPeerPath *ps = GCC_get_path (cc);
2431 const struct CadetConnectionMetrics *metrics;
2432 GNUNET_CONTAINER_HeapCostType ct_desirability;
2433 struct GNUNET_TIME_Relative uptime;
2434 struct GNUNET_TIME_Relative last_use;
2437 double success_rate;
2441 LOG (GNUNET_ERROR_TYPE_DEBUG,
2442 "Ignoring duplicate path %s.\n",
2443 GCPP_2s (es->path));
2444 es->duplicate = GNUNET_YES;
2447 ct_desirability = GCPP_get_desirability (ps);
2448 ct_length = GCPP_get_length (ps);
2449 metrics = GCC_get_metrics (cc);
2450 uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2451 last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2452 /* We add 1.0 here to avoid division by zero. */
2453 success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2456 + 100.0 / (1.0 + ct_length) /* longer paths = better */
2457 + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2458 - last_use.rel_value_us / 1000L; /* longer idle = worse */
2459 score *= success_rate; /* weigh overall by success rate */
2461 if ( (NULL == es->worst) ||
2462 (score < es->worst_score) )
2465 es->worst_score = score;
2467 es->min_length = GNUNET_MIN (es->min_length,
2469 es->max_length = GNUNET_MAX (es->max_length,
2471 es->min_desire = GNUNET_MIN (es->min_desire,
2473 es->max_desire = GNUNET_MAX (es->max_desire,
2479 * Consider using the path @a p for the tunnel @a t.
2480 * The tunnel destination is at offset @a off in path @a p.
2482 * @param cls our tunnel
2483 * @param path a path to our destination
2484 * @param off offset of the destination on path @a path
2485 * @return #GNUNET_YES (should keep iterating)
2488 consider_path_cb (void *cls,
2489 struct CadetPeerPath *path,
2492 struct CadetTunnel *t = cls;
2493 struct EvaluationSummary es;
2494 struct CadetTConnection *ct;
2496 GNUNET_assert (off < GCPP_get_length (path));
2497 es.min_length = UINT_MAX;
2500 es.min_desire = UINT64_MAX;
2502 es.duplicate = GNUNET_NO;
2505 /* Compute evaluation summary over existing connections. */
2506 GCT_iterate_connections (t,
2507 &evaluate_connection,
2509 if (GNUNET_YES == es.duplicate)
2512 /* FIXME: not sure we should really just count
2513 'num_connections' here, as they may all have
2514 consistently failed to connect. */
2516 /* We iterate by increasing path length; if we have enough paths and
2517 this one is more than twice as long than what we are currently
2518 using, then ignore all of these super-long ones! */
2519 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2520 (es.min_length * 2 < off) &&
2521 (es.max_length < off) )
2523 LOG (GNUNET_ERROR_TYPE_DEBUG,
2524 "Ignoring paths of length %u, they are way too long.\n",
2528 /* If we have enough paths and this one looks no better, ignore it. */
2529 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2530 (es.min_length < GCPP_get_length (path)) &&
2531 (es.min_desire > GCPP_get_desirability (path)) &&
2532 (es.max_length < off) )
2534 LOG (GNUNET_ERROR_TYPE_DEBUG,
2535 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2536 GCPP_get_length (path),
2537 (unsigned long long) GCPP_get_desirability (path),
2538 GCP_2s (t->destination));
2542 /* Path is interesting (better by some metric, or we don't have
2543 enough paths yet). */
2544 ct = GNUNET_new (struct CadetTConnection);
2545 ct->created = GNUNET_TIME_absolute_get ();
2547 ct->cc = GCC_create (t->destination,
2550 GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2552 &connection_ready_cb,
2555 /* FIXME: schedule job to kill connection (and path?) if it takes
2556 too long to get ready! (And track performance data on how long
2557 other connections took with the tunnel!)
2558 => Note: to be done within 'connection'-logic! */
2559 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2560 t->connection_busy_tail,
2562 t->num_busy_connections++;
2563 LOG (GNUNET_ERROR_TYPE_DEBUG,
2564 "Found interesting path %s for %s, created %s\n",
2573 * Function called to maintain the connections underlying our tunnel.
2574 * Tries to maintain (incl. tear down) connections for the tunnel, and
2575 * if there is a significant change, may trigger transmissions.
2577 * Basically, needs to check if there are connections that perform
2578 * badly, and if so eventually kill them and trigger a replacement.
2579 * The strategy is to open one more connection than
2580 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2581 * least-performing one, and then inquire for new ones.
2583 * @param cls the `struct CadetTunnel`
2586 maintain_connections_cb (void *cls)
2588 struct CadetTunnel *t = cls;
2589 struct GNUNET_TIME_Relative delay;
2590 struct EvaluationSummary es;
2592 t->maintain_connections_task = NULL;
2593 LOG (GNUNET_ERROR_TYPE_DEBUG,
2594 "Performing connection maintenance for %s.\n",
2597 es.min_length = UINT_MAX;
2600 es.min_desire = UINT64_MAX;
2603 es.duplicate = GNUNET_NO;
2604 GCT_iterate_connections (t,
2605 &evaluate_connection,
2607 if ( (NULL != es.worst) &&
2608 (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2610 /* Clear out worst-performing connection 'es.worst'. */
2611 destroy_t_connection (t,
2615 /* Consider additional paths */
2616 (void) GCP_iterate_paths (t->destination,
2620 /* FIXME: calculate when to try again based on how well we are doing;
2621 in particular, if we have to few connections, we might be able
2622 to do without this (as PATHS should tell us whenever a new path
2623 is available instantly; however, need to make sure this job is
2624 restarted after that happens).
2625 Furthermore, if the paths we do know are in a reasonably narrow
2626 quality band and are plentyful, we might also consider us stabilized
2627 and then reduce the frequency accordingly. */
2628 delay = GNUNET_TIME_UNIT_MINUTES;
2629 t->maintain_connections_task
2630 = GNUNET_SCHEDULER_add_delayed (delay,
2631 &maintain_connections_cb,
2637 * Consider using the path @a p for the tunnel @a t.
2638 * The tunnel destination is at offset @a off in path @a p.
2640 * @param cls our tunnel
2641 * @param path a path to our destination
2642 * @param off offset of the destination on path @a path
2645 GCT_consider_path (struct CadetTunnel *t,
2646 struct CadetPeerPath *p,
2649 LOG (GNUNET_ERROR_TYPE_DEBUG,
2650 "Considering %s for %s\n",
2653 (void) consider_path_cb (t,
2660 * We got a keepalive. Track in statistics.
2662 * @param cls the `struct CadetTunnel` for which we decrypted the message
2663 * @param msg the message we received on the tunnel
2666 handle_plaintext_keepalive (void *cls,
2667 const struct GNUNET_MessageHeader *msg)
2669 struct CadetTunnel *t = cls;
2671 LOG (GNUNET_ERROR_TYPE_DEBUG,
2672 "Received KEEPALIVE on %s\n",
2674 GNUNET_STATISTICS_update (stats,
2675 "# keepalives received",
2682 * Check that @a msg is well-formed.
2684 * @param cls the `struct CadetTunnel` for which we decrypted the message
2685 * @param msg the message we received on the tunnel
2686 * @return #GNUNET_OK (any variable-size payload goes)
2689 check_plaintext_data (void *cls,
2690 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2697 * We received payload data for a channel. Locate the channel
2698 * and process the data, or return an error if the channel is unknown.
2700 * @param cls the `struct CadetTunnel` for which we decrypted the message
2701 * @param msg the message we received on the tunnel
2704 handle_plaintext_data (void *cls,
2705 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2707 struct CadetTunnel *t = cls;
2708 struct CadetChannel *ch;
2710 ch = lookup_channel (t,
2714 /* We don't know about such a channel, might have been destroyed on our
2715 end in the meantime, or never existed. Send back a DESTROY. */
2716 LOG (GNUNET_ERROR_TYPE_DEBUG,
2717 "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2718 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2719 ntohl (msg->ctn.cn));
2720 GCT_send_channel_destroy (t,
2724 GCCH_handle_channel_plaintext_data (ch,
2725 GCC_get_id (t->current_ct->cc),
2731 * We received an acknowledgement for data we sent on a channel.
2732 * Locate the channel and process it, or return an error if the
2733 * channel is unknown.
2735 * @param cls the `struct CadetTunnel` for which we decrypted the message
2736 * @param ack the message we received on the tunnel
2739 handle_plaintext_data_ack (void *cls,
2740 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2742 struct CadetTunnel *t = cls;
2743 struct CadetChannel *ch;
2745 ch = lookup_channel (t,
2749 /* We don't know about such a channel, might have been destroyed on our
2750 end in the meantime, or never existed. Send back a DESTROY. */
2751 LOG (GNUNET_ERROR_TYPE_DEBUG,
2752 "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2753 ntohl (ack->ctn.cn));
2754 GCT_send_channel_destroy (t,
2758 GCCH_handle_channel_plaintext_data_ack (ch,
2759 GCC_get_id (t->current_ct->cc),
2765 * We have received a request to open a channel to a port from
2766 * another peer. Creates the incoming channel.
2768 * @param cls the `struct CadetTunnel` for which we decrypted the message
2769 * @param copen the message we received on the tunnel
2772 handle_plaintext_channel_open (void *cls,
2773 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2775 struct CadetTunnel *t = cls;
2776 struct CadetChannel *ch;
2778 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2779 ntohl (copen->ctn.cn));
2782 LOG (GNUNET_ERROR_TYPE_DEBUG,
2783 "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n",
2784 GNUNET_h2s (&copen->h_port),
2787 GCCH_handle_duplicate_open (ch,
2788 GCC_get_id (t->current_ct->cc));
2791 LOG (GNUNET_ERROR_TYPE_DEBUG,
2792 "Received CHANNEL_OPEN on h_port %s from %s\n",
2793 GNUNET_h2s (&copen->h_port),
2795 ch = GCCH_channel_incoming_new (t,
2798 ntohl (copen->opt));
2799 if (NULL != t->destroy_task)
2801 GNUNET_SCHEDULER_cancel (t->destroy_task);
2802 t->destroy_task = NULL;
2804 GNUNET_assert (GNUNET_OK ==
2805 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2806 ntohl (copen->ctn.cn),
2808 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2813 * Send a DESTROY message via the tunnel.
2815 * @param t the tunnel to transmit over
2816 * @param ctn ID of the channel to destroy
2819 GCT_send_channel_destroy (struct CadetTunnel *t,
2820 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2822 struct GNUNET_CADET_ChannelDestroyMessage msg;
2824 LOG (GNUNET_ERROR_TYPE_DEBUG,
2825 "Sending DESTORY message for channel ID %u\n",
2827 msg.header.size = htons (sizeof (msg));
2828 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2829 msg.reserved = htonl (0);
2839 * We have received confirmation from the target peer that the
2840 * given channel could be established (the port is open).
2843 * @param cls the `struct CadetTunnel` for which we decrypted the message
2844 * @param cm the message we received on the tunnel
2847 handle_plaintext_channel_open_ack (void *cls,
2848 const struct GNUNET_CADET_ChannelOpenAckMessage *cm)
2850 struct CadetTunnel *t = cls;
2851 struct CadetChannel *ch;
2853 ch = lookup_channel (t,
2857 /* We don't know about such a channel, might have been destroyed on our
2858 end in the meantime, or never existed. Send back a DESTROY. */
2859 LOG (GNUNET_ERROR_TYPE_DEBUG,
2860 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2861 ntohl (cm->ctn.cn));
2862 GCT_send_channel_destroy (t,
2866 LOG (GNUNET_ERROR_TYPE_DEBUG,
2867 "Received channel OPEN_ACK on channel %s from %s\n",
2870 GCCH_handle_channel_open_ack (ch,
2871 GCC_get_id (t->current_ct->cc),
2877 * We received a message saying that a channel should be destroyed.
2878 * Pass it on to the correct channel.
2880 * @param cls the `struct CadetTunnel` for which we decrypted the message
2881 * @param cm the message we received on the tunnel
2884 handle_plaintext_channel_destroy (void *cls,
2885 const struct GNUNET_CADET_ChannelDestroyMessage *cm)
2887 struct CadetTunnel *t = cls;
2888 struct CadetChannel *ch;
2890 ch = lookup_channel (t,
2894 /* We don't know about such a channel, might have been destroyed on our
2895 end in the meantime, or never existed. */
2896 LOG (GNUNET_ERROR_TYPE_DEBUG,
2897 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2898 ntohl (cm->ctn.cn));
2901 LOG (GNUNET_ERROR_TYPE_DEBUG,
2902 "Received channel DESTROY on %s from %s\n",
2905 GCCH_handle_remote_destroy (ch,
2906 GCC_get_id (t->current_ct->cc));
2911 * Handles a message we decrypted, by injecting it into
2912 * our message queue (which will do the dispatching).
2914 * @param cls the `struct CadetTunnel` that got the message
2915 * @param msg the message
2916 * @return #GNUNET_OK on success (always)
2917 * #GNUNET_NO to stop further processing (no error)
2918 * #GNUNET_SYSERR to stop further processing with error
2921 handle_decrypted (void *cls,
2922 const struct GNUNET_MessageHeader *msg)
2924 struct CadetTunnel *t = cls;
2926 GNUNET_assert (NULL != t->current_ct);
2927 GNUNET_MQ_inject_message (t->mq,
2934 * Function called if we had an error processing
2935 * an incoming decrypted message.
2937 * @param cls the `struct CadetTunnel`
2938 * @param error error code
2941 decrypted_error_cb (void *cls,
2942 enum GNUNET_MQ_Error error)
2944 GNUNET_break_op (0);
2949 * Create a tunnel to @a destionation. Must only be called
2950 * from within #GCP_get_tunnel().
2952 * @param destination where to create the tunnel to
2953 * @return new tunnel to @a destination
2955 struct CadetTunnel *
2956 GCT_create_tunnel (struct CadetPeer *destination)
2958 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2959 struct GNUNET_MQ_MessageHandler handlers[] = {
2960 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2961 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2962 struct GNUNET_MessageHeader,
2964 GNUNET_MQ_hd_var_size (plaintext_data,
2965 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2966 struct GNUNET_CADET_ChannelAppDataMessage,
2968 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2969 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2970 struct GNUNET_CADET_ChannelDataAckMessage,
2972 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2973 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2974 struct GNUNET_CADET_ChannelOpenMessage,
2976 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2977 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2978 struct GNUNET_CADET_ChannelOpenAckMessage,
2980 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2981 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2982 struct GNUNET_CADET_ChannelDestroyMessage,
2984 GNUNET_MQ_handler_end ()
2987 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2988 new_ephemeral (&t->ax);
2989 GNUNET_assert (GNUNET_OK ==
2990 GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2991 t->destination = destination;
2992 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2993 t->maintain_connections_task
2994 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2996 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
3001 &decrypted_error_cb,
3003 t->mst = GNUNET_MST_create (&handle_decrypted,
3010 * Add a @a connection to the @a tunnel.
3013 * @param cid connection identifer to use for the connection
3014 * @param options options for the connection
3015 * @param path path to use for the connection
3016 * @return #GNUNET_OK on success,
3017 * #GNUNET_SYSERR on failure (duplicate connection)
3020 GCT_add_inbound_connection (struct CadetTunnel *t,
3021 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
3022 enum GNUNET_CADET_ChannelOption options,
3023 struct CadetPeerPath *path)
3025 struct CadetTConnection *ct;
3027 ct = GNUNET_new (struct CadetTConnection);
3028 ct->created = GNUNET_TIME_absolute_get ();
3030 ct->cc = GCC_create_inbound (t->destination,
3035 &connection_ready_cb,
3039 LOG (GNUNET_ERROR_TYPE_DEBUG,
3040 "%s refused inbound %s (duplicate)\n",
3044 return GNUNET_SYSERR;
3046 /* FIXME: schedule job to kill connection (and path?) if it takes
3047 too long to get ready! (And track performance data on how long
3048 other connections took with the tunnel!)
3049 => Note: to be done within 'connection'-logic! */
3050 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
3051 t->connection_busy_tail,
3053 t->num_busy_connections++;
3054 LOG (GNUNET_ERROR_TYPE_DEBUG,
3063 * Handle encrypted message.
3065 * @param ct connection/tunnel combo that received encrypted message
3066 * @param msg the encrypted message to decrypt
3069 GCT_handle_encrypted (struct CadetTConnection *ct,
3070 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3072 struct CadetTunnel *t = ct->t;
3073 uint16_t size = ntohs (msg->header.size);
3074 char cbuf [size] GNUNET_ALIGN;
3075 ssize_t decrypted_size;
3077 LOG (GNUNET_ERROR_TYPE_DEBUG,
3078 "%s received %u bytes of encrypted data in state %d\n",
3080 (unsigned int) size,
3085 case CADET_TUNNEL_KEY_UNINITIALIZED:
3086 case CADET_TUNNEL_KEY_AX_RECV:
3087 /* We did not even SEND our KX, how can the other peer
3088 send us encrypted data? Must have been that we went
3089 down and the other peer still things we are up.
3090 Let's send it KX back. */
3091 GNUNET_STATISTICS_update (stats,
3092 "# received encrypted without any KX",
3095 if (NULL != t->kx_task)
3097 GNUNET_SCHEDULER_cancel (t->kx_task);
3104 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3105 /* We send KX, and other peer send KX to us at the same time.
3106 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3107 GNUNET_STATISTICS_update (stats,
3108 "# received encrypted without KX_AUTH",
3111 if (NULL != t->kx_task)
3113 GNUNET_SCHEDULER_cancel (t->kx_task);
3121 case CADET_TUNNEL_KEY_AX_SENT:
3122 /* We did not get the KX of the other peer, but that
3123 might have been lost. Send our KX again immediately. */
3124 GNUNET_STATISTICS_update (stats,
3125 "# received encrypted without KX",
3128 if (NULL != t->kx_task)
3130 GNUNET_SCHEDULER_cancel (t->kx_task);
3137 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3138 /* Great, first payload, we might graduate to OK! */
3139 case CADET_TUNNEL_KEY_OK:
3140 /* We are up and running, all good. */
3144 decrypted_size = -1;
3145 if (CADET_TUNNEL_KEY_OK == t->estate)
3147 /* We have well-established key material available,
3148 try that. (This is the common case.) */
3149 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3155 if ( (-1 == decrypted_size) &&
3156 (NULL != t->unverified_ax) )
3158 /* We have un-authenticated KX material available. We should try
3159 this as a back-up option, in case the sender crashed and
3161 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3165 if (-1 != decrypted_size)
3167 /* It worked! Treat this as authentication of the AX data! */
3168 cleanup_ax (&t->ax);
3169 t->ax = *t->unverified_ax;
3170 GNUNET_free (t->unverified_ax);
3171 t->unverified_ax = NULL;
3173 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3175 /* First time it worked, move tunnel into production! */
3176 GCT_change_estate (t,
3177 CADET_TUNNEL_KEY_OK);
3178 if (NULL != t->send_task)
3179 GNUNET_SCHEDULER_cancel (t->send_task);
3180 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3184 if (NULL != t->unverified_ax)
3186 /* We had unverified KX material that was useless; so increment
3187 counter and eventually move to ignore it. Note that we even do
3188 this increment if we successfully decrypted with the old KX
3189 material and thus didn't even both with the new one. This is
3190 the ideal case, as a malicious injection of bogus KX data
3191 basically only causes us to increment a counter a few times. */
3192 t->unverified_attempts++;
3193 LOG (GNUNET_ERROR_TYPE_DEBUG,
3194 "Failed to decrypt message with unverified KX data %u times\n",
3195 t->unverified_attempts);
3196 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3198 cleanup_ax (t->unverified_ax);
3199 GNUNET_free (t->unverified_ax);
3200 t->unverified_ax = NULL;
3204 if (-1 == decrypted_size)
3206 /* Decryption failed for good, complain. */
3207 LOG (GNUNET_ERROR_TYPE_WARNING,
3208 "%s failed to decrypt and validate encrypted data, retrying KX\n",
3210 GNUNET_STATISTICS_update (stats,
3211 "# unable to decrypt",
3214 if (NULL != t->kx_task)
3216 GNUNET_SCHEDULER_cancel (t->kx_task);
3224 GNUNET_STATISTICS_update (stats,
3225 "# decrypted bytes",
3229 /* The MST will ultimately call #handle_decrypted() on each message. */
3231 GNUNET_break_op (GNUNET_OK ==
3232 GNUNET_MST_from_buffer (t->mst,
3237 t->current_ct = NULL;
3242 * Sends an already built message on a tunnel, encrypting it and
3243 * choosing the best connection if not provided.
3245 * @param message Message to send. Function modifies it.
3246 * @param t Tunnel on which this message is transmitted.
3247 * @param cont Continuation to call once message is really sent.
3248 * @param cont_cls Closure for @c cont.
3249 * @return Handle to cancel message
3251 struct CadetTunnelQueueEntry *
3252 GCT_send (struct CadetTunnel *t,
3253 const struct GNUNET_MessageHeader *message,
3254 GCT_SendContinuation cont,
3257 struct CadetTunnelQueueEntry *tq;
3258 uint16_t payload_size;
3259 struct GNUNET_MQ_Envelope *env;
3260 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3262 if (CADET_TUNNEL_KEY_OK != t->estate)
3267 payload_size = ntohs (message->size);
3268 LOG (GNUNET_ERROR_TYPE_DEBUG,
3269 "Encrypting %u bytes for %s\n",
3270 (unsigned int) payload_size,
3272 env = GNUNET_MQ_msg_extra (ax_msg,
3274 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3275 t_ax_encrypt (&t->ax,
3279 GNUNET_STATISTICS_update (stats,
3280 "# encrypted bytes",
3283 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3284 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3285 /* FIXME: we should do this once, not once per message;
3286 this is a point multiplication, and DHRs does not
3287 change all the time. */
3288 GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3289 &ax_msg->ax_header.DHRs);
3290 t_h_encrypt (&t->ax,
3292 t_hmac (&ax_msg->ax_header,
3293 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3298 tq = GNUNET_malloc (sizeof (*tq));
3301 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3303 tq->cont_cls = cont_cls;
3304 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3307 if (NULL != t->send_task)
3308 GNUNET_SCHEDULER_cancel (t->send_task);
3310 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3317 * Cancel a previously sent message while it's in the queue.
3319 * ONLY can be called before the continuation given to the send
3320 * function is called. Once the continuation is called, the message is
3321 * no longer in the queue!
3323 * @param tq Handle to the queue entry to cancel.
3326 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3328 struct CadetTunnel *t = tq->t;
3330 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3333 GNUNET_MQ_discard (tq->env);
3339 * Iterate over all connections of a tunnel.
3341 * @param t Tunnel whose connections to iterate.
3342 * @param iter Iterator.
3343 * @param iter_cls Closure for @c iter.
3346 GCT_iterate_connections (struct CadetTunnel *t,
3347 GCT_ConnectionIterator iter,
3350 struct CadetTConnection *n;
3351 for (struct CadetTConnection *ct = t->connection_ready_head;
3359 for (struct CadetTConnection *ct = t->connection_busy_head;
3371 * Closure for #iterate_channels_cb.
3378 GCT_ChannelIterator iter;
3381 * Closure for @e iter.
3388 * Helper function for #GCT_iterate_channels.
3390 * @param cls the `struct ChanIterCls`
3392 * @param value a `struct CadetChannel`
3393 * @return #GNUNET_OK
3396 iterate_channels_cb (void *cls,
3400 struct ChanIterCls *ctx = cls;
3401 struct CadetChannel *ch = value;
3403 ctx->iter (ctx->iter_cls,
3410 * Iterate over all channels of a tunnel.
3412 * @param t Tunnel whose channels to iterate.
3413 * @param iter Iterator.
3414 * @param iter_cls Closure for @c iter.
3417 GCT_iterate_channels (struct CadetTunnel *t,
3418 GCT_ChannelIterator iter,
3421 struct ChanIterCls ctx;
3424 ctx.iter_cls = iter_cls;
3425 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3426 &iterate_channels_cb,
3433 * Call #GCCH_debug() on a channel.
3435 * @param cls points to the log level to use
3437 * @param value the `struct CadetChannel` to dump
3438 * @return #GNUNET_OK (continue iteration)
3441 debug_channel (void *cls,
3445 const enum GNUNET_ErrorType *level = cls;
3446 struct CadetChannel *ch = value;
3448 GCCH_debug (ch, *level);
3453 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3457 * Log all possible info about the tunnel state.
3459 * @param t Tunnel to debug.
3460 * @param level Debug level to use.
3463 GCT_debug (const struct CadetTunnel *t,
3464 enum GNUNET_ErrorType level)
3466 #if !defined(GNUNET_CULL_LOGGING)
3467 struct CadetTConnection *iter_c;
3470 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3472 __FILE__, __FUNCTION__, __LINE__);
3477 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3479 estate2s (t->estate),
3481 GCT_count_any_connections (t));
3484 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3488 "TTT connections:\n");
3489 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3490 GCC_debug (iter_c->cc,
3492 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3493 GCC_debug (iter_c->cc,
3497 "TTT TUNNEL END\n");
3502 /* end of gnunet-service-cadet_tunnels.c */