2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
27 * - proper connection evaluation during connection management:
28 * + when managing connections, distinguish those that
29 * have (recently) had traffic from those that were
30 * never ready (or not recently)
31 * + consider quality of current connection set when deciding
32 * how often to do maintenance
33 * + interact with PEER to drive DHT GET/PUT operations based
34 * on how much we like our connections
37 #include "gnunet_util_lib.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet-service-cadet-new.h"
41 #include "cadet_protocol.h"
42 #include "gnunet-service-cadet-new_channel.h"
43 #include "gnunet-service-cadet-new_connection.h"
44 #include "gnunet-service-cadet-new_tunnels.h"
45 #include "gnunet-service-cadet-new_peer.h"
46 #include "gnunet-service-cadet-new_paths.h"
49 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
52 * How often do we try to decrypt payload with unverified key
53 * material? Used to limit CPU increase upon receiving bogus
56 #define MAX_UNVERIFIED_ATTEMPTS 16
59 * How long do we wait until tearing down an idle tunnel?
61 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
64 * How long do we wait initially before retransmitting the KX?
65 * TODO: replace by 2 RTT if/once we have connection-level RTT data!
67 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
70 * Maximum number of skipped keys we keep in memory per tunnel.
72 #define MAX_SKIPPED_KEYS 64
75 * Maximum number of keys (and thus ratchet steps) we are willing to
76 * skip before we decide this is either a bogus packet or a DoS-attempt.
78 #define MAX_KEY_GAP 256
82 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
84 struct CadetTunnelSkippedKey
89 struct CadetTunnelSkippedKey *next;
94 struct CadetTunnelSkippedKey *prev;
97 * When was this key stored (for timeout).
99 struct GNUNET_TIME_Absolute timestamp;
104 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
109 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
112 * Key number for a given HK.
119 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
121 struct CadetTunnelAxolotl
124 * A (double linked) list of stored message keys and associated header keys
125 * for "skipped" messages, i.e. messages that have not been
126 * received despite the reception of more recent messages, (head).
128 struct CadetTunnelSkippedKey *skipped_head;
131 * Skipped messages' keys DLL, tail.
133 struct CadetTunnelSkippedKey *skipped_tail;
136 * 32-byte root key which gets updated by DH ratchet.
138 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
141 * 32-byte header key (currently used for sending).
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
146 * 32-byte header key (currently used for receiving)
148 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
151 * 32-byte next header key (for sending), used once the
152 * ratchet advances. We are sure that the sender has this
153 * key as well only after @e ratchet_allowed is #GNUNET_YES.
155 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
158 * 32-byte next header key (for receiving). To be tried
159 * when decrypting with @e HKr fails and thus the sender
160 * may have advanced the ratchet.
162 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
165 * 32-byte chain keys (used for forward-secrecy) for
166 * sending messages. Updated for every message.
168 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
171 * 32-byte chain keys (used for forward-secrecy) for
172 * receiving messages. Updated for every message. If
173 * messages are skipped, the respective derived MKs
174 * (and the current @HKr) are kept in the @e skipped_head DLL.
176 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
179 * ECDH for key exchange (A0 / B0). Note that for the
180 * 'unverified_ax', this member is an alias with the main
181 * 't->ax.kx_0' value, so do not free it!
183 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
186 * ECDH Ratchet key (our private key in the current DH). Note that
187 * for the 'unverified_ax', this member is an alias with the main
188 * 't->ax.kx_0' value, so do not free it!
190 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
193 * ECDH Ratchet key (other peer's public key in the current DH).
195 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
198 * Time when the current ratchet expires and a new one is triggered
199 * (if @e ratchet_allowed is #GNUNET_YES).
201 struct GNUNET_TIME_Absolute ratchet_expiration;
204 * Number of elements in @a skipped_head <-> @a skipped_tail.
206 unsigned int skipped;
209 * Message number (reset to 0 with each new ratchet, next message to send).
214 * Message number (reset to 0 with each new ratchet, next message to recv).
219 * Previous message numbers (# of msgs sent under prev ratchet)
224 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
229 * True (#GNUNET_YES) if we have received a message from the
230 * other peer that uses the keys from our last ratchet step.
231 * This implies that we are again allowed to advance the ratchet,
232 * otherwise we have to wait until the other peer sees our current
233 * ephemeral key and advances first.
235 * #GNUNET_NO if we have advanced the ratched but lack any evidence
236 * that the other peer has noticed this.
241 * Number of messages recieved since our last ratchet advance.
243 * If this counter = 0, we cannot send a new ratchet key in the next
246 * If this counter > 0, we could (but don't have to) send a new key.
248 * Once the @e ratchet_counter is larger than
249 * #ratchet_messages (or @e ratchet_expiration time has past), and
250 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
252 unsigned int ratchet_counter;
258 * Struct used to save messages in a non-ready tunnel to send once connected.
260 struct CadetTunnelQueueEntry
263 * We are entries in a DLL
265 struct CadetTunnelQueueEntry *next;
268 * We are entries in a DLL
270 struct CadetTunnelQueueEntry *prev;
273 * Tunnel these messages belong in.
275 struct CadetTunnel *t;
278 * Continuation to call once sent (on the channel layer).
280 GNUNET_SCHEDULER_TaskCallback cont;
283 * Closure for @c cont.
288 * Envelope of message to send follows.
290 struct GNUNET_MQ_Envelope *env;
293 * Where to put the connection identifier into the payload
294 * of the message in @e env once we have it?
296 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
301 * Struct containing all information regarding a tunnel to a peer.
306 * Destination of the tunnel.
308 struct CadetPeer *destination;
311 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
312 * ephemeral key changes.
314 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
317 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
319 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
322 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
324 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
329 struct CadetTunnelAxolotl ax;
332 * Unverified Axolotl info, used only if we got a fresh KX (not a
333 * KX_AUTH) while our end of the tunnel was still up. In this case,
334 * we keep the fresh KX around but do not put it into action until
335 * we got encrypted payload that assures us of the authenticity of
338 struct CadetTunnelAxolotl *unverified_ax;
341 * Task scheduled if there are no more channels using the tunnel.
343 struct GNUNET_SCHEDULER_Task *destroy_task;
346 * Task to trim connections if too many are present.
348 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
351 * Task to send messages from queue (if possible).
353 struct GNUNET_SCHEDULER_Task *send_task;
356 * Task to trigger KX.
358 struct GNUNET_SCHEDULER_Task *kx_task;
361 * Tokenizer for decrypted messages.
363 struct GNUNET_MessageStreamTokenizer *mst;
366 * Dispatcher for decrypted messages only (do NOT use for sending!).
368 struct GNUNET_MQ_Handle *mq;
371 * DLL of ready connections that are actively used to reach the destination peer.
373 struct CadetTConnection *connection_ready_head;
376 * DLL of ready connections that are actively used to reach the destination peer.
378 struct CadetTConnection *connection_ready_tail;
381 * DLL of connections that we maintain that might be used to reach the destination peer.
383 struct CadetTConnection *connection_busy_head;
386 * DLL of connections that we maintain that might be used to reach the destination peer.
388 struct CadetTConnection *connection_busy_tail;
391 * Channels inside this tunnel. Maps
392 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
394 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
397 * Channel ID for the next created channel in this tunnel.
399 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
402 * Queued messages, to transmit once tunnel gets connected.
404 struct CadetTunnelQueueEntry *tq_head;
407 * Queued messages, to transmit once tunnel gets connected.
409 struct CadetTunnelQueueEntry *tq_tail;
412 * How long do we wait until we retry the KX?
414 struct GNUNET_TIME_Relative kx_retry_delay;
417 * When do we try the next KX?
419 struct GNUNET_TIME_Absolute next_kx_attempt;
422 * Number of connections in the @e connection_ready_head DLL.
424 unsigned int num_ready_connections;
427 * Number of connections in the @e connection_busy_head DLL.
429 unsigned int num_busy_connections;
432 * How often have we tried and failed to decrypt a message using
433 * the unverified KX material from @e unverified_ax? Used to
434 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
436 unsigned int unverified_attempts;
439 * Number of entries in the @e tq_head DLL.
444 * State of the tunnel encryption.
446 enum CadetTunnelEState estate;
449 * Force triggering KX_AUTH independent of @e estate.
451 int kx_auth_requested;
457 * Connection @a ct is now unready, clear it's ready flag
458 * and move it from the ready DLL to the busy DLL.
460 * @param ct connection to move to unready status
463 mark_connection_unready (struct CadetTConnection *ct)
465 struct CadetTunnel *t = ct->t;
467 GNUNET_assert (GNUNET_YES == ct->is_ready);
468 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
469 t->connection_ready_tail,
471 GNUNET_assert (0 < t->num_ready_connections);
472 t->num_ready_connections--;
473 ct->is_ready = GNUNET_NO;
474 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
475 t->connection_busy_tail,
477 t->num_busy_connections++;
482 * Get the static string for the peer this tunnel is directed.
486 * @return Static string the destination peer's ID.
489 GCT_2s (const struct CadetTunnel *t)
494 return "Tunnel(NULL)";
495 GNUNET_snprintf (buf,
498 GNUNET_i2s (GCP_get_id (t->destination)));
504 * Get string description for tunnel encryption state.
506 * @param es Tunnel state.
508 * @return String representation.
511 estate2s (enum CadetTunnelEState es)
517 case CADET_TUNNEL_KEY_UNINITIALIZED:
518 return "CADET_TUNNEL_KEY_UNINITIALIZED";
519 case CADET_TUNNEL_KEY_AX_RECV:
520 return "CADET_TUNNEL_KEY_AX_RECV";
521 case CADET_TUNNEL_KEY_AX_SENT:
522 return "CADET_TUNNEL_KEY_AX_SENT";
523 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
524 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
525 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
526 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
527 case CADET_TUNNEL_KEY_OK:
528 return "CADET_TUNNEL_KEY_OK";
530 GNUNET_snprintf (buf,
532 "%u (UNKNOWN STATE)",
540 * Return the peer to which this tunnel goes.
543 * @return the destination of the tunnel
546 GCT_get_destination (struct CadetTunnel *t)
548 return t->destination;
553 * Count channels of a tunnel.
555 * @param t Tunnel on which to count.
557 * @return Number of channels.
560 GCT_count_channels (struct CadetTunnel *t)
562 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
567 * Lookup a channel by its @a ctn.
569 * @param t tunnel to look in
570 * @param ctn number of channel to find
571 * @return NULL if channel does not exist
573 struct CadetChannel *
574 lookup_channel (struct CadetTunnel *t,
575 struct GNUNET_CADET_ChannelTunnelNumber ctn)
577 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
583 * Count all created connections of a tunnel. Not necessarily ready connections!
585 * @param t Tunnel on which to count.
587 * @return Number of connections created, either being established or ready.
590 GCT_count_any_connections (const struct CadetTunnel *t)
592 return t->num_ready_connections + t->num_busy_connections;
597 * Find first connection that is ready in the list of
598 * our connections. Picks ready connections round-robin.
600 * @param t tunnel to search
601 * @return NULL if we have no connection that is ready
603 static struct CadetTConnection *
604 get_ready_connection (struct CadetTunnel *t)
606 return t->connection_ready_head;
611 * Get the encryption state of a tunnel.
615 * @return Tunnel's encryption state.
617 enum CadetTunnelEState
618 GCT_get_estate (struct CadetTunnel *t)
625 * Called when either we have a new connection, or a new message in the
626 * queue, or some existing connection has transmission capacity. Looks
627 * at our message queue and if there is a message, picks a connection
630 * @param cls the `struct CadetTunnel` to process messages on
633 trigger_transmissions (void *cls);
636 /* ************************************** start core crypto ***************************** */
640 * Create a new Axolotl ephemeral (ratchet) key.
642 * @param ax key material to update
645 new_ephemeral (struct CadetTunnelAxolotl *ax)
647 GNUNET_free_non_null (ax->DHRs);
648 LOG (GNUNET_ERROR_TYPE_DEBUG,
649 "Creating new ephemeral ratchet key (DHRs)\n");
650 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
657 * @param plaintext Content to HMAC.
658 * @param size Size of @c plaintext.
659 * @param iv Initialization vector for the message.
660 * @param key Key to use.
661 * @param hmac[out] Destination to store the HMAC.
664 t_hmac (const void *plaintext,
667 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
668 struct GNUNET_ShortHashCode *hmac)
670 static const char ctx[] = "cadet authentication key";
671 struct GNUNET_CRYPTO_AuthKey auth_key;
672 struct GNUNET_HashCode hash;
674 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
680 /* Two step: GNUNET_ShortHash is only 256 bits,
681 GNUNET_HashCode is 512, so we truncate. */
682 GNUNET_CRYPTO_hmac (&auth_key,
695 * @param key Key to use.
696 * @param[out] hash Resulting HMAC.
697 * @param source Source key material (data to HMAC).
698 * @param len Length of @a source.
701 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
702 struct GNUNET_HashCode *hash,
706 static const char ctx[] = "axolotl HMAC-HASH";
707 struct GNUNET_CRYPTO_AuthKey auth_key;
709 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
713 GNUNET_CRYPTO_hmac (&auth_key,
721 * Derive a symmetric encryption key from an HMAC-HASH.
723 * @param key Key to use for the HMAC.
724 * @param[out] out Key to generate.
725 * @param source Source key material (data to HMAC).
726 * @param len Length of @a source.
729 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
730 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
734 static const char ctx[] = "axolotl derive key";
735 struct GNUNET_HashCode h;
741 GNUNET_CRYPTO_kdf (out, sizeof (*out),
749 * Encrypt data with the axolotl tunnel key.
751 * @param ax key material to use.
752 * @param dst Destination with @a size bytes for the encrypted data.
753 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
754 * @param size Size of the buffers at @a src and @a dst
757 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
762 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
763 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
766 ax->ratchet_counter++;
767 if ( (GNUNET_YES == ax->ratchet_allowed) &&
768 ( (ratchet_messages <= ax->ratchet_counter) ||
769 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
771 ax->ratchet_flag = GNUNET_YES;
773 if (GNUNET_YES == ax->ratchet_flag)
775 /* Advance ratchet */
776 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
777 struct GNUNET_HashCode dh;
778 struct GNUNET_HashCode hmac;
779 static const char ctx[] = "axolotl ratchet";
784 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
785 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
788 t_ax_hmac_hash (&ax->RK,
792 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
794 &hmac, sizeof (hmac),
802 ax->ratchet_flag = GNUNET_NO;
803 ax->ratchet_allowed = GNUNET_NO;
804 ax->ratchet_counter = 0;
805 ax->ratchet_expiration
806 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
810 t_hmac_derive_key (&ax->CKs,
814 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
819 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
824 GNUNET_assert (size == out_size);
825 t_hmac_derive_key (&ax->CKs,
833 * Decrypt data with the axolotl tunnel key.
835 * @param ax key material to use.
836 * @param dst Destination for the decrypted data, must contain @a size bytes.
837 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
838 * @param size Size of the @a src and @a dst buffers
841 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
846 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
847 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
850 t_hmac_derive_key (&ax->CKr,
854 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
858 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
859 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
864 GNUNET_assert (out_size == size);
865 t_hmac_derive_key (&ax->CKr,
873 * Encrypt header with the axolotl header key.
875 * @param ax key material to use.
876 * @param[in|out] msg Message whose header to encrypt.
879 t_h_encrypt (struct CadetTunnelAxolotl *ax,
880 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
882 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
885 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
889 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
890 sizeof (struct GNUNET_CADET_AxHeader),
894 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
899 * Decrypt header with the current axolotl header key.
901 * @param ax key material to use.
902 * @param src Message whose header to decrypt.
903 * @param dst Where to decrypt header to.
906 t_h_decrypt (struct CadetTunnelAxolotl *ax,
907 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
908 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
910 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
913 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
917 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
918 sizeof (struct GNUNET_CADET_AxHeader),
922 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
927 * Delete a key from the list of skipped keys.
929 * @param ax key material to delete @a key from.
930 * @param key Key to delete.
933 delete_skipped_key (struct CadetTunnelAxolotl *ax,
934 struct CadetTunnelSkippedKey *key)
936 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
945 * Decrypt and verify data with the appropriate tunnel key and verify that the
946 * data has not been altered since it was sent by the remote peer.
948 * @param ax key material to use.
949 * @param dst Destination for the plaintext.
950 * @param src Source of the message. Can overlap with @c dst.
951 * @param size Size of the message.
952 * @return Size of the decrypted data, -1 if an error was encountered.
955 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
957 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
960 struct CadetTunnelSkippedKey *key;
961 struct GNUNET_ShortHashCode *hmac;
962 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
963 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
964 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
970 LOG (GNUNET_ERROR_TYPE_DEBUG,
971 "Trying skipped keys\n");
972 hmac = &plaintext_header.hmac;
973 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
975 /* Find a correct Header Key */
977 for (key = ax->skipped_head; NULL != key; key = key->next)
979 t_hmac (&src->ax_header,
980 sizeof (struct GNUNET_CADET_AxHeader) + esize,
984 if (0 == memcmp (hmac,
995 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
996 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
997 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
998 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1000 /* Decrypt header */
1001 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1005 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1006 sizeof (struct GNUNET_CADET_AxHeader),
1009 &plaintext_header.ax_header.Ns);
1010 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1012 /* Find the correct message key */
1013 N = ntohl (plaintext_header.ax_header.Ns);
1014 while ( (NULL != key) &&
1017 if ( (NULL == key) ||
1018 (0 != memcmp (&key->HK,
1020 sizeof (*valid_HK))) )
1023 /* Decrypt payload */
1024 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1029 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1034 delete_skipped_key (ax,
1041 * Delete a key from the list of skipped keys.
1043 * @param ax key material to delete from.
1044 * @param HKr Header Key to use.
1047 store_skipped_key (struct CadetTunnelAxolotl *ax,
1048 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1050 struct CadetTunnelSkippedKey *key;
1052 key = GNUNET_new (struct CadetTunnelSkippedKey);
1053 key->timestamp = GNUNET_TIME_absolute_get ();
1056 t_hmac_derive_key (&ax->CKr,
1060 t_hmac_derive_key (&ax->CKr,
1064 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1073 * Stage skipped AX keys and calculate the message key.
1074 * Stores each HK and MK for skipped messages.
1076 * @param ax key material to use
1077 * @param HKr Header key.
1078 * @param Np Received meesage number.
1079 * @return #GNUNET_OK if keys were stored.
1080 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1083 store_ax_keys (struct CadetTunnelAxolotl *ax,
1084 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1090 LOG (GNUNET_ERROR_TYPE_DEBUG,
1091 "Storing skipped keys [%u, %u)\n",
1094 if (MAX_KEY_GAP < gap)
1096 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1097 /* TODO: start new key exchange on return */
1098 GNUNET_break_op (0);
1099 LOG (GNUNET_ERROR_TYPE_WARNING,
1100 "Got message %u, expected %u+\n",
1103 return GNUNET_SYSERR;
1107 /* Delayed message: don't store keys, flag to try old keys. */
1108 return GNUNET_SYSERR;
1112 store_skipped_key (ax,
1115 while (ax->skipped > MAX_SKIPPED_KEYS)
1116 delete_skipped_key (ax,
1123 * Decrypt and verify data with the appropriate tunnel key and verify that the
1124 * data has not been altered since it was sent by the remote peer.
1126 * @param ax key material to use
1127 * @param dst Destination for the plaintext.
1128 * @param src Source of the message. Can overlap with @c dst.
1129 * @param size Size of the message.
1130 * @return Size of the decrypted data, -1 if an error was encountered.
1133 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1135 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1138 struct GNUNET_ShortHashCode msg_hmac;
1139 struct GNUNET_HashCode hmac;
1140 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1143 size_t esize; /* Size of encryped payload */
1145 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1147 /* Try current HK */
1148 t_hmac (&src->ax_header,
1149 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1152 if (0 != memcmp (&msg_hmac,
1156 static const char ctx[] = "axolotl ratchet";
1157 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1158 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1159 struct GNUNET_HashCode dh;
1160 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1163 t_hmac (&src->ax_header,
1164 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1168 if (0 != memcmp (&msg_hmac,
1172 /* Try the skipped keys, if that fails, we're out of luck. */
1173 return try_old_ax_keys (ax,
1183 Np = ntohl (plaintext_header.ax_header.Ns);
1184 PNp = ntohl (plaintext_header.ax_header.PNs);
1185 DHRp = &plaintext_header.ax_header.DHRs;
1190 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1191 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1194 t_ax_hmac_hash (&ax->RK,
1197 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1199 &hmac, sizeof (hmac),
1202 /* Commit "purported" keys */
1208 ax->ratchet_allowed = GNUNET_YES;
1215 Np = ntohl (plaintext_header.ax_header.Ns);
1216 PNp = ntohl (plaintext_header.ax_header.PNs);
1218 if ( (Np != ax->Nr) &&
1219 (GNUNET_OK != store_ax_keys (ax,
1223 /* Try the skipped keys, if that fails, we're out of luck. */
1224 return try_old_ax_keys (ax,
1240 * Our tunnel became ready for the first time, notify channels
1241 * that have been waiting.
1243 * @param cls our tunnel, not used
1244 * @param key unique ID of the channel, not used
1245 * @param value the `struct CadetChannel` to notify
1246 * @return #GNUNET_OK (continue to iterate)
1249 notify_tunnel_up_cb (void *cls,
1253 struct CadetChannel *ch = value;
1255 GCCH_tunnel_up (ch);
1261 * Change the tunnel encryption state.
1262 * If the encryption state changes to OK, stop the rekey task.
1264 * @param t Tunnel whose encryption state to change, or NULL.
1265 * @param state New encryption state.
1268 GCT_change_estate (struct CadetTunnel *t,
1269 enum CadetTunnelEState state)
1271 enum CadetTunnelEState old = t->estate;
1274 LOG (GNUNET_ERROR_TYPE_DEBUG,
1275 "%s estate changed from %s to %s\n",
1280 if ( (CADET_TUNNEL_KEY_OK != old) &&
1281 (CADET_TUNNEL_KEY_OK == t->estate) )
1283 if (NULL != t->kx_task)
1285 GNUNET_SCHEDULER_cancel (t->kx_task);
1288 /* notify all channels that have been waiting */
1289 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1290 ¬ify_tunnel_up_cb,
1292 if (NULL != t->send_task)
1293 GNUNET_SCHEDULER_cancel (t->send_task);
1294 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1301 * Send a KX message.
1303 * @param t tunnel on which to send the KX_AUTH
1304 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1305 * we are to find one that is ready.
1306 * @param ax axolotl key context to use
1309 send_kx (struct CadetTunnel *t,
1310 struct CadetTConnection *ct,
1311 struct CadetTunnelAxolotl *ax)
1313 struct CadetConnection *cc;
1314 struct GNUNET_MQ_Envelope *env;
1315 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1316 enum GNUNET_CADET_KX_Flags flags;
1319 ct = get_ready_connection (t);
1322 LOG (GNUNET_ERROR_TYPE_DEBUG,
1323 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1325 estate2s (t->estate));
1326 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1330 LOG (GNUNET_ERROR_TYPE_DEBUG,
1331 "Sending KX on %s via %s using %s in state %s\n",
1334 estate2s (t->estate));
1335 env = GNUNET_MQ_msg (msg,
1336 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1337 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1338 msg->flags = htonl (flags);
1339 msg->cid = *GCC_get_id (cc);
1340 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1341 &msg->ephemeral_key);
1342 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1344 mark_connection_unready (ct);
1345 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1346 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1347 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1348 GCT_change_estate (t,
1349 CADET_TUNNEL_KEY_AX_SENT);
1350 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1351 GCT_change_estate (t,
1352 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1359 * Send a KX_AUTH message.
1361 * @param t tunnel on which to send the KX_AUTH
1362 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1363 * we are to find one that is ready.
1364 * @param ax axolotl key context to use
1365 * @param force_reply Force the other peer to reply with a KX_AUTH message
1366 * (set if we would like to transmit right now, but cannot)
1369 send_kx_auth (struct CadetTunnel *t,
1370 struct CadetTConnection *ct,
1371 struct CadetTunnelAxolotl *ax,
1374 struct CadetConnection *cc;
1375 struct GNUNET_MQ_Envelope *env;
1376 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1377 enum GNUNET_CADET_KX_Flags flags;
1379 if ( (NULL == ct) ||
1380 (GNUNET_NO == ct->is_ready) )
1381 ct = get_ready_connection (t);
1384 LOG (GNUNET_ERROR_TYPE_DEBUG,
1385 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1387 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1388 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1391 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1393 LOG (GNUNET_ERROR_TYPE_DEBUG,
1394 "Sending KX_AUTH on %s using %s\n",
1398 env = GNUNET_MQ_msg (msg,
1399 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1400 flags = GNUNET_CADET_KX_FLAG_NONE;
1401 if (GNUNET_YES == force_reply)
1402 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1403 msg->kx.flags = htonl (flags);
1404 msg->kx.cid = *GCC_get_id (cc);
1405 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1406 &msg->kx.ephemeral_key);
1407 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1408 &msg->kx.ratchet_key);
1409 /* Compute authenticator (this is the main difference to #send_kx()) */
1410 GNUNET_CRYPTO_hash (&ax->RK,
1414 /* Compute when to be triggered again; actual job will
1415 be scheduled via #connection_ready_cb() */
1417 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1419 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1421 /* Send via cc, mark it as unready */
1422 mark_connection_unready (ct);
1424 /* Update state machine, unless we are already OK */
1425 if (CADET_TUNNEL_KEY_OK != t->estate)
1426 GCT_change_estate (t,
1427 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1435 * Cleanup state used by @a ax.
1437 * @param ax state to free, but not memory of @a ax itself
1440 cleanup_ax (struct CadetTunnelAxolotl *ax)
1442 while (NULL != ax->skipped_head)
1443 delete_skipped_key (ax,
1445 GNUNET_assert (0 == ax->skipped);
1446 GNUNET_free_non_null (ax->kx_0);
1447 GNUNET_free_non_null (ax->DHRs);
1452 * Update our Axolotl key state based on the KX data we received.
1453 * Computes the new chain keys, and root keys, etc, and also checks
1454 * wether this is a replay of the current chain.
1456 * @param[in|out] axolotl chain key state to recompute
1457 * @param pid peer identity of the other peer
1458 * @param ephemeral_key ephemeral public key of the other peer
1459 * @param ratchet_key senders next ephemeral public key
1460 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1461 * root key is already in @a ax and thus the KX is useless;
1462 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1465 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1466 const struct GNUNET_PeerIdentity *pid,
1467 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1468 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1470 struct GNUNET_HashCode key_material[3];
1471 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1472 const char salt[] = "CADET Axolotl salt";
1475 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1477 am_I_alice = GNUNET_YES;
1478 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1480 am_I_alice = GNUNET_NO;
1483 GNUNET_break_op (0);
1484 return GNUNET_SYSERR;
1487 if (0 == memcmp (&ax->DHRr,
1489 sizeof (*ratchet_key)))
1491 LOG (GNUNET_ERROR_TYPE_DEBUG,
1492 "Ratchet key already known. Ignoring KX.\n");
1496 ax->DHRr = *ratchet_key;
1499 if (GNUNET_YES == am_I_alice)
1501 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1502 ephemeral_key, /* B0 */
1507 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1508 &pid->public_key, /* A */
1513 if (GNUNET_YES == am_I_alice)
1515 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1516 &pid->public_key, /* B */
1521 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1522 ephemeral_key, /* B0 */
1529 /* (This is the triple-DH, we could probably safely skip this,
1530 as A0/B0 are already in the key material.) */
1531 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1532 ephemeral_key, /* B0 or A0 */
1536 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1537 salt, sizeof (salt),
1538 &key_material, sizeof (key_material),
1541 if (0 == memcmp (&ax->RK,
1545 LOG (GNUNET_ERROR_TYPE_DEBUG,
1546 "Root key of handshake already known. Ignoring KX.\n");
1551 if (GNUNET_YES == am_I_alice)
1557 ax->ratchet_flag = GNUNET_YES;
1565 ax->ratchet_flag = GNUNET_NO;
1566 ax->ratchet_expiration
1567 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1575 * Try to redo the KX or KX_AUTH handshake, if we can.
1577 * @param cls the `struct CadetTunnel` to do KX for.
1580 retry_kx (void *cls)
1582 struct CadetTunnel *t = cls;
1583 struct CadetTunnelAxolotl *ax;
1586 LOG (GNUNET_ERROR_TYPE_DEBUG,
1587 "Trying to make KX progress on %s in state %s\n",
1589 estate2s (t->estate));
1592 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1593 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1598 case CADET_TUNNEL_KEY_AX_RECV:
1599 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1600 /* We are responding, so only require reply
1601 if WE have a channel waiting. */
1602 if (NULL != t->unverified_ax)
1604 /* Send AX_AUTH so we might get this one verified */
1605 ax = t->unverified_ax;
1609 /* How can this be? */
1616 (0 == GCT_count_channels (t))
1620 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
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_OK:
1642 /* Must have been the *other* peer asking us to
1643 respond with a KX_AUTH. */
1644 if (NULL != t->unverified_ax)
1646 /* Sending AX_AUTH in response to AX so we might get this one verified */
1647 ax = t->unverified_ax;
1651 /* Sending AX_AUTH in response to AX_AUTH */
1664 * Handle KX message that lacks authentication (and which will thus
1665 * only be considered authenticated after we respond with our own
1666 * KX_AUTH and finally successfully decrypt payload).
1668 * @param ct connection/tunnel combo that received encrypted message
1669 * @param msg the key exchange message
1672 GCT_handle_kx (struct CadetTConnection *ct,
1673 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1675 struct CadetTunnel *t = ct->t;
1676 struct CadetTunnelAxolotl *ax;
1680 memcmp (&t->ax.DHRr,
1682 sizeof (msg->ratchet_key)))
1684 LOG (GNUNET_ERROR_TYPE_DEBUG,
1685 "Got duplicate KX. Firing back KX_AUTH.\n");
1693 /* We only keep ONE unverified KX around, so if there is an existing one,
1695 if (NULL != t->unverified_ax)
1698 memcmp (&t->unverified_ax->DHRr,
1700 sizeof (msg->ratchet_key)))
1702 LOG (GNUNET_ERROR_TYPE_DEBUG,
1703 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1711 LOG (GNUNET_ERROR_TYPE_DEBUG,
1712 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1714 memset (t->unverified_ax,
1716 sizeof (struct CadetTunnelAxolotl));
1717 t->unverified_ax->DHRs = t->ax.DHRs;
1718 t->unverified_ax->kx_0 = t->ax.kx_0;
1722 LOG (GNUNET_ERROR_TYPE_DEBUG,
1723 "Creating fresh unverified KX for %s.\n",
1725 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1726 t->unverified_ax->DHRs = t->ax.DHRs;
1727 t->unverified_ax->kx_0 = t->ax.kx_0;
1729 /* Set as the 'current' RK/DHRr the one we are currently using,
1730 so that the duplicate-detection logic of
1731 #update_ax_by_kx can work. */
1732 t->unverified_ax->RK = t->ax.RK;
1733 t->unverified_ax->DHRr = t->ax.DHRr;
1734 t->unverified_attempts = 0;
1735 ax = t->unverified_ax;
1737 /* Update 'ax' by the new key material */
1738 ret = update_ax_by_kx (ax,
1739 GCP_get_id (t->destination),
1740 &msg->ephemeral_key,
1742 GNUNET_break (GNUNET_SYSERR != ret);
1743 if (GNUNET_OK != ret)
1744 return; /* duplicate KX, nothing to do */
1746 /* move ahead in our state machine */
1747 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1748 GCT_change_estate (t,
1749 CADET_TUNNEL_KEY_AX_RECV);
1750 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1751 GCT_change_estate (t,
1752 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1754 /* KX is still not done, try again our end. */
1755 if (CADET_TUNNEL_KEY_OK != t->estate)
1757 if (NULL != t->kx_task)
1758 GNUNET_SCHEDULER_cancel (t->kx_task);
1760 = GNUNET_SCHEDULER_add_now (&retry_kx,
1767 * Handle KX_AUTH message.
1769 * @param ct connection/tunnel combo that received encrypted message
1770 * @param msg the key exchange message
1773 GCT_handle_kx_auth (struct CadetTConnection *ct,
1774 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1776 struct CadetTunnel *t = ct->t;
1777 struct CadetTunnelAxolotl ax_tmp;
1778 struct GNUNET_HashCode kx_auth;
1781 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1782 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1784 /* Confusing, we got a KX_AUTH before we even send our own
1785 KX. This should not happen. We'll send our own KX ASAP anyway,
1786 so let's ignore this here. */
1787 GNUNET_break_op (0);
1790 LOG (GNUNET_ERROR_TYPE_DEBUG,
1791 "Handling KX_AUTH message for %s\n",
1794 /* We do everything in ax_tmp until we've checked the authentication
1795 so we don't clobber anything we care about by accident. */
1798 /* Update 'ax' by the new key material */
1799 ret = update_ax_by_kx (&ax_tmp,
1800 GCP_get_id (t->destination),
1801 &msg->kx.ephemeral_key,
1802 &msg->kx.ratchet_key);
1803 GNUNET_break (GNUNET_OK == ret);
1804 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1807 if (0 != memcmp (&kx_auth,
1811 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1812 we transmitted to the sender, refuse it! */
1813 GNUNET_break_op (0);
1816 /* Yep, we're good. */
1818 if (NULL != t->unverified_ax)
1820 /* We got some "stale" KX before, drop that. */
1821 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1822 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1823 cleanup_ax (t->unverified_ax);
1824 GNUNET_free (t->unverified_ax);
1825 t->unverified_ax = NULL;
1828 /* move ahead in our state machine */
1831 case CADET_TUNNEL_KEY_UNINITIALIZED:
1832 case CADET_TUNNEL_KEY_AX_RECV:
1833 /* Checked above, this is impossible. */
1836 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1837 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1838 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1839 GCT_change_estate (t,
1840 CADET_TUNNEL_KEY_OK);
1842 case CADET_TUNNEL_KEY_OK:
1843 /* Did not expect another KX_AUTH, but so what, still acceptable.
1844 Nothing to do here. */
1851 /* ************************************** end core crypto ***************************** */
1855 * Compute the next free channel tunnel number for this tunnel.
1857 * @param t the tunnel
1858 * @return unused number that can uniquely identify a channel in the tunnel
1860 static struct GNUNET_CADET_ChannelTunnelNumber
1861 get_next_free_ctn (struct CadetTunnel *t)
1863 #define HIGH_BIT 0x8000000
1864 struct GNUNET_CADET_ChannelTunnelNumber ret;
1869 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1870 GCP_get_id (GCT_get_destination (t)));
1876 GNUNET_assert (0); // loopback must never go here!
1877 ctn = ntohl (t->next_ctn.cn);
1879 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1882 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1884 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1885 ret.cn = ntohl (ctn);
1891 * Add a channel to a tunnel, and notify channel that we are ready
1892 * for transmission if we are already up. Otherwise that notification
1893 * will be done later in #notify_tunnel_up_cb().
1897 * @return unique number identifying @a ch within @a t
1899 struct GNUNET_CADET_ChannelTunnelNumber
1900 GCT_add_channel (struct CadetTunnel *t,
1901 struct CadetChannel *ch)
1903 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1905 ctn = get_next_free_ctn (t);
1906 GNUNET_assert (GNUNET_YES ==
1907 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1910 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1911 LOG (GNUNET_ERROR_TYPE_DEBUG,
1912 "Adding %s to %s\n",
1917 case CADET_TUNNEL_KEY_UNINITIALIZED:
1918 /* waiting for connection to start KX */
1920 case CADET_TUNNEL_KEY_AX_RECV:
1921 case CADET_TUNNEL_KEY_AX_SENT:
1922 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1923 /* we're currently waiting for KX to complete */
1925 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1926 /* waiting for OTHER peer to send us data,
1927 we might need to prompt more aggressively! */
1928 if (NULL == t->kx_task)
1930 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1934 case CADET_TUNNEL_KEY_OK:
1935 /* We are ready. Tell the new channel that we are up. */
1936 GCCH_tunnel_up (ch);
1944 * We lost a connection, remove it from our list and clean up
1945 * the connection object itself.
1947 * @param ct binding of connection to tunnel of the connection that was lost.
1950 GCT_connection_lost (struct CadetTConnection *ct)
1952 struct CadetTunnel *t = ct->t;
1954 if (GNUNET_YES == ct->is_ready)
1955 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
1956 t->connection_ready_tail,
1959 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
1960 t->connection_busy_tail,
1967 * Clean up connection @a ct of a tunnel.
1969 * @param cls the `struct CadetTunnel`
1970 * @param ct connection to clean up
1973 destroy_t_connection (void *cls,
1974 struct CadetTConnection *ct)
1976 struct CadetTunnel *t = cls;
1977 struct CadetConnection *cc = ct->cc;
1979 GNUNET_assert (ct->t == t);
1980 GCT_connection_lost (ct);
1981 GCC_destroy_without_tunnel (cc);
1986 * This tunnel is no longer used, destroy it.
1988 * @param cls the idle tunnel
1991 destroy_tunnel (void *cls)
1993 struct CadetTunnel *t = cls;
1994 struct CadetTunnelQueueEntry *tq;
1996 t->destroy_task = NULL;
1997 LOG (GNUNET_ERROR_TYPE_DEBUG,
1998 "Destroying idle %s\n",
2000 GNUNET_assert (0 == GCT_count_channels (t));
2001 GCT_iterate_connections (t,
2002 &destroy_t_connection,
2004 GNUNET_assert (NULL == t->connection_ready_head);
2005 GNUNET_assert (NULL == t->connection_busy_head);
2006 while (NULL != (tq = t->tq_head))
2008 if (NULL != tq->cont)
2009 tq->cont (tq->cont_cls);
2010 GCT_send_cancel (tq);
2012 GCP_drop_tunnel (t->destination,
2014 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2015 if (NULL != t->maintain_connections_task)
2017 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2018 t->maintain_connections_task = NULL;
2020 if (NULL != t->send_task)
2022 GNUNET_SCHEDULER_cancel (t->send_task);
2023 t->send_task = NULL;
2025 if (NULL != t->kx_task)
2027 GNUNET_SCHEDULER_cancel (t->kx_task);
2030 GNUNET_MST_destroy (t->mst);
2031 GNUNET_MQ_destroy (t->mq);
2032 if (NULL != t->unverified_ax)
2034 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
2035 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
2036 cleanup_ax (t->unverified_ax);
2037 GNUNET_free (t->unverified_ax);
2039 cleanup_ax (&t->ax);
2040 GNUNET_assert (NULL == t->destroy_task);
2046 * Remove a channel from a tunnel.
2050 * @param ctn unique number identifying @a ch within @a t
2053 GCT_remove_channel (struct CadetTunnel *t,
2054 struct CadetChannel *ch,
2055 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2057 LOG (GNUNET_ERROR_TYPE_DEBUG,
2058 "Removing %s from %s\n",
2061 GNUNET_assert (GNUNET_YES ==
2062 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2066 GCT_count_channels (t)) &&
2067 (NULL == t->destroy_task) )
2070 = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2078 * Destroy remaining channels during shutdown.
2080 * @param cls the `struct CadetTunnel` of the channel
2081 * @param key key of the channel
2082 * @param value the `struct CadetChannel`
2083 * @return #GNUNET_OK (continue to iterate)
2086 destroy_remaining_channels (void *cls,
2090 struct CadetChannel *ch = value;
2092 GCCH_handle_remote_destroy (ch);
2098 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2100 * @param t tunnel to destroy
2103 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2105 GNUNET_assert (GNUNET_YES == shutting_down);
2106 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2107 &destroy_remaining_channels,
2110 GCT_count_channels (t));
2111 if (NULL != t->destroy_task)
2113 GNUNET_SCHEDULER_cancel (t->destroy_task);
2114 t->destroy_task = NULL;
2121 * Send normal payload from queue in @a t via connection @a ct.
2122 * Does nothing if our payload queue is empty.
2124 * @param t tunnel to send data from
2125 * @param ct connection to use for transmission (is ready)
2128 try_send_normal_payload (struct CadetTunnel *t,
2129 struct CadetTConnection *ct)
2131 struct CadetTunnelQueueEntry *tq;
2133 GNUNET_assert (GNUNET_YES == ct->is_ready);
2137 /* no messages pending right now */
2138 LOG (GNUNET_ERROR_TYPE_DEBUG,
2139 "Not sending payload of %s on ready %s (nothing pending)\n",
2144 /* ready to send message 'tq' on tunnel 'ct' */
2145 GNUNET_assert (t == tq->t);
2146 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2149 if (NULL != tq->cid)
2150 *tq->cid = *GCC_get_id (ct->cc);
2151 mark_connection_unready (ct);
2152 LOG (GNUNET_ERROR_TYPE_DEBUG,
2153 "Sending payload of %s on %s\n",
2156 GCC_transmit (ct->cc,
2158 if (NULL != tq->cont)
2159 tq->cont (tq->cont_cls);
2165 * A connection is @a is_ready for transmission. Looks at our message
2166 * queue and if there is a message, sends it out via the connection.
2168 * @param cls the `struct CadetTConnection` that is @a is_ready
2169 * @param is_ready #GNUNET_YES if connection are now ready,
2170 * #GNUNET_NO if connection are no longer ready
2173 connection_ready_cb (void *cls,
2176 struct CadetTConnection *ct = cls;
2177 struct CadetTunnel *t = ct->t;
2179 if (GNUNET_NO == is_ready)
2181 LOG (GNUNET_ERROR_TYPE_DEBUG,
2182 "%s no longer ready for %s\n",
2185 mark_connection_unready (ct);
2188 GNUNET_assert (GNUNET_NO == ct->is_ready);
2189 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2190 t->connection_busy_tail,
2192 GNUNET_assert (0 < t->num_busy_connections);
2193 t->num_busy_connections--;
2194 ct->is_ready = GNUNET_YES;
2195 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2196 t->connection_ready_tail,
2198 t->num_ready_connections++;
2200 LOG (GNUNET_ERROR_TYPE_DEBUG,
2201 "%s now ready for %s in state %s\n",
2204 estate2s (t->estate));
2207 case CADET_TUNNEL_KEY_UNINITIALIZED:
2208 /* Do not begin KX if WE have no channels waiting! */
2209 if (0 == GCT_count_channels (t))
2211 /* We are uninitialized, just transmit immediately,
2212 without undue delay. */
2213 if (NULL != t->kx_task)
2215 GNUNET_SCHEDULER_cancel (t->kx_task);
2222 case CADET_TUNNEL_KEY_AX_RECV:
2223 case CADET_TUNNEL_KEY_AX_SENT:
2224 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2225 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2226 /* we're currently waiting for KX to complete, schedule job */
2227 if (NULL == t->kx_task)
2229 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2233 case CADET_TUNNEL_KEY_OK:
2234 if (GNUNET_YES == t->kx_auth_requested)
2236 if (NULL != t->kx_task)
2238 GNUNET_SCHEDULER_cancel (t->kx_task);
2247 try_send_normal_payload (t,
2255 * Called when either we have a new connection, or a new message in the
2256 * queue, or some existing connection has transmission capacity. Looks
2257 * at our message queue and if there is a message, picks a connection
2260 * @param cls the `struct CadetTunnel` to process messages on
2263 trigger_transmissions (void *cls)
2265 struct CadetTunnel *t = cls;
2266 struct CadetTConnection *ct;
2268 t->send_task = NULL;
2269 if (NULL == t->tq_head)
2270 return; /* no messages pending right now */
2271 ct = get_ready_connection (t);
2273 return; /* no connections ready */
2274 try_send_normal_payload (t,
2280 * Closure for #evaluate_connection. Used to assemble summary information
2281 * about the existing connections so we can evaluate a new path.
2283 struct EvaluationSummary
2287 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2289 unsigned int min_length;
2292 * Maximum length of any of our connections, 0 if we have none.
2294 unsigned int max_length;
2297 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2299 GNUNET_CONTAINER_HeapCostType min_desire;
2302 * Maximum desirability of any of our connections, 0 if we have none.
2304 GNUNET_CONTAINER_HeapCostType max_desire;
2307 * Path we are comparing against for #evaluate_connection, can be NULL.
2309 struct CadetPeerPath *path;
2312 * Connection deemed the "worst" so far encountered by #evaluate_connection,
2313 * NULL if we did not yet encounter any connections.
2315 struct CadetTConnection *worst;
2318 * Numeric score of @e worst, only set if @e worst is non-NULL.
2323 * Set to #GNUNET_YES if we have a connection over @e path already.
2331 * Evaluate a connection, updating our summary information in @a cls about
2332 * what kinds of connections we have.
2334 * @param cls the `struct EvaluationSummary *` to update
2335 * @param ct a connection to include in the summary
2338 evaluate_connection (void *cls,
2339 struct CadetTConnection *ct)
2341 struct EvaluationSummary *es = cls;
2342 struct CadetConnection *cc = ct->cc;
2343 struct CadetPeerPath *ps = GCC_get_path (cc);
2344 GNUNET_CONTAINER_HeapCostType ct_desirability;
2350 LOG (GNUNET_ERROR_TYPE_DEBUG,
2351 "Ignoring duplicate path %s.\n",
2352 GCPP_2s (es->path));
2353 es->duplicate = GNUNET_YES;
2356 ct_desirability = GCPP_get_desirability (ps);
2357 ct_length = GCPP_get_length (ps);
2359 /* FIXME: calculate score on more than path,
2360 include connection performance metrics like
2361 last successful transmission, uptime, etc. */
2362 score = ct_desirability + ct_length; /* FIXME: weigh these as well! */
2364 if ( (NULL == es->worst) ||
2365 (score < es->worst_score) )
2368 es->worst_score = score;
2370 es->min_length = GNUNET_MIN (es->min_length,
2372 es->max_length = GNUNET_MAX (es->max_length,
2374 es->min_desire = GNUNET_MIN (es->min_desire,
2376 es->max_desire = GNUNET_MAX (es->max_desire,
2382 * Consider using the path @a p for the tunnel @a t.
2383 * The tunnel destination is at offset @a off in path @a p.
2385 * @param cls our tunnel
2386 * @param path a path to our destination
2387 * @param off offset of the destination on path @a path
2388 * @return #GNUNET_YES (should keep iterating)
2391 consider_path_cb (void *cls,
2392 struct CadetPeerPath *path,
2395 struct CadetTunnel *t = cls;
2396 struct EvaluationSummary es;
2397 struct CadetTConnection *ct;
2399 es.min_length = UINT_MAX;
2402 es.min_desire = UINT64_MAX;
2404 es.duplicate = GNUNET_NO;
2406 /* Compute evaluation summary over existing connections. */
2407 GCT_iterate_connections (t,
2408 &evaluate_connection,
2410 if (GNUNET_YES == es.duplicate)
2413 /* FIXME: not sure we should really just count
2414 'num_connections' here, as they may all have
2415 consistently failed to connect. */
2417 /* We iterate by increasing path length; if we have enough paths and
2418 this one is more than twice as long than what we are currently
2419 using, then ignore all of these super-long ones! */
2420 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2421 (es.min_length * 2 < off) &&
2422 (es.max_length < off) )
2424 LOG (GNUNET_ERROR_TYPE_DEBUG,
2425 "Ignoring paths of length %u, they are way too long.\n",
2429 /* If we have enough paths and this one looks no better, ignore it. */
2430 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2431 (es.min_length < GCPP_get_length (path)) &&
2432 (es.min_desire > GCPP_get_desirability (path)) &&
2433 (es.max_length < off) )
2435 LOG (GNUNET_ERROR_TYPE_DEBUG,
2436 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2437 GCPP_get_length (path),
2438 (unsigned long long) GCPP_get_desirability (path),
2439 GCP_2s (t->destination));
2443 /* Path is interesting (better by some metric, or we don't have
2444 enough paths yet). */
2445 ct = GNUNET_new (struct CadetTConnection);
2446 ct->created = GNUNET_TIME_absolute_get ();
2448 ct->cc = GCC_create (t->destination,
2450 GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2452 &connection_ready_cb,
2455 /* FIXME: schedule job to kill connection (and path?) if it takes
2456 too long to get ready! (And track performance data on how long
2457 other connections took with the tunnel!)
2458 => Note: to be done within 'connection'-logic! */
2459 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2460 t->connection_busy_tail,
2462 t->num_busy_connections++;
2463 LOG (GNUNET_ERROR_TYPE_DEBUG,
2464 "Found interesting path %s for %s, created %s\n",
2473 * Function called to maintain the connections underlying our tunnel.
2474 * Tries to maintain (incl. tear down) connections for the tunnel, and
2475 * if there is a significant change, may trigger transmissions.
2477 * Basically, needs to check if there are connections that perform
2478 * badly, and if so eventually kill them and trigger a replacement.
2479 * The strategy is to open one more connection than
2480 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2481 * least-performing one, and then inquire for new ones.
2483 * @param cls the `struct CadetTunnel`
2486 maintain_connections_cb (void *cls)
2488 struct CadetTunnel *t = cls;
2489 struct GNUNET_TIME_Relative delay;
2490 struct EvaluationSummary es;
2492 t->maintain_connections_task = NULL;
2493 LOG (GNUNET_ERROR_TYPE_DEBUG,
2494 "Performing connection maintenance for %s.\n",
2497 es.min_length = UINT_MAX;
2500 es.min_desire = UINT64_MAX;
2503 es.duplicate = GNUNET_NO;
2504 GCT_iterate_connections (t,
2505 &evaluate_connection,
2507 if ( (NULL != es.worst) &&
2508 (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2510 /* Clear out worst-performing connection 'es.worst'. */
2511 destroy_t_connection (t,
2515 /* Consider additional paths */
2516 (void) GCP_iterate_paths (t->destination,
2520 /* FIXME: calculate when to try again based on how well we are doing;
2521 in particular, if we have to few connections, we might be able
2522 to do without this (as PATHS should tell us whenever a new path
2523 is available instantly; however, need to make sure this job is
2524 restarted after that happens).
2525 Furthermore, if the paths we do know are in a reasonably narrow
2526 quality band and are plentyful, we might also consider us stabilized
2527 and then reduce the frequency accordingly. */
2528 delay = GNUNET_TIME_UNIT_MINUTES;
2529 t->maintain_connections_task
2530 = GNUNET_SCHEDULER_add_delayed (delay,
2531 &maintain_connections_cb,
2537 * Consider using the path @a p for the tunnel @a t.
2538 * The tunnel destination is at offset @a off in path @a p.
2540 * @param cls our tunnel
2541 * @param path a path to our destination
2542 * @param off offset of the destination on path @a path
2545 GCT_consider_path (struct CadetTunnel *t,
2546 struct CadetPeerPath *p,
2549 (void) consider_path_cb (t,
2556 * We got a keepalive. Track in statistics.
2558 * @param cls the `struct CadetTunnel` for which we decrypted the message
2559 * @param msg the message we received on the tunnel
2562 handle_plaintext_keepalive (void *cls,
2563 const struct GNUNET_MessageHeader *msg)
2565 struct CadetTunnel *t = cls;
2567 LOG (GNUNET_ERROR_TYPE_DEBUG,
2568 "Received KEEPALIVE on %s\n",
2570 GNUNET_STATISTICS_update (stats,
2571 "# keepalives received",
2578 * Check that @a msg is well-formed.
2580 * @param cls the `struct CadetTunnel` for which we decrypted the message
2581 * @param msg the message we received on the tunnel
2582 * @return #GNUNET_OK (any variable-size payload goes)
2585 check_plaintext_data (void *cls,
2586 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2593 * We received payload data for a channel. Locate the channel
2594 * and process the data, or return an error if the channel is unknown.
2596 * @param cls the `struct CadetTunnel` for which we decrypted the message
2597 * @param msg the message we received on the tunnel
2600 handle_plaintext_data (void *cls,
2601 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2603 struct CadetTunnel *t = cls;
2604 struct CadetChannel *ch;
2606 ch = lookup_channel (t,
2610 /* We don't know about such a channel, might have been destroyed on our
2611 end in the meantime, or never existed. Send back a DESTROY. */
2612 LOG (GNUNET_ERROR_TYPE_DEBUG,
2613 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2614 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2615 ntohl (msg->ctn.cn));
2616 GCT_send_channel_destroy (t,
2620 GCCH_handle_channel_plaintext_data (ch,
2626 * We received an acknowledgement for data we sent on a channel.
2627 * Locate the channel and process it, or return an error if the
2628 * channel is unknown.
2630 * @param cls the `struct CadetTunnel` for which we decrypted the message
2631 * @param ack the message we received on the tunnel
2634 handle_plaintext_data_ack (void *cls,
2635 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2637 struct CadetTunnel *t = cls;
2638 struct CadetChannel *ch;
2640 ch = lookup_channel (t,
2644 /* We don't know about such a channel, might have been destroyed on our
2645 end in the meantime, or never existed. Send back a DESTROY. */
2646 LOG (GNUNET_ERROR_TYPE_DEBUG,
2647 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2648 ntohl (ack->ctn.cn));
2649 GCT_send_channel_destroy (t,
2653 GCCH_handle_channel_plaintext_data_ack (ch,
2659 * We have received a request to open a channel to a port from
2660 * another peer. Creates the incoming channel.
2662 * @param cls the `struct CadetTunnel` for which we decrypted the message
2663 * @param copen the message we received on the tunnel
2666 handle_plaintext_channel_open (void *cls,
2667 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2669 struct CadetTunnel *t = cls;
2670 struct CadetChannel *ch;
2672 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2673 ntohl (copen->ctn.cn));
2676 LOG (GNUNET_ERROR_TYPE_DEBUG,
2677 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2678 GNUNET_h2s (&copen->port),
2681 GCCH_handle_duplicate_open (ch);
2684 LOG (GNUNET_ERROR_TYPE_DEBUG,
2685 "Receicved channel OPEN on port %s from %s\n",
2686 GNUNET_h2s (&copen->port),
2688 ch = GCCH_channel_incoming_new (t,
2691 ntohl (copen->opt));
2692 GNUNET_assert (GNUNET_OK ==
2693 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2694 ntohl (copen->ctn.cn),
2696 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2701 * Send a DESTROY message via the tunnel.
2703 * @param t the tunnel to transmit over
2704 * @param ctn ID of the channel to destroy
2707 GCT_send_channel_destroy (struct CadetTunnel *t,
2708 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2710 struct GNUNET_CADET_ChannelManageMessage msg;
2712 LOG (GNUNET_ERROR_TYPE_DEBUG,
2713 "Sending DESTORY message for channel ID %u\n",
2715 msg.header.size = htons (sizeof (msg));
2716 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2717 msg.reserved = htonl (0);
2727 * We have received confirmation from the target peer that the
2728 * given channel could be established (the port is open).
2731 * @param cls the `struct CadetTunnel` for which we decrypted the message
2732 * @param cm the message we received on the tunnel
2735 handle_plaintext_channel_open_ack (void *cls,
2736 const struct GNUNET_CADET_ChannelManageMessage *cm)
2738 struct CadetTunnel *t = cls;
2739 struct CadetChannel *ch;
2741 ch = lookup_channel (t,
2745 /* We don't know about such a channel, might have been destroyed on our
2746 end in the meantime, or never existed. Send back a DESTROY. */
2747 LOG (GNUNET_ERROR_TYPE_DEBUG,
2748 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2749 ntohl (cm->ctn.cn));
2750 GCT_send_channel_destroy (t,
2754 LOG (GNUNET_ERROR_TYPE_DEBUG,
2755 "Received channel OPEN_ACK on channel %s from %s\n",
2758 GCCH_handle_channel_open_ack (ch);
2763 * We received a message saying that a channel should be destroyed.
2764 * Pass it on to the correct channel.
2766 * @param cls the `struct CadetTunnel` for which we decrypted the message
2767 * @param cm the message we received on the tunnel
2770 handle_plaintext_channel_destroy (void *cls,
2771 const struct GNUNET_CADET_ChannelManageMessage *cm)
2773 struct CadetTunnel *t = cls;
2774 struct CadetChannel *ch;
2776 ch = lookup_channel (t,
2780 /* We don't know about such a channel, might have been destroyed on our
2781 end in the meantime, or never existed. */
2782 LOG (GNUNET_ERROR_TYPE_DEBUG,
2783 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2784 ntohl (cm->ctn.cn));
2787 LOG (GNUNET_ERROR_TYPE_DEBUG,
2788 "Receicved channel DESTROY on %s from %s\n",
2791 GCCH_handle_remote_destroy (ch);
2796 * Handles a message we decrypted, by injecting it into
2797 * our message queue (which will do the dispatching).
2799 * @param cls the `struct CadetTunnel` that got the message
2800 * @param msg the message
2801 * @return #GNUNET_OK (continue to process)
2804 handle_decrypted (void *cls,
2805 const struct GNUNET_MessageHeader *msg)
2807 struct CadetTunnel *t = cls;
2809 GNUNET_MQ_inject_message (t->mq,
2816 * Function called if we had an error processing
2817 * an incoming decrypted message.
2819 * @param cls the `struct CadetTunnel`
2820 * @param error error code
2823 decrypted_error_cb (void *cls,
2824 enum GNUNET_MQ_Error error)
2826 GNUNET_break_op (0);
2831 * Create a tunnel to @a destionation. Must only be called
2832 * from within #GCP_get_tunnel().
2834 * @param destination where to create the tunnel to
2835 * @return new tunnel to @a destination
2837 struct CadetTunnel *
2838 GCT_create_tunnel (struct CadetPeer *destination)
2840 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2841 struct GNUNET_MQ_MessageHandler handlers[] = {
2842 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2843 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2844 struct GNUNET_MessageHeader,
2846 GNUNET_MQ_hd_var_size (plaintext_data,
2847 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2848 struct GNUNET_CADET_ChannelAppDataMessage,
2850 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2851 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2852 struct GNUNET_CADET_ChannelDataAckMessage,
2854 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2855 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2856 struct GNUNET_CADET_ChannelOpenMessage,
2858 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2859 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2860 struct GNUNET_CADET_ChannelManageMessage,
2862 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2863 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2864 struct GNUNET_CADET_ChannelManageMessage,
2866 GNUNET_MQ_handler_end ()
2869 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2870 new_ephemeral (&t->ax);
2871 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2872 t->destination = destination;
2873 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2874 t->maintain_connections_task
2875 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2877 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2882 &decrypted_error_cb,
2884 t->mst = GNUNET_MST_create (&handle_decrypted,
2891 * Add a @a connection to the @a tunnel.
2894 * @param cid connection identifer to use for the connection
2895 * @param options options for the connection
2896 * @param path path to use for the connection
2897 * @return #GNUNET_OK on success,
2898 * #GNUNET_SYSERR on failure (duplicate connection)
2901 GCT_add_inbound_connection (struct CadetTunnel *t,
2902 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2903 enum GNUNET_CADET_ChannelOption options,
2904 struct CadetPeerPath *path)
2906 struct CadetTConnection *ct;
2908 ct = GNUNET_new (struct CadetTConnection);
2909 ct->created = GNUNET_TIME_absolute_get ();
2911 ct->cc = GCC_create_inbound (t->destination,
2916 &connection_ready_cb,
2920 LOG (GNUNET_ERROR_TYPE_DEBUG,
2921 "%s refused inbound %s (duplicate)\n",
2925 return GNUNET_SYSERR;
2927 /* FIXME: schedule job to kill connection (and path?) if it takes
2928 too long to get ready! (And track performance data on how long
2929 other connections took with the tunnel!)
2930 => Note: to be done within 'connection'-logic! */
2931 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2932 t->connection_busy_tail,
2934 t->num_busy_connections++;
2935 LOG (GNUNET_ERROR_TYPE_DEBUG,
2944 * Handle encrypted message.
2946 * @param ct connection/tunnel combo that received encrypted message
2947 * @param msg the encrypted message to decrypt
2950 GCT_handle_encrypted (struct CadetTConnection *ct,
2951 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2953 struct CadetTunnel *t = ct->t;
2954 uint16_t size = ntohs (msg->header.size);
2955 char cbuf [size] GNUNET_ALIGN;
2956 ssize_t decrypted_size;
2958 LOG (GNUNET_ERROR_TYPE_DEBUG,
2959 "%s received %u bytes of encrypted data in state %d\n",
2961 (unsigned int) size,
2966 case CADET_TUNNEL_KEY_UNINITIALIZED:
2967 case CADET_TUNNEL_KEY_AX_RECV:
2968 /* We did not even SEND our KX, how can the other peer
2969 send us encrypted data? */
2970 GNUNET_break_op (0);
2972 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2973 /* We send KX, and other peer send KX to us at the same time.
2974 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
2975 GNUNET_STATISTICS_update (stats,
2976 "# received encrypted without KX_AUTH",
2979 if (NULL != t->kx_task)
2981 GNUNET_SCHEDULER_cancel (t->kx_task);
2989 case CADET_TUNNEL_KEY_AX_SENT:
2990 /* We did not get the KX of the other peer, but that
2991 might have been lost. Send our KX again immediately. */
2992 GNUNET_STATISTICS_update (stats,
2993 "# received encrypted without KX",
2996 if (NULL != t->kx_task)
2998 GNUNET_SCHEDULER_cancel (t->kx_task);
3005 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3006 /* Great, first payload, we might graduate to OK! */
3007 case CADET_TUNNEL_KEY_OK:
3008 /* We are up and running, all good. */
3012 GNUNET_STATISTICS_update (stats,
3013 "# received encrypted",
3016 decrypted_size = -1;
3017 if (CADET_TUNNEL_KEY_OK == t->estate)
3019 /* We have well-established key material available,
3020 try that. (This is the common case.) */
3021 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3027 if ( (-1 == decrypted_size) &&
3028 (NULL != t->unverified_ax) )
3030 /* We have un-authenticated KX material available. We should try
3031 this as a back-up option, in case the sender crashed and
3033 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3037 if (-1 != decrypted_size)
3039 /* It worked! Treat this as authentication of the AX data! */
3040 t->ax.DHRs = NULL; /* aliased with ax.DHRs */
3041 t->ax.kx_0 = NULL; /* aliased with ax.DHRs */
3042 cleanup_ax (&t->ax);
3043 t->ax = *t->unverified_ax;
3044 GNUNET_free (t->unverified_ax);
3045 t->unverified_ax = NULL;
3047 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3049 /* First time it worked, move tunnel into production! */
3050 GCT_change_estate (t,
3051 CADET_TUNNEL_KEY_OK);
3052 if (NULL != t->send_task)
3053 GNUNET_SCHEDULER_cancel (t->send_task);
3054 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3058 if (NULL != t->unverified_ax)
3060 /* We had unverified KX material that was useless; so increment
3061 counter and eventually move to ignore it. Note that we even do
3062 this increment if we successfully decrypted with the old KX
3063 material and thus didn't even both with the new one. This is
3064 the ideal case, as a malicious injection of bogus KX data
3065 basically only causes us to increment a counter a few times. */
3066 t->unverified_attempts++;
3067 LOG (GNUNET_ERROR_TYPE_DEBUG,
3068 "Failed to decrypt message with unverified KX data %u times\n",
3069 t->unverified_attempts);
3070 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3072 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
3073 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
3074 cleanup_ax (t->unverified_ax);
3075 GNUNET_free (t->unverified_ax);
3076 t->unverified_ax = NULL;
3080 if (-1 == decrypted_size)
3082 /* Decryption failed for good, complain. */
3083 GNUNET_break_op (0);
3084 LOG (GNUNET_ERROR_TYPE_WARNING,
3085 "%s failed to decrypt and validate encrypted data\n",
3087 GNUNET_STATISTICS_update (stats,
3088 "# unable to decrypt",
3094 /* The MST will ultimately call #handle_decrypted() on each message. */
3095 GNUNET_break_op (GNUNET_OK ==
3096 GNUNET_MST_from_buffer (t->mst,
3105 * Sends an already built message on a tunnel, encrypting it and
3106 * choosing the best connection if not provided.
3108 * @param message Message to send. Function modifies it.
3109 * @param t Tunnel on which this message is transmitted.
3110 * @param cont Continuation to call once message is really sent.
3111 * @param cont_cls Closure for @c cont.
3112 * @return Handle to cancel message
3114 struct CadetTunnelQueueEntry *
3115 GCT_send (struct CadetTunnel *t,
3116 const struct GNUNET_MessageHeader *message,
3117 GNUNET_SCHEDULER_TaskCallback cont,
3120 struct CadetTunnelQueueEntry *tq;
3121 uint16_t payload_size;
3122 struct GNUNET_MQ_Envelope *env;
3123 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3125 if (CADET_TUNNEL_KEY_OK != t->estate)
3130 payload_size = ntohs (message->size);
3131 LOG (GNUNET_ERROR_TYPE_DEBUG,
3132 "Encrypting %u bytes for %s\n",
3133 (unsigned int) payload_size,
3135 env = GNUNET_MQ_msg_extra (ax_msg,
3137 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3138 t_ax_encrypt (&t->ax,
3142 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3143 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3144 /* FIXME: we should do this once, not once per message;
3145 this is a point multiplication, and DHRs does not
3146 change all the time. */
3147 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
3148 &ax_msg->ax_header.DHRs);
3149 t_h_encrypt (&t->ax,
3151 t_hmac (&ax_msg->ax_header,
3152 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3157 tq = GNUNET_malloc (sizeof (*tq));
3160 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3162 tq->cont_cls = cont_cls;
3163 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3166 if (NULL != t->send_task)
3167 GNUNET_SCHEDULER_cancel (t->send_task);
3169 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3176 * Cancel a previously sent message while it's in the queue.
3178 * ONLY can be called before the continuation given to the send
3179 * function is called. Once the continuation is called, the message is
3180 * no longer in the queue!
3182 * @param tq Handle to the queue entry to cancel.
3185 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3187 struct CadetTunnel *t = tq->t;
3189 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3192 GNUNET_MQ_discard (tq->env);
3198 * Iterate over all connections of a tunnel.
3200 * @param t Tunnel whose connections to iterate.
3201 * @param iter Iterator.
3202 * @param iter_cls Closure for @c iter.
3205 GCT_iterate_connections (struct CadetTunnel *t,
3206 GCT_ConnectionIterator iter,
3209 struct CadetTConnection *n;
3210 for (struct CadetTConnection *ct = t->connection_ready_head;
3218 for (struct CadetTConnection *ct = t->connection_busy_head;
3230 * Closure for #iterate_channels_cb.
3237 GCT_ChannelIterator iter;
3240 * Closure for @e iter.
3247 * Helper function for #GCT_iterate_channels.
3249 * @param cls the `struct ChanIterCls`
3251 * @param value a `struct CadetChannel`
3252 * @return #GNUNET_OK
3255 iterate_channels_cb (void *cls,
3259 struct ChanIterCls *ctx = cls;
3260 struct CadetChannel *ch = value;
3262 ctx->iter (ctx->iter_cls,
3269 * Iterate over all channels of a tunnel.
3271 * @param t Tunnel whose channels to iterate.
3272 * @param iter Iterator.
3273 * @param iter_cls Closure for @c iter.
3276 GCT_iterate_channels (struct CadetTunnel *t,
3277 GCT_ChannelIterator iter,
3280 struct ChanIterCls ctx;
3283 ctx.iter_cls = iter_cls;
3284 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3285 &iterate_channels_cb,
3292 * Call #GCCH_debug() on a channel.
3294 * @param cls points to the log level to use
3296 * @param value the `struct CadetChannel` to dump
3297 * @return #GNUNET_OK (continue iteration)
3300 debug_channel (void *cls,
3304 const enum GNUNET_ErrorType *level = cls;
3305 struct CadetChannel *ch = value;
3307 GCCH_debug (ch, *level);
3312 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3316 * Log all possible info about the tunnel state.
3318 * @param t Tunnel to debug.
3319 * @param level Debug level to use.
3322 GCT_debug (const struct CadetTunnel *t,
3323 enum GNUNET_ErrorType level)
3325 struct CadetTConnection *iter_c;
3328 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3330 __FILE__, __FUNCTION__, __LINE__);
3335 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3337 estate2s (t->estate),
3339 GCT_count_any_connections (t));
3342 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3346 "TTT connections:\n");
3347 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3348 GCC_debug (iter_c->cc,
3350 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3351 GCC_debug (iter_c->cc,
3355 "TTT TUNNEL END\n");
3359 /* end of gnunet-service-cadet-new_tunnels.c */