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 (send).
138 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141 * 32-byte header key (recv)
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146 * 32-byte next header key (send).
148 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
151 * 32-byte next header key (recv).
153 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
156 * 32-byte chain keys (used for forward-secrecy updating, send).
158 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
161 * 32-byte chain keys (used for forward-secrecy updating, recv).
163 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
166 * ECDH for key exchange (A0 / B0).
168 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
171 * ECDH Ratchet key (send).
173 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
176 * ECDH Ratchet key (recv).
178 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
181 * When does this ratchet expire and a new one is triggered.
183 struct GNUNET_TIME_Absolute ratchet_expiration;
186 * Number of elements in @a skipped_head <-> @a skipped_tail.
188 unsigned int skipped;
191 * Message number (reset to 0 with each new ratchet, next message to send).
196 * Message number (reset to 0 with each new ratchet, next message to recv).
201 * Previous message numbers (# of msgs sent under prev ratchet)
206 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
211 * Number of messages recieved since our last ratchet advance.
212 * - If this counter = 0, we cannot send a new ratchet key in next msg.
213 * - If this counter > 0, we can (but don't yet have to) send a new key.
215 unsigned int ratchet_allowed;
218 * Number of messages recieved since our last ratchet advance.
219 * - If this counter = 0, we cannot send a new ratchet key in next msg.
220 * - If this counter > 0, we can (but don't yet have to) send a new key.
222 unsigned int ratchet_counter;
228 * Struct used to save messages in a non-ready tunnel to send once connected.
230 struct CadetTunnelQueueEntry
233 * We are entries in a DLL
235 struct CadetTunnelQueueEntry *next;
238 * We are entries in a DLL
240 struct CadetTunnelQueueEntry *prev;
243 * Tunnel these messages belong in.
245 struct CadetTunnel *t;
248 * Continuation to call once sent (on the channel layer).
250 GNUNET_SCHEDULER_TaskCallback cont;
253 * Closure for @c cont.
258 * Envelope of message to send follows.
260 struct GNUNET_MQ_Envelope *env;
263 * Where to put the connection identifier into the payload
264 * of the message in @e env once we have it?
266 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
271 * Struct containing all information regarding a tunnel to a peer.
276 * Destination of the tunnel.
278 struct CadetPeer *destination;
281 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282 * ephemeral key changes.
284 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
287 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
289 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
292 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
294 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
299 struct CadetTunnelAxolotl ax;
302 * Unverified Axolotl info, used only if we got a fresh KX (not a
303 * KX_AUTH) while our end of the tunnel was still up. In this case,
304 * we keep the fresh KX around but do not put it into action until
305 * we got encrypted payload that assures us of the authenticity of
308 struct CadetTunnelAxolotl *unverified_ax;
311 * Task scheduled if there are no more channels using the tunnel.
313 struct GNUNET_SCHEDULER_Task *destroy_task;
316 * Task to trim connections if too many are present.
318 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
321 * Task to send messages from queue (if possible).
323 struct GNUNET_SCHEDULER_Task *send_task;
326 * Task to trigger KX.
328 struct GNUNET_SCHEDULER_Task *kx_task;
331 * Tokenizer for decrypted messages.
333 struct GNUNET_MessageStreamTokenizer *mst;
336 * Dispatcher for decrypted messages only (do NOT use for sending!).
338 struct GNUNET_MQ_Handle *mq;
341 * DLL of connections that are actively used to reach the destination peer.
343 struct CadetTConnection *connection_head;
346 * DLL of connections that are actively used to reach the destination peer.
348 struct CadetTConnection *connection_tail;
351 * Channels inside this tunnel. Maps
352 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
354 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
357 * Channel ID for the next created channel in this tunnel.
359 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
362 * Queued messages, to transmit once tunnel gets connected.
364 struct CadetTunnelQueueEntry *tq_head;
367 * Queued messages, to transmit once tunnel gets connected.
369 struct CadetTunnelQueueEntry *tq_tail;
372 * How long do we wait until we retry the KX?
374 struct GNUNET_TIME_Relative kx_retry_delay;
377 * When do we try the next KX?
379 struct GNUNET_TIME_Absolute next_kx_attempt;
382 * Number of connections in the @e connection_head DLL.
384 unsigned int num_connections;
387 * How often have we tried and failed to decrypt a message using
388 * the unverified KX material from @e unverified_ax? Used to
389 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
391 unsigned int unverified_attempts;
394 * Number of entries in the @e tq_head DLL.
399 * State of the tunnel encryption.
401 enum CadetTunnelEState estate;
407 * Get the static string for the peer this tunnel is directed.
411 * @return Static string the destination peer's ID.
414 GCT_2s (const struct CadetTunnel *t)
419 return "Tunnel(NULL)";
420 GNUNET_snprintf (buf,
423 GNUNET_i2s (GCP_get_id (t->destination)));
429 * Get string description for tunnel encryption state.
431 * @param es Tunnel state.
433 * @return String representation.
436 estate2s (enum CadetTunnelEState es)
442 case CADET_TUNNEL_KEY_UNINITIALIZED:
443 return "CADET_TUNNEL_KEY_UNINITIALIZED";
444 case CADET_TUNNEL_KEY_SENT:
445 return "CADET_TUNNEL_KEY_SENT";
446 case CADET_TUNNEL_KEY_PING:
447 return "CADET_TUNNEL_KEY_PING";
448 case CADET_TUNNEL_KEY_OK:
449 return "CADET_TUNNEL_KEY_OK";
450 case CADET_TUNNEL_KEY_REKEY:
451 return "CADET_TUNNEL_KEY_REKEY";
453 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
460 * Return the peer to which this tunnel goes.
463 * @return the destination of the tunnel
466 GCT_get_destination (struct CadetTunnel *t)
468 return t->destination;
473 * Count channels of a tunnel.
475 * @param t Tunnel on which to count.
477 * @return Number of channels.
480 GCT_count_channels (struct CadetTunnel *t)
482 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
487 * Lookup a channel by its @a ctn.
489 * @param t tunnel to look in
490 * @param ctn number of channel to find
491 * @return NULL if channel does not exist
493 struct CadetChannel *
494 lookup_channel (struct CadetTunnel *t,
495 struct GNUNET_CADET_ChannelTunnelNumber ctn)
497 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
503 * Count all created connections of a tunnel. Not necessarily ready connections!
505 * @param t Tunnel on which to count.
507 * @return Number of connections created, either being established or ready.
510 GCT_count_any_connections (struct CadetTunnel *t)
512 return t->num_connections;
517 * Find first connection that is ready in the list of
518 * our connections. Picks ready connections round-robin.
520 * @param t tunnel to search
521 * @return NULL if we have no connection that is ready
523 static struct CadetTConnection *
524 get_ready_connection (struct CadetTunnel *t)
526 for (struct CadetTConnection *pos = t->connection_head;
529 if (GNUNET_YES == pos->is_ready)
531 if (pos != t->connection_tail)
533 /* move 'pos' to the end, so we try other ready connections
534 first next time (round-robin, modulo availability) */
535 GNUNET_CONTAINER_DLL_remove (t->connection_head,
538 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
549 * Get the encryption state of a tunnel.
553 * @return Tunnel's encryption state.
555 enum CadetTunnelEState
556 GCT_get_estate (struct CadetTunnel *t)
563 * Called when either we have a new connection, or a new message in the
564 * queue, or some existing connection has transmission capacity. Looks
565 * at our message queue and if there is a message, picks a connection
568 * @param cls the `struct CadetTunnel` to process messages on
571 trigger_transmissions (void *cls);
574 /* ************************************** start core crypto ***************************** */
578 * Create a new Axolotl ephemeral (ratchet) key.
580 * @param ax key material to update
583 new_ephemeral (struct CadetTunnelAxolotl *ax)
585 GNUNET_free_non_null (ax->DHRs);
586 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
593 * @param plaintext Content to HMAC.
594 * @param size Size of @c plaintext.
595 * @param iv Initialization vector for the message.
596 * @param key Key to use.
597 * @param hmac[out] Destination to store the HMAC.
600 t_hmac (const void *plaintext,
603 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
604 struct GNUNET_ShortHashCode *hmac)
606 static const char ctx[] = "cadet authentication key";
607 struct GNUNET_CRYPTO_AuthKey auth_key;
608 struct GNUNET_HashCode hash;
610 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
616 /* Two step: GNUNET_ShortHash is only 256 bits,
617 GNUNET_HashCode is 512, so we truncate. */
618 GNUNET_CRYPTO_hmac (&auth_key,
631 * @param key Key to use.
632 * @param hash[out] Resulting HMAC.
633 * @param source Source key material (data to HMAC).
634 * @param len Length of @a source.
637 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
638 struct GNUNET_HashCode *hash,
642 static const char ctx[] = "axolotl HMAC-HASH";
643 struct GNUNET_CRYPTO_AuthKey auth_key;
645 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
649 GNUNET_CRYPTO_hmac (&auth_key,
657 * Derive a symmetric encryption key from an HMAC-HASH.
659 * @param key Key to use for the HMAC.
660 * @param[out] out Key to generate.
661 * @param source Source key material (data to HMAC).
662 * @param len Length of @a source.
665 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
666 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
670 static const char ctx[] = "axolotl derive key";
671 struct GNUNET_HashCode h;
677 GNUNET_CRYPTO_kdf (out, sizeof (*out),
685 * Encrypt data with the axolotl tunnel key.
687 * @param ax key material to use.
688 * @param dst Destination with @a size bytes for the encrypted data.
689 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
690 * @param size Size of the buffers at @a src and @a dst
693 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
698 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
699 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
702 ax->ratchet_counter++;
703 if ( (GNUNET_YES == ax->ratchet_allowed) &&
704 ( (ratchet_messages <= ax->ratchet_counter) ||
705 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
707 ax->ratchet_flag = GNUNET_YES;
709 if (GNUNET_YES == ax->ratchet_flag)
711 /* Advance ratchet */
712 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
713 struct GNUNET_HashCode dh;
714 struct GNUNET_HashCode hmac;
715 static const char ctx[] = "axolotl ratchet";
720 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
721 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
724 t_ax_hmac_hash (&ax->RK,
728 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
730 &hmac, sizeof (hmac),
738 ax->ratchet_flag = GNUNET_NO;
739 ax->ratchet_allowed = GNUNET_NO;
740 ax->ratchet_counter = 0;
741 ax->ratchet_expiration
742 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
746 t_hmac_derive_key (&ax->CKs,
750 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
755 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
760 GNUNET_assert (size == out_size);
761 t_hmac_derive_key (&ax->CKs,
769 * Decrypt data with the axolotl tunnel key.
771 * @param ax key material to use.
772 * @param dst Destination for the decrypted data, must contain @a size bytes.
773 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
774 * @param size Size of the @a src and @a dst buffers
777 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
782 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
783 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
786 t_hmac_derive_key (&ax->CKr,
790 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
794 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
795 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
800 GNUNET_assert (out_size == size);
801 t_hmac_derive_key (&ax->CKr,
809 * Encrypt header with the axolotl header key.
811 * @param ax key material to use.
812 * @param msg Message whose header to encrypt.
815 t_h_encrypt (struct CadetTunnelAxolotl *ax,
816 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
818 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
821 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
825 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header.Ns,
826 sizeof (struct GNUNET_CADET_AxHeader),
830 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
835 * Decrypt header with the current axolotl header key.
837 * @param ax key material to use.
838 * @param src Message whose header to decrypt.
839 * @param dst Where to decrypt header to.
842 t_h_decrypt (struct CadetTunnelAxolotl *ax,
843 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
844 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
846 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
849 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
853 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
854 sizeof (struct GNUNET_CADET_AxHeader),
858 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
863 * Delete a key from the list of skipped keys.
865 * @param ax key material to delete @a key from.
866 * @param key Key to delete.
869 delete_skipped_key (struct CadetTunnelAxolotl *ax,
870 struct CadetTunnelSkippedKey *key)
872 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
881 * Decrypt and verify data with the appropriate tunnel key and verify that the
882 * data has not been altered since it was sent by the remote peer.
884 * @param ax key material to use.
885 * @param dst Destination for the plaintext.
886 * @param src Source of the message. Can overlap with @c dst.
887 * @param size Size of the message.
888 * @return Size of the decrypted data, -1 if an error was encountered.
891 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
893 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
896 struct CadetTunnelSkippedKey *key;
897 struct GNUNET_ShortHashCode *hmac;
898 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
899 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
900 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
906 LOG (GNUNET_ERROR_TYPE_DEBUG,
907 "Trying skipped keys\n");
908 hmac = &plaintext_header.hmac;
909 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
911 /* Find a correct Header Key */
913 for (key = ax->skipped_head; NULL != key; key = key->next)
915 t_hmac (&src->ax_header,
916 sizeof (struct GNUNET_CADET_AxHeader) + esize,
920 if (0 == memcmp (hmac,
931 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
932 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
933 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
934 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
937 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
941 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
942 sizeof (struct GNUNET_CADET_AxHeader),
945 &plaintext_header.ax_header.Ns);
946 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
948 /* Find the correct message key */
949 N = ntohl (plaintext_header.ax_header.Ns);
950 while ( (NULL != key) &&
953 if ( (NULL == key) ||
954 (0 != memcmp (&key->HK,
956 sizeof (*valid_HK))) )
959 /* Decrypt payload */
960 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
965 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
970 delete_skipped_key (ax,
977 * Delete a key from the list of skipped keys.
979 * @param ax key material to delete from.
980 * @param HKr Header Key to use.
983 store_skipped_key (struct CadetTunnelAxolotl *ax,
984 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
986 struct CadetTunnelSkippedKey *key;
988 key = GNUNET_new (struct CadetTunnelSkippedKey);
989 key->timestamp = GNUNET_TIME_absolute_get ();
992 t_hmac_derive_key (&ax->CKr,
996 t_hmac_derive_key (&ax->CKr,
1000 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1009 * Stage skipped AX keys and calculate the message key.
1010 * Stores each HK and MK for skipped messages.
1012 * @param ax key material to use
1013 * @param HKr Header key.
1014 * @param Np Received meesage number.
1015 * @return #GNUNET_OK if keys were stored.
1016 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1019 store_ax_keys (struct CadetTunnelAxolotl *ax,
1020 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1026 LOG (GNUNET_ERROR_TYPE_DEBUG,
1027 "Storing skipped keys [%u, %u)\n",
1030 if (MAX_KEY_GAP < gap)
1032 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1033 /* TODO: start new key exchange on return */
1034 GNUNET_break_op (0);
1035 LOG (GNUNET_ERROR_TYPE_WARNING,
1036 "Got message %u, expected %u+\n",
1039 return GNUNET_SYSERR;
1043 /* Delayed message: don't store keys, flag to try old keys. */
1044 return GNUNET_SYSERR;
1048 store_skipped_key (ax,
1051 while (ax->skipped > MAX_SKIPPED_KEYS)
1052 delete_skipped_key (ax,
1059 * Decrypt and verify data with the appropriate tunnel key and verify that the
1060 * data has not been altered since it was sent by the remote peer.
1062 * @param ax key material to use
1063 * @param dst Destination for the plaintext.
1064 * @param src Source of the message. Can overlap with @c dst.
1065 * @param size Size of the message.
1066 * @return Size of the decrypted data, -1 if an error was encountered.
1069 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1071 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1074 struct GNUNET_ShortHashCode msg_hmac;
1075 struct GNUNET_HashCode hmac;
1076 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1079 size_t esize; /* Size of encryped payload */
1081 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1083 /* Try current HK */
1084 t_hmac (&src->ax_header,
1085 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1088 if (0 != memcmp (&msg_hmac,
1092 static const char ctx[] = "axolotl ratchet";
1093 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1094 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1095 struct GNUNET_HashCode dh;
1096 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1099 t_hmac (&src->ax_header,
1100 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1104 if (0 != memcmp (&msg_hmac,
1108 /* Try the skipped keys, if that fails, we're out of luck. */
1109 return try_old_ax_keys (ax,
1119 Np = ntohl (plaintext_header.ax_header.Ns);
1120 PNp = ntohl (plaintext_header.ax_header.PNs);
1121 DHRp = &plaintext_header.ax_header.DHRs;
1126 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1127 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1130 t_ax_hmac_hash (&ax->RK,
1133 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1135 &hmac, sizeof (hmac),
1138 /* Commit "purported" keys */
1144 ax->ratchet_allowed = GNUNET_YES;
1151 Np = ntohl (plaintext_header.ax_header.Ns);
1152 PNp = ntohl (plaintext_header.ax_header.PNs);
1154 if ( (Np != ax->Nr) &&
1155 (GNUNET_OK != store_ax_keys (ax,
1159 /* Try the skipped keys, if that fails, we're out of luck. */
1160 return try_old_ax_keys (ax,
1176 * Our tunnel became ready for the first time, notify channels
1177 * that have been waiting.
1179 * @param cls our tunnel, not used
1180 * @param key unique ID of the channel, not used
1181 * @param value the `struct CadetChannel` to notify
1182 * @return #GNUNET_OK (continue to iterate)
1185 notify_tunnel_up_cb (void *cls,
1189 struct CadetChannel *ch = value;
1191 GCCH_tunnel_up (ch);
1197 * Change the tunnel encryption state.
1198 * If the encryption state changes to OK, stop the rekey task.
1200 * @param t Tunnel whose encryption state to change, or NULL.
1201 * @param state New encryption state.
1204 GCT_change_estate (struct CadetTunnel *t,
1205 enum CadetTunnelEState state)
1207 enum CadetTunnelEState old = t->estate;
1210 LOG (GNUNET_ERROR_TYPE_DEBUG,
1211 "Tunnel %s estate changed from %d to %d\n",
1216 if ( (CADET_TUNNEL_KEY_OK != old) &&
1217 (CADET_TUNNEL_KEY_OK == t->estate) )
1219 if (NULL != t->kx_task)
1221 GNUNET_SCHEDULER_cancel (t->kx_task);
1224 if (CADET_TUNNEL_KEY_REKEY != old)
1226 /* notify all channels that have been waiting */
1227 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1228 ¬ify_tunnel_up_cb,
1232 /* FIXME: schedule rekey task! */
1238 * Send a KX message.
1240 * FIXME: does not take care of sender-authentication yet!
1242 * @param t Tunnel on which to send it.
1243 * @param ax axolotl key context to use
1244 * @param force_reply Force the other peer to reply with a KX message.
1247 send_kx (struct CadetTunnel *t,
1248 struct CadetTunnelAxolotl *ax,
1251 struct CadetTConnection *ct;
1252 struct CadetConnection *cc;
1253 struct GNUNET_MQ_Envelope *env;
1254 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1255 enum GNUNET_CADET_KX_Flags flags;
1257 ct = get_ready_connection (t);
1260 LOG (GNUNET_ERROR_TYPE_DEBUG,
1261 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1266 LOG (GNUNET_ERROR_TYPE_DEBUG,
1267 "Sending KX on tunnel %s using connection %s\n",
1271 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1272 env = GNUNET_MQ_msg (msg,
1273 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1274 flags = GNUNET_CADET_KX_FLAG_NONE;
1275 if (GNUNET_YES == force_reply)
1276 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1277 msg->flags = htonl (flags);
1278 msg->cid = *GCC_get_id (cc);
1279 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1280 &msg->ephemeral_key);
1281 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1283 ct->is_ready = GNUNET_NO;
1286 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1287 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1288 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1289 GCT_change_estate (t,
1290 CADET_TUNNEL_KEY_SENT);
1295 * Cleanup state used by @a ax.
1297 * @param ax state to free, but not memory of @a ax itself
1300 cleanup_ax (struct CadetTunnelAxolotl *ax)
1302 while (NULL != ax->skipped_head)
1303 delete_skipped_key (ax,
1305 GNUNET_assert (0 == ax->skipped);
1306 GNUNET_free_non_null (ax->kx_0);
1307 GNUNET_free_non_null (ax->DHRs);
1312 * Handle KX message that lacks authentication (and which will thus
1313 * only be considered authenticated after we respond with our own
1314 * KX_AUTH and finally successfully decrypt payload).
1316 * @param ct connection/tunnel combo that received encrypted message
1317 * @param msg the key exchange message
1320 GCT_handle_kx (struct CadetTConnection *ct,
1321 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1323 struct CadetTunnel *t = ct->t;
1324 struct CadetTunnelAxolotl *ax;
1325 struct GNUNET_HashCode key_material[3];
1326 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1327 const char salt[] = "CADET Axolotl salt";
1328 const struct GNUNET_PeerIdentity *pid;
1331 /* We only keep ONE unverified KX around, so if there is an existing one,
1333 if (NULL != t->unverified_ax)
1335 LOG (GNUNET_ERROR_TYPE_DEBUG,
1336 "Dropping old unverified KX state, got a fresh one.\n",
1337 t->unverified_attempts);
1338 cleanup_ax (t->unverified_ax);
1339 memset (t->unverified_ax,
1341 sizeof (struct CadetTunnelAxolotl));
1342 new_ephemeral (t->unverified_ax);
1343 t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1347 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1348 new_ephemeral (t->unverified_ax);
1349 t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1351 t->unverified_attempts = 0;
1352 ax = t->unverified_ax;
1354 pid = GCP_get_id (t->destination);
1355 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1357 am_I_alice = GNUNET_YES;
1358 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1360 am_I_alice = GNUNET_NO;
1363 GNUNET_break_op (0);
1367 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1369 if (NULL != t->kx_task)
1371 GNUNET_SCHEDULER_cancel (t->kx_task);
1379 if (0 == memcmp (&ax->DHRr,
1381 sizeof (msg->ratchet_key)))
1383 LOG (GNUNET_ERROR_TYPE_DEBUG,
1384 " known ratchet key, exit\n");
1388 ax->DHRr = msg->ratchet_key;
1391 if (GNUNET_YES == am_I_alice)
1393 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1394 &msg->ephemeral_key, /* B0 */
1399 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1400 &pid->public_key, /* A */
1405 if (GNUNET_YES == am_I_alice)
1407 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1408 &pid->public_key, /* B */
1413 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1414 &msg->ephemeral_key, /* B0 */
1421 /* (This is the triple-DH, we could probably safely skip this,
1422 as A0/B0 are already in the key material.) */
1423 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1424 &msg->ephemeral_key, /* B0 or A0 */
1428 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1429 salt, sizeof (salt),
1430 &key_material, sizeof (key_material),
1433 if (0 == memcmp (&ax->RK,
1437 LOG (GNUNET_ERROR_TYPE_INFO,
1438 " known handshake key, exit\n");
1441 LOG (GNUNET_ERROR_TYPE_DEBUG,
1442 "Handling KX message for tunnel %s\n",
1446 if (GNUNET_YES == am_I_alice)
1452 ax->ratchet_flag = GNUNET_YES;
1460 ax->ratchet_flag = GNUNET_NO;
1461 ax->ratchet_allowed = GNUNET_NO;
1462 ax->ratchet_counter = 0;
1463 ax->ratchet_expiration
1464 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1473 case CADET_TUNNEL_KEY_UNINITIALIZED:
1474 GCT_change_estate (t,
1475 CADET_TUNNEL_KEY_PING);
1477 case CADET_TUNNEL_KEY_SENT:
1478 /* Got a response to us sending our key; now
1479 we can start transmitting! */
1480 GCT_change_estate (t,
1481 CADET_TUNNEL_KEY_OK);
1482 if (NULL != t->send_task)
1483 GNUNET_SCHEDULER_cancel (t->send_task);
1484 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1487 case CADET_TUNNEL_KEY_PING:
1488 /* Got a key yet again; need encrypted payload to advance */
1490 case CADET_TUNNEL_KEY_OK:
1491 /* Did not expect a key, but so what. */
1493 case CADET_TUNNEL_KEY_REKEY:
1494 /* Got a key yet again; need encrypted payload to advance */
1500 /* ************************************** end core crypto ***************************** */
1504 * Compute the next free channel tunnel number for this tunnel.
1506 * @param t the tunnel
1507 * @return unused number that can uniquely identify a channel in the tunnel
1509 static struct GNUNET_CADET_ChannelTunnelNumber
1510 get_next_free_ctn (struct CadetTunnel *t)
1512 #define HIGH_BIT 0x8000000
1513 struct GNUNET_CADET_ChannelTunnelNumber ret;
1518 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1519 GCP_get_id (GCT_get_destination (t)));
1525 GNUNET_assert (0); // loopback must never go here!
1526 ctn = ntohl (t->next_ctn.cn);
1528 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1531 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1533 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1534 ret.cn = ntohl (ctn);
1540 * Add a channel to a tunnel, and notify channel that we are ready
1541 * for transmission if we are already up. Otherwise that notification
1542 * will be done later in #notify_tunnel_up_cb().
1546 * @return unique number identifying @a ch within @a t
1548 struct GNUNET_CADET_ChannelTunnelNumber
1549 GCT_add_channel (struct CadetTunnel *t,
1550 struct CadetChannel *ch)
1552 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1554 ctn = get_next_free_ctn (t);
1555 GNUNET_assert (GNUNET_YES ==
1556 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1559 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1560 LOG (GNUNET_ERROR_TYPE_DEBUG,
1561 "Adding channel %s to tunnel %s\n",
1564 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1565 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1566 GCCH_tunnel_up (ch);
1572 * We lost a connection, remove it from our list and clean up
1573 * the connection object itself.
1575 * @param ct binding of connection to tunnel of the connection that was lost.
1578 GCT_connection_lost (struct CadetTConnection *ct)
1580 struct CadetTunnel *t = ct->t;
1582 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1590 * This tunnel is no longer used, destroy it.
1592 * @param cls the idle tunnel
1595 destroy_tunnel (void *cls)
1597 struct CadetTunnel *t = cls;
1598 struct CadetTConnection *ct;
1599 struct CadetTunnelQueueEntry *tq;
1601 t->destroy_task = NULL;
1602 LOG (GNUNET_ERROR_TYPE_DEBUG,
1603 "Destroying idle tunnel %s\n",
1605 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1606 while (NULL != (ct = t->connection_head))
1608 struct CadetConnection *cc;
1610 GNUNET_assert (ct->t == t);
1612 GCT_connection_lost (ct);
1613 GCC_destroy_without_tunnel (cc);
1615 while (NULL != (tq = t->tq_head))
1617 if (NULL != tq->cont)
1618 tq->cont (tq->cont_cls);
1619 GCT_send_cancel (tq);
1621 GCP_drop_tunnel (t->destination,
1623 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1624 if (NULL != t->maintain_connections_task)
1626 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1627 t->maintain_connections_task = NULL;
1629 if (NULL != t->send_task)
1631 GNUNET_SCHEDULER_cancel (t->send_task);
1632 t->send_task = NULL;
1634 if (NULL != t->kx_task)
1636 GNUNET_SCHEDULER_cancel (t->kx_task);
1639 GNUNET_MST_destroy (t->mst);
1640 GNUNET_MQ_destroy (t->mq);
1641 cleanup_ax (&t->ax);
1642 if (NULL != t->unverified_ax)
1644 cleanup_ax (t->unverified_ax);
1645 GNUNET_free (t->unverified_ax);
1652 * Remove a channel from a tunnel.
1656 * @param ctn unique number identifying @a ch within @a t
1659 GCT_remove_channel (struct CadetTunnel *t,
1660 struct CadetChannel *ch,
1661 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1663 LOG (GNUNET_ERROR_TYPE_DEBUG,
1664 "Removing channel %s from tunnel %s\n",
1667 GNUNET_assert (GNUNET_YES ==
1668 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1672 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1674 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1682 * Destroy remaining channels during shutdown.
1684 * @param cls the `struct CadetTunnel` of the channel
1685 * @param key key of the channel
1686 * @param value the `struct CadetChannel`
1687 * @return #GNUNET_OK (continue to iterate)
1690 destroy_remaining_channels (void *cls,
1694 struct CadetChannel *ch = value;
1696 GCCH_handle_remote_destroy (ch);
1702 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1704 * @param t tunnel to destroy
1707 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1709 GNUNET_assert (GNUNET_YES == shutting_down);
1710 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1711 &destroy_remaining_channels,
1714 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1715 if (NULL != t->destroy_task)
1717 GNUNET_SCHEDULER_cancel (t->destroy_task);
1718 t->destroy_task = NULL;
1725 * It's been a while, we should try to redo the KX, if we can.
1727 * @param cls the `struct CadetTunnel` to do KX for.
1730 retry_kx (void *cls)
1732 struct CadetTunnel *t = cls;
1737 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1738 (CADET_TUNNEL_KEY_SENT == t->estate) )
1745 * Send normal payload from queue in @a t via connection @a ct.
1746 * Does nothing if our payload queue is empty.
1748 * @param t tunnel to send data from
1749 * @param ct connection to use for transmission (is ready)
1752 try_send_normal_payload (struct CadetTunnel *t,
1753 struct CadetTConnection *ct)
1755 struct CadetTunnelQueueEntry *tq;
1757 GNUNET_assert (GNUNET_YES == ct->is_ready);
1761 /* no messages pending right now */
1762 LOG (GNUNET_ERROR_TYPE_DEBUG,
1763 "Not sending payload of %s on ready %s (nothing pending)\n",
1768 /* ready to send message 'tq' on tunnel 'ct' */
1769 GNUNET_assert (t == tq->t);
1770 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1773 if (NULL != tq->cid)
1774 *tq->cid = *GCC_get_id (ct->cc);
1775 ct->is_ready = GNUNET_NO;
1776 LOG (GNUNET_ERROR_TYPE_DEBUG,
1777 "Sending payload of %s on %s\n",
1780 GCC_transmit (ct->cc,
1782 if (NULL != tq->cont)
1783 tq->cont (tq->cont_cls);
1789 * A connection is @a is_ready for transmission. Looks at our message
1790 * queue and if there is a message, sends it out via the connection.
1792 * @param cls the `struct CadetTConnection` that is @a is_ready
1793 * @param is_ready #GNUNET_YES if connection are now ready,
1794 * #GNUNET_NO if connection are no longer ready
1797 connection_ready_cb (void *cls,
1800 struct CadetTConnection *ct = cls;
1801 struct CadetTunnel *t = ct->t;
1803 if (GNUNET_NO == is_ready)
1805 LOG (GNUNET_ERROR_TYPE_DEBUG,
1806 "Connection %s no longer ready for tunnel %s\n",
1809 ct->is_ready = GNUNET_NO;
1812 ct->is_ready = GNUNET_YES;
1813 LOG (GNUNET_ERROR_TYPE_DEBUG,
1814 "Connection %s now ready for tunnel %s in state %s\n",
1817 estate2s (t->estate));
1820 case CADET_TUNNEL_KEY_UNINITIALIZED:
1825 case CADET_TUNNEL_KEY_SENT:
1826 case CADET_TUNNEL_KEY_PING:
1827 /* opportunity to #retry_kx() starts now, schedule job */
1828 if (NULL == t->kx_task)
1831 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1836 case CADET_TUNNEL_KEY_OK:
1837 try_send_normal_payload (t,
1840 case CADET_TUNNEL_KEY_REKEY:
1844 t->estate = CADET_TUNNEL_KEY_OK;
1851 * Called when either we have a new connection, or a new message in the
1852 * queue, or some existing connection has transmission capacity. Looks
1853 * at our message queue and if there is a message, picks a connection
1856 * @param cls the `struct CadetTunnel` to process messages on
1859 trigger_transmissions (void *cls)
1861 struct CadetTunnel *t = cls;
1862 struct CadetTConnection *ct;
1864 t->send_task = NULL;
1865 if (NULL == t->tq_head)
1866 return; /* no messages pending right now */
1867 ct = get_ready_connection (t);
1869 return; /* no connections ready */
1870 try_send_normal_payload (t,
1876 * Consider using the path @a p for the tunnel @a t.
1877 * The tunnel destination is at offset @a off in path @a p.
1879 * @param cls our tunnel
1880 * @param path a path to our destination
1881 * @param off offset of the destination on path @a path
1882 * @return #GNUNET_YES (should keep iterating)
1885 consider_path_cb (void *cls,
1886 struct CadetPeerPath *path,
1889 struct CadetTunnel *t = cls;
1890 unsigned int min_length = UINT_MAX;
1891 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1892 struct CadetTConnection *ct;
1894 /* Check if we care about the new path. */
1895 for (ct = t->connection_head;
1899 struct CadetPeerPath *ps;
1901 ps = GCC_get_path (ct->cc);
1904 LOG (GNUNET_ERROR_TYPE_DEBUG,
1905 "Ignoring duplicate path %s for tunnel %s.\n",
1908 return GNUNET_YES; /* duplicate */
1910 min_length = GNUNET_MIN (min_length,
1911 GCPP_get_length (ps));
1912 max_desire = GNUNET_MAX (max_desire,
1913 GCPP_get_desirability (ps));
1916 /* FIXME: not sure we should really just count
1917 'num_connections' here, as they may all have
1918 consistently failed to connect. */
1920 /* We iterate by increasing path length; if we have enough paths and
1921 this one is more than twice as long than what we are currently
1922 using, then ignore all of these super-long ones! */
1923 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1924 (min_length * 2 < off) )
1926 LOG (GNUNET_ERROR_TYPE_DEBUG,
1927 "Ignoring paths of length %u, they are way too long.\n",
1931 /* If we have enough paths and this one looks no better, ignore it. */
1932 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1933 (min_length < GCPP_get_length (path)) &&
1934 (max_desire > GCPP_get_desirability (path)) )
1936 LOG (GNUNET_ERROR_TYPE_DEBUG,
1937 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1938 GCPP_get_length (path),
1939 (unsigned long long) GCPP_get_desirability (path),
1940 GCP_2s (t->destination));
1944 /* Path is interesting (better by some metric, or we don't have
1945 enough paths yet). */
1946 ct = GNUNET_new (struct CadetTConnection);
1947 ct->created = GNUNET_TIME_absolute_get ();
1949 ct->cc = GCC_create (t->destination,
1952 &connection_ready_cb,
1954 /* FIXME: schedule job to kill connection (and path?) if it takes
1955 too long to get ready! (And track performance data on how long
1956 other connections took with the tunnel!)
1957 => Note: to be done within 'connection'-logic! */
1958 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1961 t->num_connections++;
1962 LOG (GNUNET_ERROR_TYPE_DEBUG,
1963 "Found interesting path %s for tunnel %s, created connection %s\n",
1972 * Function called to maintain the connections underlying our tunnel.
1973 * Tries to maintain (incl. tear down) connections for the tunnel, and
1974 * if there is a significant change, may trigger transmissions.
1976 * Basically, needs to check if there are connections that perform
1977 * badly, and if so eventually kill them and trigger a replacement.
1978 * The strategy is to open one more connection than
1979 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1980 * least-performing one, and then inquire for new ones.
1982 * @param cls the `struct CadetTunnel`
1985 maintain_connections_cb (void *cls)
1987 struct CadetTunnel *t = cls;
1989 t->maintain_connections_task = NULL;
1990 LOG (GNUNET_ERROR_TYPE_DEBUG,
1991 "Performing connection maintenance for tunnel %s.\n",
1994 (void) GCP_iterate_paths (t->destination,
1998 GNUNET_break (0); // FIXME: implement!
2003 * Consider using the path @a p for the tunnel @a t.
2004 * The tunnel destination is at offset @a off in path @a p.
2006 * @param cls our tunnel
2007 * @param path a path to our destination
2008 * @param off offset of the destination on path @a path
2011 GCT_consider_path (struct CadetTunnel *t,
2012 struct CadetPeerPath *p,
2015 (void) consider_path_cb (t,
2022 * We got a keepalive. Track in statistics.
2024 * @param cls the `struct CadetTunnel` for which we decrypted the message
2025 * @param msg the message we received on the tunnel
2028 handle_plaintext_keepalive (void *cls,
2029 const struct GNUNET_MessageHeader *msg)
2031 struct CadetTunnel *t = cls;
2033 LOG (GNUNET_ERROR_TYPE_DEBUG,
2034 "Received KEEPALIVE on tunnel %s\n",
2036 GNUNET_STATISTICS_update (stats,
2037 "# keepalives received",
2044 * Check that @a msg is well-formed.
2046 * @param cls the `struct CadetTunnel` for which we decrypted the message
2047 * @param msg the message we received on the tunnel
2048 * @return #GNUNET_OK (any variable-size payload goes)
2051 check_plaintext_data (void *cls,
2052 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2059 * We received payload data for a channel. Locate the channel
2060 * and process the data, or return an error if the channel is unknown.
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_data (void *cls,
2067 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2069 struct CadetTunnel *t = cls;
2070 struct CadetChannel *ch;
2072 ch = lookup_channel (t,
2076 /* We don't know about such a channel, might have been destroyed on our
2077 end in the meantime, or never existed. Send back a DESTROY. */
2078 LOG (GNUNET_ERROR_TYPE_DEBUG,
2079 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2080 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2081 ntohl (msg->ctn.cn));
2082 GCT_send_channel_destroy (t,
2086 GCCH_handle_channel_plaintext_data (ch,
2092 * We received an acknowledgement for data we sent on a channel.
2093 * Locate the channel and process it, or return an error if the
2094 * channel is unknown.
2096 * @param cls the `struct CadetTunnel` for which we decrypted the message
2097 * @param ack the message we received on the tunnel
2100 handle_plaintext_data_ack (void *cls,
2101 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2103 struct CadetTunnel *t = cls;
2104 struct CadetChannel *ch;
2106 ch = lookup_channel (t,
2110 /* We don't know about such a channel, might have been destroyed on our
2111 end in the meantime, or never existed. Send back a DESTROY. */
2112 LOG (GNUNET_ERROR_TYPE_DEBUG,
2113 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2114 ntohl (ack->ctn.cn));
2115 GCT_send_channel_destroy (t,
2119 GCCH_handle_channel_plaintext_data_ack (ch,
2125 * We have received a request to open a channel to a port from
2126 * another peer. Creates the incoming channel.
2128 * @param cls the `struct CadetTunnel` for which we decrypted the message
2129 * @param copen the message we received on the tunnel
2132 handle_plaintext_channel_open (void *cls,
2133 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2135 struct CadetTunnel *t = cls;
2136 struct CadetChannel *ch;
2138 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2139 ntohl (copen->ctn.cn));
2142 LOG (GNUNET_ERROR_TYPE_DEBUG,
2143 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2144 GNUNET_h2s (&copen->port),
2147 GCCH_handle_duplicate_open (ch);
2150 LOG (GNUNET_ERROR_TYPE_DEBUG,
2151 "Receicved channel OPEN on port %s from %s\n",
2152 GNUNET_h2s (&copen->port),
2154 ch = GCCH_channel_incoming_new (t,
2157 ntohl (copen->opt));
2158 GNUNET_assert (GNUNET_OK ==
2159 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2160 ntohl (copen->ctn.cn),
2162 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2167 * Send a DESTROY message via the tunnel.
2169 * @param t the tunnel to transmit over
2170 * @param ctn ID of the channel to destroy
2173 GCT_send_channel_destroy (struct CadetTunnel *t,
2174 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2176 struct GNUNET_CADET_ChannelManageMessage msg;
2178 LOG (GNUNET_ERROR_TYPE_DEBUG,
2179 "Sending DESTORY message for channel ID %u\n",
2181 msg.header.size = htons (sizeof (msg));
2182 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2183 msg.reserved = htonl (0);
2193 * We have received confirmation from the target peer that the
2194 * given channel could be established (the port is open).
2197 * @param cls the `struct CadetTunnel` for which we decrypted the message
2198 * @param cm the message we received on the tunnel
2201 handle_plaintext_channel_open_ack (void *cls,
2202 const struct GNUNET_CADET_ChannelManageMessage *cm)
2204 struct CadetTunnel *t = cls;
2205 struct CadetChannel *ch;
2207 ch = lookup_channel (t,
2211 /* We don't know about such a channel, might have been destroyed on our
2212 end in the meantime, or never existed. Send back a DESTROY. */
2213 LOG (GNUNET_ERROR_TYPE_DEBUG,
2214 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2215 ntohl (cm->ctn.cn));
2216 GCT_send_channel_destroy (t,
2220 LOG (GNUNET_ERROR_TYPE_DEBUG,
2221 "Received channel OPEN_ACK on channel %s from %s\n",
2224 GCCH_handle_channel_open_ack (ch);
2229 * We received a message saying that a channel should be destroyed.
2230 * Pass it on to the correct channel.
2232 * @param cls the `struct CadetTunnel` for which we decrypted the message
2233 * @param cm the message we received on the tunnel
2236 handle_plaintext_channel_destroy (void *cls,
2237 const struct GNUNET_CADET_ChannelManageMessage *cm)
2239 struct CadetTunnel *t = cls;
2240 struct CadetChannel *ch;
2242 ch = lookup_channel (t,
2246 /* We don't know about such a channel, might have been destroyed on our
2247 end in the meantime, or never existed. */
2248 LOG (GNUNET_ERROR_TYPE_DEBUG,
2249 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2250 ntohl (cm->ctn.cn));
2253 LOG (GNUNET_ERROR_TYPE_DEBUG,
2254 "Receicved channel DESTROY on %s from %s\n",
2257 GCCH_handle_remote_destroy (ch);
2262 * Handles a message we decrypted, by injecting it into
2263 * our message queue (which will do the dispatching).
2265 * @param cls the `struct CadetTunnel` that got the message
2266 * @param msg the message
2267 * @return #GNUNET_OK (continue to process)
2270 handle_decrypted (void *cls,
2271 const struct GNUNET_MessageHeader *msg)
2273 struct CadetTunnel *t = cls;
2275 GNUNET_MQ_inject_message (t->mq,
2282 * Function called if we had an error processing
2283 * an incoming decrypted message.
2285 * @param cls the `struct CadetTunnel`
2286 * @param error error code
2289 decrypted_error_cb (void *cls,
2290 enum GNUNET_MQ_Error error)
2292 GNUNET_break_op (0);
2297 * Create a tunnel to @a destionation. Must only be called
2298 * from within #GCP_get_tunnel().
2300 * @param destination where to create the tunnel to
2301 * @return new tunnel to @a destination
2303 struct CadetTunnel *
2304 GCT_create_tunnel (struct CadetPeer *destination)
2306 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2307 struct GNUNET_MQ_MessageHandler handlers[] = {
2308 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2309 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2310 struct GNUNET_MessageHeader,
2312 GNUNET_MQ_hd_var_size (plaintext_data,
2313 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2314 struct GNUNET_CADET_ChannelAppDataMessage,
2316 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2317 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2318 struct GNUNET_CADET_ChannelDataAckMessage,
2320 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2321 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2322 struct GNUNET_CADET_ChannelOpenMessage,
2324 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2325 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2326 struct GNUNET_CADET_ChannelManageMessage,
2328 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2329 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2330 struct GNUNET_CADET_ChannelManageMessage,
2332 GNUNET_MQ_handler_end ()
2335 new_ephemeral (&t->ax);
2336 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2337 t->destination = destination;
2338 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2339 t->maintain_connections_task
2340 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2342 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2347 &decrypted_error_cb,
2349 t->mst = GNUNET_MST_create (&handle_decrypted,
2356 * Add a @a connection to the @a tunnel.
2359 * @param cid connection identifer to use for the connection
2360 * @param path path to use for the connection
2361 * @return #GNUNET_OK on success,
2362 * #GNUNET_SYSERR on failure (duplicate connection)
2365 GCT_add_inbound_connection (struct CadetTunnel *t,
2366 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2367 struct CadetPeerPath *path)
2369 struct CadetTConnection *ct;
2371 ct = GNUNET_new (struct CadetTConnection);
2372 ct->created = GNUNET_TIME_absolute_get ();
2374 ct->cc = GCC_create_inbound (t->destination,
2378 &connection_ready_cb,
2382 LOG (GNUNET_ERROR_TYPE_DEBUG,
2383 "Tunnel %s refused inbound connection %s (duplicate)\n",
2387 return GNUNET_SYSERR;
2389 /* FIXME: schedule job to kill connection (and path?) if it takes
2390 too long to get ready! (And track performance data on how long
2391 other connections took with the tunnel!)
2392 => Note: to be done within 'connection'-logic! */
2393 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2396 t->num_connections++;
2397 LOG (GNUNET_ERROR_TYPE_DEBUG,
2398 "Tunnel %s has new connection %s\n",
2406 * Handle encrypted message.
2408 * @param ct connection/tunnel combo that received encrypted message
2409 * @param msg the encrypted message to decrypt
2412 GCT_handle_encrypted (struct CadetTConnection *ct,
2413 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2415 struct CadetTunnel *t = ct->t;
2416 uint16_t size = ntohs (msg->header.size);
2417 char cbuf [size] GNUNET_ALIGN;
2418 ssize_t decrypted_size;
2420 LOG (GNUNET_ERROR_TYPE_DEBUG,
2421 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2423 (unsigned int) size,
2428 case CADET_TUNNEL_KEY_UNINITIALIZED:
2429 /* We did not even SEND our KX, how can the other peer
2430 send us encrypted data? */
2431 GNUNET_break_op (0);
2433 case CADET_TUNNEL_KEY_SENT:
2434 /* We did not get the KX of the other peer, but that
2435 might have been lost. Ask for KX again. */
2436 GNUNET_STATISTICS_update (stats,
2437 "# received encrypted without KX",
2440 if (NULL != t->kx_task)
2441 GNUNET_SCHEDULER_cancel (t->kx_task);
2442 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2445 case CADET_TUNNEL_KEY_PING:
2446 /* Great, first payload, we might graduate to OK */
2447 case CADET_TUNNEL_KEY_OK:
2448 case CADET_TUNNEL_KEY_REKEY:
2452 GNUNET_STATISTICS_update (stats,
2453 "# received encrypted",
2456 decrypted_size = -1;
2457 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
2458 (CADET_TUNNEL_KEY_REKEY == t->estate) )
2460 /* We have well-established key material available,
2461 try that. (This is the common case.) */
2462 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2468 if ( (-1 == decrypted_size) &&
2469 (NULL != t->unverified_ax) )
2471 /* We have un-authenticated KX material available. We should try
2472 this as a back-up option, in case the sender crashed and
2474 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2478 if (-1 != decrypted_size)
2480 /* It worked! Treat this as authentication of the AX data! */
2481 cleanup_ax (&t->ax);
2482 t->ax = *t->unverified_ax;
2483 GNUNET_free (t->unverified_ax);
2484 t->unverified_ax = NULL;
2486 if (CADET_TUNNEL_KEY_PING == t->estate)
2488 /* First time it worked, move tunnel into production! */
2489 GCT_change_estate (t,
2490 CADET_TUNNEL_KEY_OK);
2491 if (NULL != t->send_task)
2492 GNUNET_SCHEDULER_cancel (t->send_task);
2493 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2497 if (NULL != t->unverified_ax)
2499 /* We had unverified KX material that was useless; so increment
2500 counter and eventually move to ignore it. Note that we even do
2501 this increment if we successfully decrypted with the old KX
2502 material and thus didn't even both with the new one. This is
2503 the ideal case, as a malicious injection of bogus KX data
2504 basically only causes us to increment a counter a few times. */
2505 t->unverified_attempts++;
2506 LOG (GNUNET_ERROR_TYPE_DEBUG,
2507 "Failed to decrypt message with unverified KX data %u times\n",
2508 t->unverified_attempts);
2509 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2511 cleanup_ax (t->unverified_ax);
2512 GNUNET_free (t->unverified_ax);
2513 t->unverified_ax = NULL;
2517 if (-1 == decrypted_size)
2519 /* Decryption failed for good, complain. */
2520 GNUNET_break_op (0);
2521 LOG (GNUNET_ERROR_TYPE_WARNING,
2522 "Tunnel %s failed to decrypt and validate encrypted data\n",
2524 GNUNET_STATISTICS_update (stats,
2525 "# unable to decrypt",
2531 /* The MST will ultimately call #handle_decrypted() on each message. */
2532 GNUNET_break_op (GNUNET_OK ==
2533 GNUNET_MST_from_buffer (t->mst,
2542 * Sends an already built message on a tunnel, encrypting it and
2543 * choosing the best connection if not provided.
2545 * @param message Message to send. Function modifies it.
2546 * @param t Tunnel on which this message is transmitted.
2547 * @param cont Continuation to call once message is really sent.
2548 * @param cont_cls Closure for @c cont.
2549 * @return Handle to cancel message
2551 struct CadetTunnelQueueEntry *
2552 GCT_send (struct CadetTunnel *t,
2553 const struct GNUNET_MessageHeader *message,
2554 GNUNET_SCHEDULER_TaskCallback cont,
2557 struct CadetTunnelQueueEntry *tq;
2558 uint16_t payload_size;
2559 struct GNUNET_MQ_Envelope *env;
2560 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2562 if ( (CADET_TUNNEL_KEY_OK != t->estate) &&
2563 (CADET_TUNNEL_KEY_REKEY != t->estate) )
2568 payload_size = ntohs (message->size);
2569 LOG (GNUNET_ERROR_TYPE_DEBUG,
2570 "Encrypting %u bytes for tunnel %s\n",
2571 (unsigned int) payload_size,
2573 env = GNUNET_MQ_msg_extra (ax_msg,
2575 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2576 t_ax_encrypt (&t->ax,
2580 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2581 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2582 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2583 &ax_msg->ax_header.DHRs);
2584 t_h_encrypt (&t->ax,
2586 t_hmac (&ax_msg->ax_header,
2587 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2592 tq = GNUNET_malloc (sizeof (*tq));
2595 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2597 tq->cont_cls = cont_cls;
2598 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2601 if (NULL != t->send_task)
2602 GNUNET_SCHEDULER_cancel (t->send_task);
2604 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2611 * Cancel a previously sent message while it's in the queue.
2613 * ONLY can be called before the continuation given to the send
2614 * function is called. Once the continuation is called, the message is
2615 * no longer in the queue!
2617 * @param tq Handle to the queue entry to cancel.
2620 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2622 struct CadetTunnel *t = tq->t;
2624 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2627 GNUNET_MQ_discard (tq->env);
2633 * Iterate over all connections of a tunnel.
2635 * @param t Tunnel whose connections to iterate.
2636 * @param iter Iterator.
2637 * @param iter_cls Closure for @c iter.
2640 GCT_iterate_connections (struct CadetTunnel *t,
2641 GCT_ConnectionIterator iter,
2644 for (struct CadetTConnection *ct = t->connection_head;
2653 * Closure for #iterate_channels_cb.
2660 GCT_ChannelIterator iter;
2663 * Closure for @e iter.
2670 * Helper function for #GCT_iterate_channels.
2672 * @param cls the `struct ChanIterCls`
2674 * @param value a `struct CadetChannel`
2675 * @return #GNUNET_OK
2678 iterate_channels_cb (void *cls,
2682 struct ChanIterCls *ctx = cls;
2683 struct CadetChannel *ch = value;
2685 ctx->iter (ctx->iter_cls,
2692 * Iterate over all channels of a tunnel.
2694 * @param t Tunnel whose channels to iterate.
2695 * @param iter Iterator.
2696 * @param iter_cls Closure for @c iter.
2699 GCT_iterate_channels (struct CadetTunnel *t,
2700 GCT_ChannelIterator iter,
2703 struct ChanIterCls ctx;
2706 ctx.iter_cls = iter_cls;
2707 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2708 &iterate_channels_cb,
2715 * Call #GCCH_debug() on a channel.
2717 * @param cls points to the log level to use
2719 * @param value the `struct CadetChannel` to dump
2720 * @return #GNUNET_OK (continue iteration)
2723 debug_channel (void *cls,
2727 const enum GNUNET_ErrorType *level = cls;
2728 struct CadetChannel *ch = value;
2730 GCCH_debug (ch, *level);
2735 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2739 * Log all possible info about the tunnel state.
2741 * @param t Tunnel to debug.
2742 * @param level Debug level to use.
2745 GCT_debug (const struct CadetTunnel *t,
2746 enum GNUNET_ErrorType level)
2748 struct CadetTConnection *iter_c;
2751 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2753 __FILE__, __FUNCTION__, __LINE__);
2758 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2760 estate2s (t->estate),
2762 t->num_connections);
2765 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2769 "TTT connections:\n");
2770 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2771 GCC_debug (iter_c->cc,
2775 "TTT TUNNEL END\n");
2779 /* end of gnunet-service-cadet-new_tunnels.c */