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
28 * + clean up KX logic, including adding sender authentication
29 * + implement rekeying
30 * + check KX estate machine -- make sure it is never stuck!
31 * - connection management
32 * + properly (evaluate, kill old ones, search for new ones)
33 * + when managing connections, distinguish those that
34 * have (recently) had traffic from those that were
35 * never ready (or not recently)
38 #include "gnunet_util_lib.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_signatures.h"
41 #include "gnunet-service-cadet-new.h"
42 #include "cadet_protocol.h"
43 #include "gnunet-service-cadet-new_channel.h"
44 #include "gnunet-service-cadet-new_connection.h"
45 #include "gnunet-service-cadet-new_tunnels.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
50 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
53 * How often do we try to decrypt payload with unverified key
54 * material? Used to limit CPU increase upon receiving bogus
57 #define MAX_UNVERIFIED_ATTEMPTS 16
60 * How long do we wait until tearing down an idle tunnel?
62 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
65 * Maximum number of skipped keys we keep in memory per tunnel.
67 #define MAX_SKIPPED_KEYS 64
70 * Maximum number of keys (and thus ratchet steps) we are willing to
71 * skip before we decide this is either a bogus packet or a DoS-attempt.
73 #define MAX_KEY_GAP 256
77 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
79 struct CadetTunnelSkippedKey
84 struct CadetTunnelSkippedKey *next;
89 struct CadetTunnelSkippedKey *prev;
92 * When was this key stored (for timeout).
94 struct GNUNET_TIME_Absolute timestamp;
99 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
104 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
107 * Key number for a given HK.
114 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
116 struct CadetTunnelAxolotl
119 * A (double linked) list of stored message keys and associated header keys
120 * for "skipped" messages, i.e. messages that have not been
121 * received despite the reception of more recent messages, (head).
123 struct CadetTunnelSkippedKey *skipped_head;
126 * Skipped messages' keys DLL, tail.
128 struct CadetTunnelSkippedKey *skipped_tail;
131 * 32-byte root key which gets updated by DH ratchet.
133 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
136 * 32-byte header key (currently used for sending).
138 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141 * 32-byte header key (currently used for receiving)
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146 * 32-byte next header key (for sending), used once the
147 * ratchet advances. We are sure that the sender has this
148 * key as well only after @e ratchet_allowed is #GNUNET_YES.
150 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
153 * 32-byte next header key (for receiving). To be tried
154 * when decrypting with @e HKr fails and thus the sender
155 * may have advanced the ratchet.
157 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
160 * 32-byte chain keys (used for forward-secrecy) for
161 * sending messages. Updated for every message.
163 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
166 * 32-byte chain keys (used for forward-secrecy) for
167 * receiving messages. Updated for every message. If
168 * messages are skipped, the respective derived MKs
169 * (and the current @HKr) are kept in the @e skipped_head DLL.
171 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
174 * ECDH for key exchange (A0 / B0).
176 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
179 * ECDH Ratchet key (our private key in the current DH).
181 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
184 * ECDH Ratchet key (other peer's public key in the current DH).
186 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
189 * Time when the current ratchet expires and a new one is triggered
190 * (if @e ratchet_allowed is #GNUNET_YES).
192 struct GNUNET_TIME_Absolute ratchet_expiration;
195 * Number of elements in @a skipped_head <-> @a skipped_tail.
197 unsigned int skipped;
200 * Message number (reset to 0 with each new ratchet, next message to send).
205 * Message number (reset to 0 with each new ratchet, next message to recv).
210 * Previous message numbers (# of msgs sent under prev ratchet)
215 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
220 * True (#GNUNET_YES) if we have received a message from the
221 * other peer that uses the keys from our last ratchet step.
222 * This implies that we are again allowed to advance the ratchet,
223 * otherwise we have to wait until the other peer sees our current
224 * ephemeral key and advances first.
226 * #GNUNET_NO if we have advanced the ratched but lack any evidence
227 * that the other peer has noticed this.
232 * Number of messages recieved since our last ratchet advance.
234 * If this counter = 0, we cannot send a new ratchet key in the next
237 * If this counter > 0, we could (but don't have to) send a new key.
239 * Once the @e ratchet_counter is larger than
240 * #ratchet_messages (or @e ratchet_expiration time has past), and
241 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
243 unsigned int ratchet_counter;
249 * Struct used to save messages in a non-ready tunnel to send once connected.
251 struct CadetTunnelQueueEntry
254 * We are entries in a DLL
256 struct CadetTunnelQueueEntry *next;
259 * We are entries in a DLL
261 struct CadetTunnelQueueEntry *prev;
264 * Tunnel these messages belong in.
266 struct CadetTunnel *t;
269 * Continuation to call once sent (on the channel layer).
271 GNUNET_SCHEDULER_TaskCallback cont;
274 * Closure for @c cont.
279 * Envelope of message to send follows.
281 struct GNUNET_MQ_Envelope *env;
284 * Where to put the connection identifier into the payload
285 * of the message in @e env once we have it?
287 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
292 * Struct containing all information regarding a tunnel to a peer.
297 * Destination of the tunnel.
299 struct CadetPeer *destination;
302 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
303 * ephemeral key changes.
305 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
308 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
310 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
313 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
315 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
320 struct CadetTunnelAxolotl ax;
323 * Unverified Axolotl info, used only if we got a fresh KX (not a
324 * KX_AUTH) while our end of the tunnel was still up. In this case,
325 * we keep the fresh KX around but do not put it into action until
326 * we got encrypted payload that assures us of the authenticity of
329 struct CadetTunnelAxolotl *unverified_ax;
332 * Task scheduled if there are no more channels using the tunnel.
334 struct GNUNET_SCHEDULER_Task *destroy_task;
337 * Task to trim connections if too many are present.
339 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
342 * Task to send messages from queue (if possible).
344 struct GNUNET_SCHEDULER_Task *send_task;
347 * Task to trigger KX.
349 struct GNUNET_SCHEDULER_Task *kx_task;
352 * Tokenizer for decrypted messages.
354 struct GNUNET_MessageStreamTokenizer *mst;
357 * Dispatcher for decrypted messages only (do NOT use for sending!).
359 struct GNUNET_MQ_Handle *mq;
362 * DLL of connections that are actively used to reach the destination peer.
364 struct CadetTConnection *connection_head;
367 * DLL of connections that are actively used to reach the destination peer.
369 struct CadetTConnection *connection_tail;
372 * Channels inside this tunnel. Maps
373 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
375 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
378 * Channel ID for the next created channel in this tunnel.
380 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
383 * Queued messages, to transmit once tunnel gets connected.
385 struct CadetTunnelQueueEntry *tq_head;
388 * Queued messages, to transmit once tunnel gets connected.
390 struct CadetTunnelQueueEntry *tq_tail;
393 * How long do we wait until we retry the KX?
395 struct GNUNET_TIME_Relative kx_retry_delay;
398 * When do we try the next KX?
400 struct GNUNET_TIME_Absolute next_kx_attempt;
403 * Number of connections in the @e connection_head DLL.
405 unsigned int num_connections;
408 * How often have we tried and failed to decrypt a message using
409 * the unverified KX material from @e unverified_ax? Used to
410 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
412 unsigned int unverified_attempts;
415 * Number of entries in the @e tq_head DLL.
420 * State of the tunnel encryption.
422 enum CadetTunnelEState estate;
428 * Get the static string for the peer this tunnel is directed.
432 * @return Static string the destination peer's ID.
435 GCT_2s (const struct CadetTunnel *t)
440 return "Tunnel(NULL)";
441 GNUNET_snprintf (buf,
444 GNUNET_i2s (GCP_get_id (t->destination)));
450 * Get string description for tunnel encryption state.
452 * @param es Tunnel state.
454 * @return String representation.
457 estate2s (enum CadetTunnelEState es)
463 case CADET_TUNNEL_KEY_UNINITIALIZED:
464 return "CADET_TUNNEL_KEY_UNINITIALIZED";
465 case CADET_TUNNEL_KEY_SENT:
466 return "CADET_TUNNEL_KEY_SENT";
467 case CADET_TUNNEL_KEY_PING:
468 return "CADET_TUNNEL_KEY_PING";
469 case CADET_TUNNEL_KEY_OK:
470 return "CADET_TUNNEL_KEY_OK";
472 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
479 * Return the peer to which this tunnel goes.
482 * @return the destination of the tunnel
485 GCT_get_destination (struct CadetTunnel *t)
487 return t->destination;
492 * Count channels of a tunnel.
494 * @param t Tunnel on which to count.
496 * @return Number of channels.
499 GCT_count_channels (struct CadetTunnel *t)
501 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
506 * Lookup a channel by its @a ctn.
508 * @param t tunnel to look in
509 * @param ctn number of channel to find
510 * @return NULL if channel does not exist
512 struct CadetChannel *
513 lookup_channel (struct CadetTunnel *t,
514 struct GNUNET_CADET_ChannelTunnelNumber ctn)
516 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
522 * Count all created connections of a tunnel. Not necessarily ready connections!
524 * @param t Tunnel on which to count.
526 * @return Number of connections created, either being established or ready.
529 GCT_count_any_connections (struct CadetTunnel *t)
531 return t->num_connections;
536 * Find first connection that is ready in the list of
537 * our connections. Picks ready connections round-robin.
539 * @param t tunnel to search
540 * @return NULL if we have no connection that is ready
542 static struct CadetTConnection *
543 get_ready_connection (struct CadetTunnel *t)
545 for (struct CadetTConnection *pos = t->connection_head;
548 if (GNUNET_YES == pos->is_ready)
550 if (pos != t->connection_tail)
552 /* move 'pos' to the end, so we try other ready connections
553 first next time (round-robin, modulo availability) */
554 GNUNET_CONTAINER_DLL_remove (t->connection_head,
557 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
568 * Get the encryption state of a tunnel.
572 * @return Tunnel's encryption state.
574 enum CadetTunnelEState
575 GCT_get_estate (struct CadetTunnel *t)
582 * Called when either we have a new connection, or a new message in the
583 * queue, or some existing connection has transmission capacity. Looks
584 * at our message queue and if there is a message, picks a connection
587 * @param cls the `struct CadetTunnel` to process messages on
590 trigger_transmissions (void *cls);
593 /* ************************************** start core crypto ***************************** */
597 * Create a new Axolotl ephemeral (ratchet) key.
599 * @param ax key material to update
602 new_ephemeral (struct CadetTunnelAxolotl *ax)
604 GNUNET_free_non_null (ax->DHRs);
605 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
612 * @param plaintext Content to HMAC.
613 * @param size Size of @c plaintext.
614 * @param iv Initialization vector for the message.
615 * @param key Key to use.
616 * @param hmac[out] Destination to store the HMAC.
619 t_hmac (const void *plaintext,
622 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
623 struct GNUNET_ShortHashCode *hmac)
625 static const char ctx[] = "cadet authentication key";
626 struct GNUNET_CRYPTO_AuthKey auth_key;
627 struct GNUNET_HashCode hash;
629 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
635 /* Two step: GNUNET_ShortHash is only 256 bits,
636 GNUNET_HashCode is 512, so we truncate. */
637 GNUNET_CRYPTO_hmac (&auth_key,
650 * @param key Key to use.
651 * @param[out] hash Resulting HMAC.
652 * @param source Source key material (data to HMAC).
653 * @param len Length of @a source.
656 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
657 struct GNUNET_HashCode *hash,
661 static const char ctx[] = "axolotl HMAC-HASH";
662 struct GNUNET_CRYPTO_AuthKey auth_key;
664 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
668 GNUNET_CRYPTO_hmac (&auth_key,
676 * Derive a symmetric encryption key from an HMAC-HASH.
678 * @param key Key to use for the HMAC.
679 * @param[out] out Key to generate.
680 * @param source Source key material (data to HMAC).
681 * @param len Length of @a source.
684 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
685 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
689 static const char ctx[] = "axolotl derive key";
690 struct GNUNET_HashCode h;
696 GNUNET_CRYPTO_kdf (out, sizeof (*out),
704 * Encrypt data with the axolotl tunnel key.
706 * @param ax key material to use.
707 * @param dst Destination with @a size bytes for the encrypted data.
708 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
709 * @param size Size of the buffers at @a src and @a dst
712 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
717 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
718 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
721 ax->ratchet_counter++;
722 if ( (GNUNET_YES == ax->ratchet_allowed) &&
723 ( (ratchet_messages <= ax->ratchet_counter) ||
724 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
726 ax->ratchet_flag = GNUNET_YES;
728 if (GNUNET_YES == ax->ratchet_flag)
730 /* Advance ratchet */
731 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
732 struct GNUNET_HashCode dh;
733 struct GNUNET_HashCode hmac;
734 static const char ctx[] = "axolotl ratchet";
739 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
740 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
743 t_ax_hmac_hash (&ax->RK,
747 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
749 &hmac, sizeof (hmac),
757 ax->ratchet_flag = GNUNET_NO;
758 ax->ratchet_allowed = GNUNET_NO;
759 ax->ratchet_counter = 0;
760 ax->ratchet_expiration
761 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
765 t_hmac_derive_key (&ax->CKs,
769 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
774 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
779 GNUNET_assert (size == out_size);
780 t_hmac_derive_key (&ax->CKs,
788 * Decrypt data with the axolotl tunnel key.
790 * @param ax key material to use.
791 * @param dst Destination for the decrypted data, must contain @a size bytes.
792 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
793 * @param size Size of the @a src and @a dst buffers
796 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
801 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
802 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
805 t_hmac_derive_key (&ax->CKr,
809 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
813 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
814 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
819 GNUNET_assert (out_size == size);
820 t_hmac_derive_key (&ax->CKr,
828 * Encrypt header with the axolotl header key.
830 * @param ax key material to use.
831 * @param[in|out] msg Message whose header to encrypt.
834 t_h_encrypt (struct CadetTunnelAxolotl *ax,
835 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
837 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
840 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
844 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
845 sizeof (struct GNUNET_CADET_AxHeader),
849 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
854 * Decrypt header with the current axolotl header key.
856 * @param ax key material to use.
857 * @param src Message whose header to decrypt.
858 * @param dst Where to decrypt header to.
861 t_h_decrypt (struct CadetTunnelAxolotl *ax,
862 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
863 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
865 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
868 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
872 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
873 sizeof (struct GNUNET_CADET_AxHeader),
877 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
882 * Delete a key from the list of skipped keys.
884 * @param ax key material to delete @a key from.
885 * @param key Key to delete.
888 delete_skipped_key (struct CadetTunnelAxolotl *ax,
889 struct CadetTunnelSkippedKey *key)
891 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
900 * Decrypt and verify data with the appropriate tunnel key and verify that the
901 * data has not been altered since it was sent by the remote peer.
903 * @param ax key material to use.
904 * @param dst Destination for the plaintext.
905 * @param src Source of the message. Can overlap with @c dst.
906 * @param size Size of the message.
907 * @return Size of the decrypted data, -1 if an error was encountered.
910 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
912 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
915 struct CadetTunnelSkippedKey *key;
916 struct GNUNET_ShortHashCode *hmac;
917 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
918 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
919 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
925 LOG (GNUNET_ERROR_TYPE_DEBUG,
926 "Trying skipped keys\n");
927 hmac = &plaintext_header.hmac;
928 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
930 /* Find a correct Header Key */
932 for (key = ax->skipped_head; NULL != key; key = key->next)
934 t_hmac (&src->ax_header,
935 sizeof (struct GNUNET_CADET_AxHeader) + esize,
939 if (0 == memcmp (hmac,
950 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
951 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
952 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
953 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
956 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
960 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
961 sizeof (struct GNUNET_CADET_AxHeader),
964 &plaintext_header.ax_header.Ns);
965 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
967 /* Find the correct message key */
968 N = ntohl (plaintext_header.ax_header.Ns);
969 while ( (NULL != key) &&
972 if ( (NULL == key) ||
973 (0 != memcmp (&key->HK,
975 sizeof (*valid_HK))) )
978 /* Decrypt payload */
979 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
984 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
989 delete_skipped_key (ax,
996 * Delete a key from the list of skipped keys.
998 * @param ax key material to delete from.
999 * @param HKr Header Key to use.
1002 store_skipped_key (struct CadetTunnelAxolotl *ax,
1003 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1005 struct CadetTunnelSkippedKey *key;
1007 key = GNUNET_new (struct CadetTunnelSkippedKey);
1008 key->timestamp = GNUNET_TIME_absolute_get ();
1011 t_hmac_derive_key (&ax->CKr,
1015 t_hmac_derive_key (&ax->CKr,
1019 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1028 * Stage skipped AX keys and calculate the message key.
1029 * Stores each HK and MK for skipped messages.
1031 * @param ax key material to use
1032 * @param HKr Header key.
1033 * @param Np Received meesage number.
1034 * @return #GNUNET_OK if keys were stored.
1035 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1038 store_ax_keys (struct CadetTunnelAxolotl *ax,
1039 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1045 LOG (GNUNET_ERROR_TYPE_DEBUG,
1046 "Storing skipped keys [%u, %u)\n",
1049 if (MAX_KEY_GAP < gap)
1051 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1052 /* TODO: start new key exchange on return */
1053 GNUNET_break_op (0);
1054 LOG (GNUNET_ERROR_TYPE_WARNING,
1055 "Got message %u, expected %u+\n",
1058 return GNUNET_SYSERR;
1062 /* Delayed message: don't store keys, flag to try old keys. */
1063 return GNUNET_SYSERR;
1067 store_skipped_key (ax,
1070 while (ax->skipped > MAX_SKIPPED_KEYS)
1071 delete_skipped_key (ax,
1078 * Decrypt and verify data with the appropriate tunnel key and verify that the
1079 * data has not been altered since it was sent by the remote peer.
1081 * @param ax key material to use
1082 * @param dst Destination for the plaintext.
1083 * @param src Source of the message. Can overlap with @c dst.
1084 * @param size Size of the message.
1085 * @return Size of the decrypted data, -1 if an error was encountered.
1088 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1090 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1093 struct GNUNET_ShortHashCode msg_hmac;
1094 struct GNUNET_HashCode hmac;
1095 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1098 size_t esize; /* Size of encryped payload */
1100 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1102 /* Try current HK */
1103 t_hmac (&src->ax_header,
1104 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1107 if (0 != memcmp (&msg_hmac,
1111 static const char ctx[] = "axolotl ratchet";
1112 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1113 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1114 struct GNUNET_HashCode dh;
1115 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1118 t_hmac (&src->ax_header,
1119 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1123 if (0 != memcmp (&msg_hmac,
1127 /* Try the skipped keys, if that fails, we're out of luck. */
1128 return try_old_ax_keys (ax,
1138 Np = ntohl (plaintext_header.ax_header.Ns);
1139 PNp = ntohl (plaintext_header.ax_header.PNs);
1140 DHRp = &plaintext_header.ax_header.DHRs;
1145 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1146 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1149 t_ax_hmac_hash (&ax->RK,
1152 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1154 &hmac, sizeof (hmac),
1157 /* Commit "purported" keys */
1163 ax->ratchet_allowed = GNUNET_YES;
1170 Np = ntohl (plaintext_header.ax_header.Ns);
1171 PNp = ntohl (plaintext_header.ax_header.PNs);
1173 if ( (Np != ax->Nr) &&
1174 (GNUNET_OK != store_ax_keys (ax,
1178 /* Try the skipped keys, if that fails, we're out of luck. */
1179 return try_old_ax_keys (ax,
1195 * Our tunnel became ready for the first time, notify channels
1196 * that have been waiting.
1198 * @param cls our tunnel, not used
1199 * @param key unique ID of the channel, not used
1200 * @param value the `struct CadetChannel` to notify
1201 * @return #GNUNET_OK (continue to iterate)
1204 notify_tunnel_up_cb (void *cls,
1208 struct CadetChannel *ch = value;
1210 GCCH_tunnel_up (ch);
1216 * Change the tunnel encryption state.
1217 * If the encryption state changes to OK, stop the rekey task.
1219 * @param t Tunnel whose encryption state to change, or NULL.
1220 * @param state New encryption state.
1223 GCT_change_estate (struct CadetTunnel *t,
1224 enum CadetTunnelEState state)
1226 enum CadetTunnelEState old = t->estate;
1229 LOG (GNUNET_ERROR_TYPE_DEBUG,
1230 "Tunnel %s estate changed from %d to %d\n",
1235 if ( (CADET_TUNNEL_KEY_OK != old) &&
1236 (CADET_TUNNEL_KEY_OK == t->estate) )
1238 if (NULL != t->kx_task)
1240 GNUNET_SCHEDULER_cancel (t->kx_task);
1243 /* notify all channels that have been waiting */
1244 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1245 ¬ify_tunnel_up_cb,
1252 * Send a KX message.
1254 * FIXME: does not take care of sender-authentication yet!
1256 * @param t Tunnel on which to send it.
1257 * @param ax axolotl key context to use
1258 * @param force_reply Force the other peer to reply with a KX message.
1261 send_kx (struct CadetTunnel *t,
1262 struct CadetTunnelAxolotl *ax,
1265 struct CadetTConnection *ct;
1266 struct CadetConnection *cc;
1267 struct GNUNET_MQ_Envelope *env;
1268 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1269 enum GNUNET_CADET_KX_Flags flags;
1271 ct = get_ready_connection (t);
1274 LOG (GNUNET_ERROR_TYPE_DEBUG,
1275 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1280 LOG (GNUNET_ERROR_TYPE_DEBUG,
1281 "Sending KX on tunnel %s using connection %s\n",
1285 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1286 env = GNUNET_MQ_msg (msg,
1287 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1288 flags = GNUNET_CADET_KX_FLAG_NONE;
1289 if (GNUNET_YES == force_reply)
1290 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1291 msg->flags = htonl (flags);
1292 msg->cid = *GCC_get_id (cc);
1293 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1294 &msg->ephemeral_key);
1295 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1297 ct->is_ready = GNUNET_NO;
1300 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1301 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1302 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1303 GCT_change_estate (t,
1304 CADET_TUNNEL_KEY_SENT);
1309 * Cleanup state used by @a ax.
1311 * @param ax state to free, but not memory of @a ax itself
1314 cleanup_ax (struct CadetTunnelAxolotl *ax)
1316 while (NULL != ax->skipped_head)
1317 delete_skipped_key (ax,
1319 GNUNET_assert (0 == ax->skipped);
1320 GNUNET_free_non_null (ax->kx_0);
1321 GNUNET_free_non_null (ax->DHRs);
1326 * Update our Axolotl key state based on the KX data we received.
1327 * Computes the new chain keys, and root keys, etc, and also checks
1328 * wether this is a replay of the current chain.
1330 * @param[in|out] axolotl chain key state to recompute
1331 * @param pid peer identity of the other peer
1332 * @param ephemeral_key ephemeral public key of the other peer
1333 * @param ratchet_key senders next ephemeral public key
1334 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1335 * root key is already in @a ax and thus the KX is useless;
1336 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1339 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1340 const struct GNUNET_PeerIdentity *pid,
1341 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1342 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1344 struct GNUNET_HashCode key_material[3];
1345 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1346 const char salt[] = "CADET Axolotl salt";
1349 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1351 am_I_alice = GNUNET_YES;
1352 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1354 am_I_alice = GNUNET_NO;
1357 GNUNET_break_op (0);
1358 return GNUNET_SYSERR;
1361 if (0 == memcmp (&ax->DHRr,
1363 sizeof (*ratchet_key)))
1365 LOG (GNUNET_ERROR_TYPE_DEBUG,
1366 "Ratchet key already known. Ignoring KX.\n");
1370 ax->DHRr = *ratchet_key;
1373 if (GNUNET_YES == am_I_alice)
1375 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1376 ephemeral_key, /* B0 */
1381 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1382 &pid->public_key, /* A */
1387 if (GNUNET_YES == am_I_alice)
1389 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1390 &pid->public_key, /* B */
1395 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1396 ephemeral_key, /* B0 */
1403 /* (This is the triple-DH, we could probably safely skip this,
1404 as A0/B0 are already in the key material.) */
1405 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1406 ephemeral_key, /* B0 or A0 */
1410 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1411 salt, sizeof (salt),
1412 &key_material, sizeof (key_material),
1415 if (0 == memcmp (&ax->RK,
1419 LOG (GNUNET_ERROR_TYPE_DEBUG,
1420 "Root key of handshake already known. Ignoring KX.\n");
1425 if (GNUNET_YES == am_I_alice)
1431 ax->ratchet_flag = GNUNET_YES;
1439 ax->ratchet_flag = GNUNET_NO;
1440 ax->ratchet_expiration
1441 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1449 * Handle KX message that lacks authentication (and which will thus
1450 * only be considered authenticated after we respond with our own
1451 * KX_AUTH and finally successfully decrypt payload).
1453 * @param ct connection/tunnel combo that received encrypted message
1454 * @param msg the key exchange message
1457 GCT_handle_kx (struct CadetTConnection *ct,
1458 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1460 struct CadetTunnel *t = ct->t;
1461 struct CadetTunnelAxolotl *ax;
1464 LOG (GNUNET_ERROR_TYPE_DEBUG,
1465 "Handling KX message for tunnel %s\n",
1468 /* We only keep ONE unverified KX around, so if there is an existing one,
1470 if (NULL != t->unverified_ax)
1472 LOG (GNUNET_ERROR_TYPE_DEBUG,
1473 "Dropping old unverified KX state, got a fresh one.\n",
1474 t->unverified_attempts);
1475 cleanup_ax (t->unverified_ax);
1476 memset (t->unverified_ax,
1478 sizeof (struct CadetTunnelAxolotl));
1479 new_ephemeral (t->unverified_ax);
1480 t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1484 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1485 new_ephemeral (t->unverified_ax);
1486 t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1488 /* Set as the 'current' RK the one we are currently using,
1489 so that the duplicate-detection logic of
1490 #update_ax_by_kx can work. */
1491 t->unverified_ax->RK = t->ax.RK;
1492 t->unverified_attempts = 0;
1493 ax = t->unverified_ax;
1495 /* FIXME: why this? Investigate use of kx_task! */
1496 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1498 if (NULL != t->kx_task)
1500 GNUNET_SCHEDULER_cancel (t->kx_task);
1508 /* Update 'ax' by the new key material */
1509 ret = update_ax_by_kx (ax,
1510 GCP_get_id (t->destination),
1511 &msg->ephemeral_key,
1513 GNUNET_break (GNUNET_SYSERR != ret);
1514 if (GNUNET_OK != ret)
1515 return; /* duplicate KX, nothing to do */
1517 /* move ahead in our state machine */
1520 case CADET_TUNNEL_KEY_UNINITIALIZED:
1521 GCT_change_estate (t,
1522 CADET_TUNNEL_KEY_PING);
1524 case CADET_TUNNEL_KEY_SENT:
1525 /* Got a response to us sending our key; now
1526 we can start transmitting! */
1527 GCT_change_estate (t,
1528 CADET_TUNNEL_KEY_OK);
1529 if (NULL != t->send_task)
1530 GNUNET_SCHEDULER_cancel (t->send_task);
1531 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1534 case CADET_TUNNEL_KEY_PING:
1535 /* Got a key yet again; need encrypted payload or KX_AUTH
1536 to advance to #CADET_TUNNEL_KEY_OK! */
1538 case CADET_TUNNEL_KEY_OK:
1539 /* Did not expect a key, but so what. */
1545 /* ************************************** end core crypto ***************************** */
1549 * Compute the next free channel tunnel number for this tunnel.
1551 * @param t the tunnel
1552 * @return unused number that can uniquely identify a channel in the tunnel
1554 static struct GNUNET_CADET_ChannelTunnelNumber
1555 get_next_free_ctn (struct CadetTunnel *t)
1557 #define HIGH_BIT 0x8000000
1558 struct GNUNET_CADET_ChannelTunnelNumber ret;
1563 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1564 GCP_get_id (GCT_get_destination (t)));
1570 GNUNET_assert (0); // loopback must never go here!
1571 ctn = ntohl (t->next_ctn.cn);
1573 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1576 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1578 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1579 ret.cn = ntohl (ctn);
1585 * Add a channel to a tunnel, and notify channel that we are ready
1586 * for transmission if we are already up. Otherwise that notification
1587 * will be done later in #notify_tunnel_up_cb().
1591 * @return unique number identifying @a ch within @a t
1593 struct GNUNET_CADET_ChannelTunnelNumber
1594 GCT_add_channel (struct CadetTunnel *t,
1595 struct CadetChannel *ch)
1597 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1599 ctn = get_next_free_ctn (t);
1600 GNUNET_assert (GNUNET_YES ==
1601 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1604 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1605 LOG (GNUNET_ERROR_TYPE_DEBUG,
1606 "Adding channel %s to tunnel %s\n",
1609 if (CADET_TUNNEL_KEY_OK == t->estate)
1610 GCCH_tunnel_up (ch);
1616 * We lost a connection, remove it from our list and clean up
1617 * the connection object itself.
1619 * @param ct binding of connection to tunnel of the connection that was lost.
1622 GCT_connection_lost (struct CadetTConnection *ct)
1624 struct CadetTunnel *t = ct->t;
1626 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1634 * This tunnel is no longer used, destroy it.
1636 * @param cls the idle tunnel
1639 destroy_tunnel (void *cls)
1641 struct CadetTunnel *t = cls;
1642 struct CadetTConnection *ct;
1643 struct CadetTunnelQueueEntry *tq;
1645 t->destroy_task = NULL;
1646 LOG (GNUNET_ERROR_TYPE_DEBUG,
1647 "Destroying idle tunnel %s\n",
1649 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1650 while (NULL != (ct = t->connection_head))
1652 struct CadetConnection *cc;
1654 GNUNET_assert (ct->t == t);
1656 GCT_connection_lost (ct);
1657 GCC_destroy_without_tunnel (cc);
1659 while (NULL != (tq = t->tq_head))
1661 if (NULL != tq->cont)
1662 tq->cont (tq->cont_cls);
1663 GCT_send_cancel (tq);
1665 GCP_drop_tunnel (t->destination,
1667 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1668 if (NULL != t->maintain_connections_task)
1670 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1671 t->maintain_connections_task = NULL;
1673 if (NULL != t->send_task)
1675 GNUNET_SCHEDULER_cancel (t->send_task);
1676 t->send_task = NULL;
1678 if (NULL != t->kx_task)
1680 GNUNET_SCHEDULER_cancel (t->kx_task);
1683 GNUNET_MST_destroy (t->mst);
1684 GNUNET_MQ_destroy (t->mq);
1685 cleanup_ax (&t->ax);
1686 if (NULL != t->unverified_ax)
1688 cleanup_ax (t->unverified_ax);
1689 GNUNET_free (t->unverified_ax);
1696 * Remove a channel from a tunnel.
1700 * @param ctn unique number identifying @a ch within @a t
1703 GCT_remove_channel (struct CadetTunnel *t,
1704 struct CadetChannel *ch,
1705 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1707 LOG (GNUNET_ERROR_TYPE_DEBUG,
1708 "Removing channel %s from tunnel %s\n",
1711 GNUNET_assert (GNUNET_YES ==
1712 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1716 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1718 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1726 * Destroy remaining channels during shutdown.
1728 * @param cls the `struct CadetTunnel` of the channel
1729 * @param key key of the channel
1730 * @param value the `struct CadetChannel`
1731 * @return #GNUNET_OK (continue to iterate)
1734 destroy_remaining_channels (void *cls,
1738 struct CadetChannel *ch = value;
1740 GCCH_handle_remote_destroy (ch);
1746 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1748 * @param t tunnel to destroy
1751 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1753 GNUNET_assert (GNUNET_YES == shutting_down);
1754 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1755 &destroy_remaining_channels,
1758 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1759 if (NULL != t->destroy_task)
1761 GNUNET_SCHEDULER_cancel (t->destroy_task);
1762 t->destroy_task = NULL;
1769 * It's been a while, we should try to redo the KX, if we can.
1771 * @param cls the `struct CadetTunnel` to do KX for.
1774 retry_kx (void *cls)
1776 struct CadetTunnel *t = cls;
1781 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1782 (CADET_TUNNEL_KEY_SENT == t->estate) )
1789 * Send normal payload from queue in @a t via connection @a ct.
1790 * Does nothing if our payload queue is empty.
1792 * @param t tunnel to send data from
1793 * @param ct connection to use for transmission (is ready)
1796 try_send_normal_payload (struct CadetTunnel *t,
1797 struct CadetTConnection *ct)
1799 struct CadetTunnelQueueEntry *tq;
1801 GNUNET_assert (GNUNET_YES == ct->is_ready);
1805 /* no messages pending right now */
1806 LOG (GNUNET_ERROR_TYPE_DEBUG,
1807 "Not sending payload of %s on ready %s (nothing pending)\n",
1812 /* ready to send message 'tq' on tunnel 'ct' */
1813 GNUNET_assert (t == tq->t);
1814 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1817 if (NULL != tq->cid)
1818 *tq->cid = *GCC_get_id (ct->cc);
1819 ct->is_ready = GNUNET_NO;
1820 LOG (GNUNET_ERROR_TYPE_DEBUG,
1821 "Sending payload of %s on %s\n",
1824 GCC_transmit (ct->cc,
1826 if (NULL != tq->cont)
1827 tq->cont (tq->cont_cls);
1833 * A connection is @a is_ready for transmission. Looks at our message
1834 * queue and if there is a message, sends it out via the connection.
1836 * @param cls the `struct CadetTConnection` that is @a is_ready
1837 * @param is_ready #GNUNET_YES if connection are now ready,
1838 * #GNUNET_NO if connection are no longer ready
1841 connection_ready_cb (void *cls,
1844 struct CadetTConnection *ct = cls;
1845 struct CadetTunnel *t = ct->t;
1847 if (GNUNET_NO == is_ready)
1849 LOG (GNUNET_ERROR_TYPE_DEBUG,
1850 "Connection %s no longer ready for tunnel %s\n",
1853 ct->is_ready = GNUNET_NO;
1856 ct->is_ready = GNUNET_YES;
1857 LOG (GNUNET_ERROR_TYPE_DEBUG,
1858 "Connection %s now ready for tunnel %s in state %s\n",
1861 estate2s (t->estate));
1864 case CADET_TUNNEL_KEY_UNINITIALIZED:
1869 case CADET_TUNNEL_KEY_SENT:
1870 case CADET_TUNNEL_KEY_PING:
1871 /* opportunity to #retry_kx() starts now, schedule job */
1872 if (NULL == t->kx_task)
1875 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1880 case CADET_TUNNEL_KEY_OK:
1881 try_send_normal_payload (t,
1889 * Called when either we have a new connection, or a new message in the
1890 * queue, or some existing connection has transmission capacity. Looks
1891 * at our message queue and if there is a message, picks a connection
1894 * @param cls the `struct CadetTunnel` to process messages on
1897 trigger_transmissions (void *cls)
1899 struct CadetTunnel *t = cls;
1900 struct CadetTConnection *ct;
1902 t->send_task = NULL;
1903 if (NULL == t->tq_head)
1904 return; /* no messages pending right now */
1905 ct = get_ready_connection (t);
1907 return; /* no connections ready */
1908 try_send_normal_payload (t,
1914 * Consider using the path @a p for the tunnel @a t.
1915 * The tunnel destination is at offset @a off in path @a p.
1917 * @param cls our tunnel
1918 * @param path a path to our destination
1919 * @param off offset of the destination on path @a path
1920 * @return #GNUNET_YES (should keep iterating)
1923 consider_path_cb (void *cls,
1924 struct CadetPeerPath *path,
1927 struct CadetTunnel *t = cls;
1928 unsigned int min_length = UINT_MAX;
1929 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1930 struct CadetTConnection *ct;
1932 /* Check if we care about the new path. */
1933 for (ct = t->connection_head;
1937 struct CadetPeerPath *ps;
1939 ps = GCC_get_path (ct->cc);
1942 LOG (GNUNET_ERROR_TYPE_DEBUG,
1943 "Ignoring duplicate path %s for tunnel %s.\n",
1946 return GNUNET_YES; /* duplicate */
1948 min_length = GNUNET_MIN (min_length,
1949 GCPP_get_length (ps));
1950 max_desire = GNUNET_MAX (max_desire,
1951 GCPP_get_desirability (ps));
1954 /* FIXME: not sure we should really just count
1955 'num_connections' here, as they may all have
1956 consistently failed to connect. */
1958 /* We iterate by increasing path length; if we have enough paths and
1959 this one is more than twice as long than what we are currently
1960 using, then ignore all of these super-long ones! */
1961 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1962 (min_length * 2 < off) )
1964 LOG (GNUNET_ERROR_TYPE_DEBUG,
1965 "Ignoring paths of length %u, they are way too long.\n",
1969 /* If we have enough paths and this one looks no better, ignore it. */
1970 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1971 (min_length < GCPP_get_length (path)) &&
1972 (max_desire > GCPP_get_desirability (path)) )
1974 LOG (GNUNET_ERROR_TYPE_DEBUG,
1975 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1976 GCPP_get_length (path),
1977 (unsigned long long) GCPP_get_desirability (path),
1978 GCP_2s (t->destination));
1982 /* Path is interesting (better by some metric, or we don't have
1983 enough paths yet). */
1984 ct = GNUNET_new (struct CadetTConnection);
1985 ct->created = GNUNET_TIME_absolute_get ();
1987 ct->cc = GCC_create (t->destination,
1990 &connection_ready_cb,
1992 /* FIXME: schedule job to kill connection (and path?) if it takes
1993 too long to get ready! (And track performance data on how long
1994 other connections took with the tunnel!)
1995 => Note: to be done within 'connection'-logic! */
1996 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1999 t->num_connections++;
2000 LOG (GNUNET_ERROR_TYPE_DEBUG,
2001 "Found interesting path %s for tunnel %s, created connection %s\n",
2010 * Function called to maintain the connections underlying our tunnel.
2011 * Tries to maintain (incl. tear down) connections for the tunnel, and
2012 * if there is a significant change, may trigger transmissions.
2014 * Basically, needs to check if there are connections that perform
2015 * badly, and if so eventually kill them and trigger a replacement.
2016 * The strategy is to open one more connection than
2017 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2018 * least-performing one, and then inquire for new ones.
2020 * @param cls the `struct CadetTunnel`
2023 maintain_connections_cb (void *cls)
2025 struct CadetTunnel *t = cls;
2027 t->maintain_connections_task = NULL;
2028 LOG (GNUNET_ERROR_TYPE_DEBUG,
2029 "Performing connection maintenance for tunnel %s.\n",
2032 (void) GCP_iterate_paths (t->destination,
2036 GNUNET_break (0); // FIXME: implement!
2041 * Consider using the path @a p for the tunnel @a t.
2042 * The tunnel destination is at offset @a off in path @a p.
2044 * @param cls our tunnel
2045 * @param path a path to our destination
2046 * @param off offset of the destination on path @a path
2049 GCT_consider_path (struct CadetTunnel *t,
2050 struct CadetPeerPath *p,
2053 (void) consider_path_cb (t,
2060 * We got a keepalive. Track in statistics.
2062 * @param cls the `struct CadetTunnel` for which we decrypted the message
2063 * @param msg the message we received on the tunnel
2066 handle_plaintext_keepalive (void *cls,
2067 const struct GNUNET_MessageHeader *msg)
2069 struct CadetTunnel *t = cls;
2071 LOG (GNUNET_ERROR_TYPE_DEBUG,
2072 "Received KEEPALIVE on tunnel %s\n",
2074 GNUNET_STATISTICS_update (stats,
2075 "# keepalives received",
2082 * Check that @a msg is well-formed.
2084 * @param cls the `struct CadetTunnel` for which we decrypted the message
2085 * @param msg the message we received on the tunnel
2086 * @return #GNUNET_OK (any variable-size payload goes)
2089 check_plaintext_data (void *cls,
2090 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2097 * We received payload data for a channel. Locate the channel
2098 * and process the data, or return an error if the channel is unknown.
2100 * @param cls the `struct CadetTunnel` for which we decrypted the message
2101 * @param msg the message we received on the tunnel
2104 handle_plaintext_data (void *cls,
2105 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2107 struct CadetTunnel *t = cls;
2108 struct CadetChannel *ch;
2110 ch = lookup_channel (t,
2114 /* We don't know about such a channel, might have been destroyed on our
2115 end in the meantime, or never existed. Send back a DESTROY. */
2116 LOG (GNUNET_ERROR_TYPE_DEBUG,
2117 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2118 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2119 ntohl (msg->ctn.cn));
2120 GCT_send_channel_destroy (t,
2124 GCCH_handle_channel_plaintext_data (ch,
2130 * We received an acknowledgement for data we sent on a channel.
2131 * Locate the channel and process it, or return an error if the
2132 * channel is unknown.
2134 * @param cls the `struct CadetTunnel` for which we decrypted the message
2135 * @param ack the message we received on the tunnel
2138 handle_plaintext_data_ack (void *cls,
2139 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2141 struct CadetTunnel *t = cls;
2142 struct CadetChannel *ch;
2144 ch = lookup_channel (t,
2148 /* We don't know about such a channel, might have been destroyed on our
2149 end in the meantime, or never existed. Send back a DESTROY. */
2150 LOG (GNUNET_ERROR_TYPE_DEBUG,
2151 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2152 ntohl (ack->ctn.cn));
2153 GCT_send_channel_destroy (t,
2157 GCCH_handle_channel_plaintext_data_ack (ch,
2163 * We have received a request to open a channel to a port from
2164 * another peer. Creates the incoming channel.
2166 * @param cls the `struct CadetTunnel` for which we decrypted the message
2167 * @param copen the message we received on the tunnel
2170 handle_plaintext_channel_open (void *cls,
2171 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2173 struct CadetTunnel *t = cls;
2174 struct CadetChannel *ch;
2176 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2177 ntohl (copen->ctn.cn));
2180 LOG (GNUNET_ERROR_TYPE_DEBUG,
2181 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2182 GNUNET_h2s (&copen->port),
2185 GCCH_handle_duplicate_open (ch);
2188 LOG (GNUNET_ERROR_TYPE_DEBUG,
2189 "Receicved channel OPEN on port %s from %s\n",
2190 GNUNET_h2s (&copen->port),
2192 ch = GCCH_channel_incoming_new (t,
2195 ntohl (copen->opt));
2196 GNUNET_assert (GNUNET_OK ==
2197 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2198 ntohl (copen->ctn.cn),
2200 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2205 * Send a DESTROY message via the tunnel.
2207 * @param t the tunnel to transmit over
2208 * @param ctn ID of the channel to destroy
2211 GCT_send_channel_destroy (struct CadetTunnel *t,
2212 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2214 struct GNUNET_CADET_ChannelManageMessage msg;
2216 LOG (GNUNET_ERROR_TYPE_DEBUG,
2217 "Sending DESTORY message for channel ID %u\n",
2219 msg.header.size = htons (sizeof (msg));
2220 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2221 msg.reserved = htonl (0);
2231 * We have received confirmation from the target peer that the
2232 * given channel could be established (the port is open).
2235 * @param cls the `struct CadetTunnel` for which we decrypted the message
2236 * @param cm the message we received on the tunnel
2239 handle_plaintext_channel_open_ack (void *cls,
2240 const struct GNUNET_CADET_ChannelManageMessage *cm)
2242 struct CadetTunnel *t = cls;
2243 struct CadetChannel *ch;
2245 ch = lookup_channel (t,
2249 /* We don't know about such a channel, might have been destroyed on our
2250 end in the meantime, or never existed. Send back a DESTROY. */
2251 LOG (GNUNET_ERROR_TYPE_DEBUG,
2252 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2253 ntohl (cm->ctn.cn));
2254 GCT_send_channel_destroy (t,
2258 LOG (GNUNET_ERROR_TYPE_DEBUG,
2259 "Received channel OPEN_ACK on channel %s from %s\n",
2262 GCCH_handle_channel_open_ack (ch);
2267 * We received a message saying that a channel should be destroyed.
2268 * Pass it on to the correct channel.
2270 * @param cls the `struct CadetTunnel` for which we decrypted the message
2271 * @param cm the message we received on the tunnel
2274 handle_plaintext_channel_destroy (void *cls,
2275 const struct GNUNET_CADET_ChannelManageMessage *cm)
2277 struct CadetTunnel *t = cls;
2278 struct CadetChannel *ch;
2280 ch = lookup_channel (t,
2284 /* We don't know about such a channel, might have been destroyed on our
2285 end in the meantime, or never existed. */
2286 LOG (GNUNET_ERROR_TYPE_DEBUG,
2287 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2288 ntohl (cm->ctn.cn));
2291 LOG (GNUNET_ERROR_TYPE_DEBUG,
2292 "Receicved channel DESTROY on %s from %s\n",
2295 GCCH_handle_remote_destroy (ch);
2300 * Handles a message we decrypted, by injecting it into
2301 * our message queue (which will do the dispatching).
2303 * @param cls the `struct CadetTunnel` that got the message
2304 * @param msg the message
2305 * @return #GNUNET_OK (continue to process)
2308 handle_decrypted (void *cls,
2309 const struct GNUNET_MessageHeader *msg)
2311 struct CadetTunnel *t = cls;
2313 GNUNET_MQ_inject_message (t->mq,
2320 * Function called if we had an error processing
2321 * an incoming decrypted message.
2323 * @param cls the `struct CadetTunnel`
2324 * @param error error code
2327 decrypted_error_cb (void *cls,
2328 enum GNUNET_MQ_Error error)
2330 GNUNET_break_op (0);
2335 * Create a tunnel to @a destionation. Must only be called
2336 * from within #GCP_get_tunnel().
2338 * @param destination where to create the tunnel to
2339 * @return new tunnel to @a destination
2341 struct CadetTunnel *
2342 GCT_create_tunnel (struct CadetPeer *destination)
2344 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2345 struct GNUNET_MQ_MessageHandler handlers[] = {
2346 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2347 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2348 struct GNUNET_MessageHeader,
2350 GNUNET_MQ_hd_var_size (plaintext_data,
2351 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2352 struct GNUNET_CADET_ChannelAppDataMessage,
2354 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2355 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2356 struct GNUNET_CADET_ChannelDataAckMessage,
2358 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2359 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2360 struct GNUNET_CADET_ChannelOpenMessage,
2362 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2363 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2364 struct GNUNET_CADET_ChannelManageMessage,
2366 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2367 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2368 struct GNUNET_CADET_ChannelManageMessage,
2370 GNUNET_MQ_handler_end ()
2373 new_ephemeral (&t->ax);
2374 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2375 t->destination = destination;
2376 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2377 t->maintain_connections_task
2378 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2380 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2385 &decrypted_error_cb,
2387 t->mst = GNUNET_MST_create (&handle_decrypted,
2394 * Add a @a connection to the @a tunnel.
2397 * @param cid connection identifer to use for the connection
2398 * @param path path to use for the connection
2399 * @return #GNUNET_OK on success,
2400 * #GNUNET_SYSERR on failure (duplicate connection)
2403 GCT_add_inbound_connection (struct CadetTunnel *t,
2404 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2405 struct CadetPeerPath *path)
2407 struct CadetTConnection *ct;
2409 ct = GNUNET_new (struct CadetTConnection);
2410 ct->created = GNUNET_TIME_absolute_get ();
2412 ct->cc = GCC_create_inbound (t->destination,
2416 &connection_ready_cb,
2420 LOG (GNUNET_ERROR_TYPE_DEBUG,
2421 "Tunnel %s refused inbound connection %s (duplicate)\n",
2425 return GNUNET_SYSERR;
2427 /* FIXME: schedule job to kill connection (and path?) if it takes
2428 too long to get ready! (And track performance data on how long
2429 other connections took with the tunnel!)
2430 => Note: to be done within 'connection'-logic! */
2431 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2434 t->num_connections++;
2435 LOG (GNUNET_ERROR_TYPE_DEBUG,
2436 "Tunnel %s has new connection %s\n",
2444 * Handle encrypted message.
2446 * @param ct connection/tunnel combo that received encrypted message
2447 * @param msg the encrypted message to decrypt
2450 GCT_handle_encrypted (struct CadetTConnection *ct,
2451 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2453 struct CadetTunnel *t = ct->t;
2454 uint16_t size = ntohs (msg->header.size);
2455 char cbuf [size] GNUNET_ALIGN;
2456 ssize_t decrypted_size;
2458 LOG (GNUNET_ERROR_TYPE_DEBUG,
2459 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2461 (unsigned int) size,
2466 case CADET_TUNNEL_KEY_UNINITIALIZED:
2467 /* We did not even SEND our KX, how can the other peer
2468 send us encrypted data? */
2469 GNUNET_break_op (0);
2471 case CADET_TUNNEL_KEY_SENT:
2472 /* We did not get the KX of the other peer, but that
2473 might have been lost. Ask for KX again. */
2474 GNUNET_STATISTICS_update (stats,
2475 "# received encrypted without KX",
2478 if (NULL != t->kx_task)
2479 GNUNET_SCHEDULER_cancel (t->kx_task);
2480 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2483 case CADET_TUNNEL_KEY_PING:
2484 /* Great, first payload, we might graduate to OK */
2485 case CADET_TUNNEL_KEY_OK:
2489 GNUNET_STATISTICS_update (stats,
2490 "# received encrypted",
2493 decrypted_size = -1;
2494 if (CADET_TUNNEL_KEY_OK == t->estate)
2496 /* We have well-established key material available,
2497 try that. (This is the common case.) */
2498 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2504 if ( (-1 == decrypted_size) &&
2505 (NULL != t->unverified_ax) )
2507 /* We have un-authenticated KX material available. We should try
2508 this as a back-up option, in case the sender crashed and
2510 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2514 if (-1 != decrypted_size)
2516 /* It worked! Treat this as authentication of the AX data! */
2517 cleanup_ax (&t->ax);
2518 t->ax = *t->unverified_ax;
2519 GNUNET_free (t->unverified_ax);
2520 t->unverified_ax = NULL;
2522 if (CADET_TUNNEL_KEY_PING == t->estate)
2524 /* First time it worked, move tunnel into production! */
2525 GCT_change_estate (t,
2526 CADET_TUNNEL_KEY_OK);
2527 if (NULL != t->send_task)
2528 GNUNET_SCHEDULER_cancel (t->send_task);
2529 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2533 if (NULL != t->unverified_ax)
2535 /* We had unverified KX material that was useless; so increment
2536 counter and eventually move to ignore it. Note that we even do
2537 this increment if we successfully decrypted with the old KX
2538 material and thus didn't even both with the new one. This is
2539 the ideal case, as a malicious injection of bogus KX data
2540 basically only causes us to increment a counter a few times. */
2541 t->unverified_attempts++;
2542 LOG (GNUNET_ERROR_TYPE_DEBUG,
2543 "Failed to decrypt message with unverified KX data %u times\n",
2544 t->unverified_attempts);
2545 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2547 cleanup_ax (t->unverified_ax);
2548 GNUNET_free (t->unverified_ax);
2549 t->unverified_ax = NULL;
2553 if (-1 == decrypted_size)
2555 /* Decryption failed for good, complain. */
2556 GNUNET_break_op (0);
2557 LOG (GNUNET_ERROR_TYPE_WARNING,
2558 "Tunnel %s failed to decrypt and validate encrypted data\n",
2560 GNUNET_STATISTICS_update (stats,
2561 "# unable to decrypt",
2567 /* The MST will ultimately call #handle_decrypted() on each message. */
2568 GNUNET_break_op (GNUNET_OK ==
2569 GNUNET_MST_from_buffer (t->mst,
2578 * Sends an already built message on a tunnel, encrypting it and
2579 * choosing the best connection if not provided.
2581 * @param message Message to send. Function modifies it.
2582 * @param t Tunnel on which this message is transmitted.
2583 * @param cont Continuation to call once message is really sent.
2584 * @param cont_cls Closure for @c cont.
2585 * @return Handle to cancel message
2587 struct CadetTunnelQueueEntry *
2588 GCT_send (struct CadetTunnel *t,
2589 const struct GNUNET_MessageHeader *message,
2590 GNUNET_SCHEDULER_TaskCallback cont,
2593 struct CadetTunnelQueueEntry *tq;
2594 uint16_t payload_size;
2595 struct GNUNET_MQ_Envelope *env;
2596 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2598 if (CADET_TUNNEL_KEY_OK != t->estate)
2603 payload_size = ntohs (message->size);
2604 LOG (GNUNET_ERROR_TYPE_DEBUG,
2605 "Encrypting %u bytes for tunnel %s\n",
2606 (unsigned int) payload_size,
2608 env = GNUNET_MQ_msg_extra (ax_msg,
2610 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2611 t_ax_encrypt (&t->ax,
2615 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2616 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2617 /* FIXME: we should do this once, not once per message;
2618 this is a point multiplication, and DHRs does not
2619 change all the time. */
2620 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2621 &ax_msg->ax_header.DHRs);
2622 t_h_encrypt (&t->ax,
2624 t_hmac (&ax_msg->ax_header,
2625 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2630 tq = GNUNET_malloc (sizeof (*tq));
2633 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2635 tq->cont_cls = cont_cls;
2636 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2639 if (NULL != t->send_task)
2640 GNUNET_SCHEDULER_cancel (t->send_task);
2642 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2649 * Cancel a previously sent message while it's in the queue.
2651 * ONLY can be called before the continuation given to the send
2652 * function is called. Once the continuation is called, the message is
2653 * no longer in the queue!
2655 * @param tq Handle to the queue entry to cancel.
2658 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2660 struct CadetTunnel *t = tq->t;
2662 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2665 GNUNET_MQ_discard (tq->env);
2671 * Iterate over all connections of a tunnel.
2673 * @param t Tunnel whose connections to iterate.
2674 * @param iter Iterator.
2675 * @param iter_cls Closure for @c iter.
2678 GCT_iterate_connections (struct CadetTunnel *t,
2679 GCT_ConnectionIterator iter,
2682 for (struct CadetTConnection *ct = t->connection_head;
2691 * Closure for #iterate_channels_cb.
2698 GCT_ChannelIterator iter;
2701 * Closure for @e iter.
2708 * Helper function for #GCT_iterate_channels.
2710 * @param cls the `struct ChanIterCls`
2712 * @param value a `struct CadetChannel`
2713 * @return #GNUNET_OK
2716 iterate_channels_cb (void *cls,
2720 struct ChanIterCls *ctx = cls;
2721 struct CadetChannel *ch = value;
2723 ctx->iter (ctx->iter_cls,
2730 * Iterate over all channels of a tunnel.
2732 * @param t Tunnel whose channels to iterate.
2733 * @param iter Iterator.
2734 * @param iter_cls Closure for @c iter.
2737 GCT_iterate_channels (struct CadetTunnel *t,
2738 GCT_ChannelIterator iter,
2741 struct ChanIterCls ctx;
2744 ctx.iter_cls = iter_cls;
2745 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2746 &iterate_channels_cb,
2753 * Call #GCCH_debug() on a channel.
2755 * @param cls points to the log level to use
2757 * @param value the `struct CadetChannel` to dump
2758 * @return #GNUNET_OK (continue iteration)
2761 debug_channel (void *cls,
2765 const enum GNUNET_ErrorType *level = cls;
2766 struct CadetChannel *ch = value;
2768 GCCH_debug (ch, *level);
2773 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2777 * Log all possible info about the tunnel state.
2779 * @param t Tunnel to debug.
2780 * @param level Debug level to use.
2783 GCT_debug (const struct CadetTunnel *t,
2784 enum GNUNET_ErrorType level)
2786 struct CadetTConnection *iter_c;
2789 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2791 __FILE__, __FUNCTION__, __LINE__);
2796 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2798 estate2s (t->estate),
2800 t->num_connections);
2803 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2807 "TTT connections:\n");
2808 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2809 GCC_debug (iter_c->cc,
2813 "TTT TUNNEL END\n");
2817 /* end of gnunet-service-cadet-new_tunnels.c */