2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
27 * - implement keepalive
28 * - implement rekeying
29 * - check KX estate machine -- make sure it is never stuck!
30 * - clean up KX logic, including adding sender authentication
31 * - implement connection management (evaluate, kill old ones,
32 * 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__)
54 * How long do we wait until tearing down an idle tunnel?
56 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
59 * Yuck, replace by 'offsetof' expression?
62 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
63 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
67 * Maximum number of skipped keys we keep in memory per tunnel.
69 #define MAX_SKIPPED_KEYS 64
72 * Maximum number of keys (and thus ratchet steps) we are willing to
73 * skip before we decide this is either a bogus packet or a DoS-attempt.
75 #define MAX_KEY_GAP 256
79 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
81 struct CadetTunnelSkippedKey
86 struct CadetTunnelSkippedKey *next;
91 struct CadetTunnelSkippedKey *prev;
94 * When was this key stored (for timeout).
96 struct GNUNET_TIME_Absolute timestamp;
101 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
106 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
109 * Key number for a given HK.
116 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
118 struct CadetTunnelAxolotl
121 * A (double linked) list of stored message keys and associated header keys
122 * for "skipped" messages, i.e. messages that have not been
123 * received despite the reception of more recent messages, (head).
125 struct CadetTunnelSkippedKey *skipped_head;
128 * Skipped messages' keys DLL, tail.
130 struct CadetTunnelSkippedKey *skipped_tail;
133 * 32-byte root key which gets updated by DH ratchet.
135 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
138 * 32-byte header key (send).
140 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
143 * 32-byte header key (recv)
145 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
148 * 32-byte next header key (send).
150 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
153 * 32-byte next header key (recv).
155 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
158 * 32-byte chain keys (used for forward-secrecy updating, send).
160 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
163 * 32-byte chain keys (used for forward-secrecy updating, recv).
165 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
168 * ECDH for key exchange (A0 / B0).
170 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
173 * ECDH Ratchet key (send).
175 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
178 * ECDH Ratchet key (recv).
180 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
183 * When does this ratchet expire and a new one is triggered.
185 struct GNUNET_TIME_Absolute ratchet_expiration;
188 * Number of elements in @a skipped_head <-> @a skipped_tail.
190 unsigned int skipped;
193 * Message number (reset to 0 with each new ratchet, next message to send).
198 * Message number (reset to 0 with each new ratchet, next message to recv).
203 * Previous message numbers (# of msgs sent under prev ratchet)
208 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
213 * Number of messages recieved since our last ratchet advance.
214 * - If this counter = 0, we cannot send a new ratchet key in next msg.
215 * - If this counter > 0, we can (but don't yet have to) send a new key.
217 unsigned int ratchet_allowed;
220 * Number of messages recieved since our last ratchet advance.
221 * - If this counter = 0, we cannot send a new ratchet key in next msg.
222 * - If this counter > 0, we can (but don't yet have to) send a new key.
224 unsigned int ratchet_counter;
230 * Struct used to save messages in a non-ready tunnel to send once connected.
232 struct CadetTunnelQueueEntry
235 * We are entries in a DLL
237 struct CadetTunnelQueueEntry *next;
240 * We are entries in a DLL
242 struct CadetTunnelQueueEntry *prev;
245 * Tunnel these messages belong in.
247 struct CadetTunnel *t;
250 * Continuation to call once sent (on the channel layer).
252 GNUNET_SCHEDULER_TaskCallback cont;
255 * Closure for @c cont.
260 * Envelope of message to send follows.
262 struct GNUNET_MQ_Envelope *env;
265 * Where to put the connection identifier into the payload
266 * of the message in @e env once we have it?
268 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
273 * Struct containing all information regarding a tunnel to a peer.
278 * Destination of the tunnel.
280 struct CadetPeer *destination;
283 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
284 * ephemeral key changes.
286 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
289 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
291 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
294 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
296 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
301 struct CadetTunnelAxolotl ax;
304 * Task scheduled if there are no more channels using the tunnel.
306 struct GNUNET_SCHEDULER_Task *destroy_task;
309 * Task to trim connections if too many are present.
311 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
314 * Task to send messages from queue (if possible).
316 struct GNUNET_SCHEDULER_Task *send_task;
319 * Task to trigger KX.
321 struct GNUNET_SCHEDULER_Task *kx_task;
324 * Tokenizer for decrypted messages.
326 struct GNUNET_MessageStreamTokenizer *mst;
329 * Dispatcher for decrypted messages only (do NOT use for sending!).
331 struct GNUNET_MQ_Handle *mq;
334 * DLL of connections that are actively used to reach the destination peer.
336 struct CadetTConnection *connection_head;
339 * DLL of connections that are actively used to reach the destination peer.
341 struct CadetTConnection *connection_tail;
344 * Channels inside this tunnel. Maps
345 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
347 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
350 * Channel ID for the next created channel in this tunnel.
352 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
355 * Queued messages, to transmit once tunnel gets connected.
357 struct CadetTunnelQueueEntry *tq_head;
360 * Queued messages, to transmit once tunnel gets connected.
362 struct CadetTunnelQueueEntry *tq_tail;
366 * Ephemeral message in the queue (to avoid queueing more than one).
368 struct CadetConnectionQueue *ephm_hKILL;
371 * Pong message in the queue.
373 struct CadetConnectionQueue *pong_hKILL;
376 * How long do we wait until we retry the KX?
378 struct GNUNET_TIME_Relative kx_retry_delay;
381 * When do we try the next KX?
383 struct GNUNET_TIME_Absolute next_kx_attempt;
386 * Number of connections in the @e connection_head DLL.
388 unsigned int num_connections;
391 * Number of entries in the @e tq_head DLL.
396 * State of the tunnel encryption.
398 enum CadetTunnelEState estate;
404 * Get the static string for the peer this tunnel is directed.
408 * @return Static string the destination peer's ID.
411 GCT_2s (const struct CadetTunnel *t)
416 return "Tunnel(NULL)";
417 GNUNET_snprintf (buf,
420 GNUNET_i2s (GCP_get_id (t->destination)));
426 * Get string description for tunnel encryption state.
428 * @param es Tunnel state.
430 * @return String representation.
433 estate2s (enum CadetTunnelEState es)
439 case CADET_TUNNEL_KEY_UNINITIALIZED:
440 return "CADET_TUNNEL_KEY_UNINITIALIZED";
441 case CADET_TUNNEL_KEY_SENT:
442 return "CADET_TUNNEL_KEY_SENT";
443 case CADET_TUNNEL_KEY_PING:
444 return "CADET_TUNNEL_KEY_PING";
445 case CADET_TUNNEL_KEY_OK:
446 return "CADET_TUNNEL_KEY_OK";
447 case CADET_TUNNEL_KEY_REKEY:
448 return "CADET_TUNNEL_KEY_REKEY";
450 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
457 * Return the peer to which this tunnel goes.
460 * @return the destination of the tunnel
463 GCT_get_destination (struct CadetTunnel *t)
465 return t->destination;
470 * Count channels of a tunnel.
472 * @param t Tunnel on which to count.
474 * @return Number of channels.
477 GCT_count_channels (struct CadetTunnel *t)
479 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
484 * Lookup a channel by its @a ctn.
486 * @param t tunnel to look in
487 * @param ctn number of channel to find
488 * @return NULL if channel does not exist
490 struct CadetChannel *
491 lookup_channel (struct CadetTunnel *t,
492 struct GNUNET_CADET_ChannelTunnelNumber ctn)
494 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
500 * Count all created connections of a tunnel. Not necessarily ready connections!
502 * @param t Tunnel on which to count.
504 * @return Number of connections created, either being established or ready.
507 GCT_count_any_connections (struct CadetTunnel *t)
509 return t->num_connections;
514 * Find first connection that is ready in the list of
515 * our connections. Picks ready connections round-robin.
517 * @param t tunnel to search
518 * @return NULL if we have no connection that is ready
520 static struct CadetTConnection *
521 get_ready_connection (struct CadetTunnel *t)
523 for (struct CadetTConnection *pos = t->connection_head;
526 if (GNUNET_YES == pos->is_ready)
528 if (pos != t->connection_tail)
530 /* move 'pos' to the end, so we try other ready connections
531 first next time (round-robin, modulo availability) */
532 GNUNET_CONTAINER_DLL_remove (t->connection_head,
535 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
546 * Get the encryption state of a tunnel.
550 * @return Tunnel's encryption state.
552 enum CadetTunnelEState
553 GCT_get_estate (struct CadetTunnel *t)
560 * Create a new Axolotl ephemeral (ratchet) key.
565 new_ephemeral (struct CadetTunnel *t)
567 GNUNET_free_non_null (t->ax.DHRs);
568 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
574 * Called when either we have a new connection, or a new message in the
575 * queue, or some existing connection has transmission capacity. Looks
576 * at our message queue and if there is a message, picks a connection
579 * @param cls the `struct CadetTunnel` to process messages on
582 trigger_transmissions (void *cls);
585 /* ************************************** start core crypto ***************************** */
591 * @param plaintext Content to HMAC.
592 * @param size Size of @c plaintext.
593 * @param iv Initialization vector for the message.
594 * @param key Key to use.
595 * @param hmac[out] Destination to store the HMAC.
598 t_hmac (const void *plaintext,
601 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
602 struct GNUNET_ShortHashCode *hmac)
604 static const char ctx[] = "cadet authentication key";
605 struct GNUNET_CRYPTO_AuthKey auth_key;
606 struct GNUNET_HashCode hash;
608 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
614 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
615 GNUNET_CRYPTO_hmac (&auth_key,
628 * @param key Key to use.
629 * @param hash[out] Resulting HMAC.
630 * @param source Source key material (data to HMAC).
631 * @param len Length of @a source.
634 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
635 struct GNUNET_HashCode *hash,
639 static const char ctx[] = "axolotl HMAC-HASH";
640 struct GNUNET_CRYPTO_AuthKey auth_key;
642 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
646 GNUNET_CRYPTO_hmac (&auth_key,
654 * Derive a symmetric encryption key from an HMAC-HASH.
656 * @param key Key to use for the HMAC.
657 * @param[out] out Key to generate.
658 * @param source Source key material (data to HMAC).
659 * @param len Length of @a source.
662 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
663 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
667 static const char ctx[] = "axolotl derive key";
668 struct GNUNET_HashCode h;
674 GNUNET_CRYPTO_kdf (out, sizeof (*out),
682 * Encrypt data with the axolotl tunnel key.
684 * @param t Tunnel whose key to use.
685 * @param dst Destination with @a size bytes for the encrypted data.
686 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
687 * @param size Size of the buffers at @a src and @a dst
690 t_ax_encrypt (struct CadetTunnel *t,
695 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
696 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
697 struct CadetTunnelAxolotl *ax;
701 ax->ratchet_counter++;
702 if ( (GNUNET_YES == ax->ratchet_allowed) &&
703 ( (ratchet_messages <= ax->ratchet_counter) ||
704 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
706 ax->ratchet_flag = GNUNET_YES;
708 if (GNUNET_YES == ax->ratchet_flag)
710 /* Advance ratchet */
711 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
712 struct GNUNET_HashCode dh;
713 struct GNUNET_HashCode hmac;
714 static const char ctx[] = "axolotl ratchet";
719 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
720 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
723 t_ax_hmac_hash (&ax->RK,
727 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
729 &hmac, sizeof (hmac),
737 ax->ratchet_flag = GNUNET_NO;
738 ax->ratchet_allowed = GNUNET_NO;
739 ax->ratchet_counter = 0;
740 ax->ratchet_expiration
741 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
745 t_hmac_derive_key (&ax->CKs,
749 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
754 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
759 GNUNET_assert (size == out_size);
760 t_hmac_derive_key (&ax->CKs,
768 * Decrypt data with the axolotl tunnel key.
770 * @param t Tunnel whose key to use.
771 * @param dst Destination for the decrypted data, must contain @a size bytes.
772 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
773 * @param size Size of the @a src and @a dst buffers
776 t_ax_decrypt (struct CadetTunnel *t,
781 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
782 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
783 struct CadetTunnelAxolotl *ax;
787 t_hmac_derive_key (&ax->CKr,
791 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
795 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
796 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
801 GNUNET_assert (out_size == size);
802 t_hmac_derive_key (&ax->CKr,
810 * Encrypt header with the axolotl header key.
812 * @param t Tunnel whose key to use.
813 * @param msg Message whose header to encrypt.
816 t_h_encrypt (struct CadetTunnel *t,
817 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
819 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
820 struct CadetTunnelAxolotl *ax;
824 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
828 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
833 GNUNET_assert (AX_HEADER_SIZE == out_size);
838 * Decrypt header with the current axolotl header key.
840 * @param t Tunnel whose current ax HK to use.
841 * @param src Message whose header to decrypt.
842 * @param dst Where to decrypt header to.
845 t_h_decrypt (struct CadetTunnel *t,
846 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
847 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
849 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
850 struct CadetTunnelAxolotl *ax;
854 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
858 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
863 GNUNET_assert (AX_HEADER_SIZE == out_size);
868 * Delete a key from the list of skipped keys.
870 * @param t Tunnel to delete from.
871 * @param key Key to delete.
874 delete_skipped_key (struct CadetTunnel *t,
875 struct CadetTunnelSkippedKey *key)
877 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
886 * Decrypt and verify data with the appropriate tunnel key and verify that the
887 * data has not been altered since it was sent by the remote peer.
889 * @param t Tunnel whose key to use.
890 * @param dst Destination for the plaintext.
891 * @param src Source of the message. Can overlap with @c dst.
892 * @param size Size of the message.
893 * @return Size of the decrypted data, -1 if an error was encountered.
896 try_old_ax_keys (struct CadetTunnel *t,
898 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
901 struct CadetTunnelSkippedKey *key;
902 struct GNUNET_ShortHashCode *hmac;
903 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
904 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
905 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
911 LOG (GNUNET_ERROR_TYPE_DEBUG,
912 "Trying skipped keys\n");
913 hmac = &plaintext_header.hmac;
914 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
916 /* Find a correct Header Key */
918 for (key = t->ax.skipped_head; NULL != key; key = key->next)
921 AX_HEADER_SIZE + esize,
925 if (0 == memcmp (hmac,
936 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
937 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
938 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
939 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
942 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
946 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
950 &plaintext_header.Ns);
951 GNUNET_assert (AX_HEADER_SIZE == res);
953 /* Find the correct message key */
954 N = ntohl (plaintext_header.Ns);
955 while ( (NULL != key) &&
958 if ( (NULL == key) ||
959 (0 != memcmp (&key->HK,
961 sizeof (*valid_HK))) )
964 /* Decrypt payload */
965 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
970 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
975 delete_skipped_key (t,
982 * Delete a key from the list of skipped keys.
984 * @param t Tunnel to delete from.
985 * @param HKr Header Key to use.
988 store_skipped_key (struct CadetTunnel *t,
989 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
991 struct CadetTunnelSkippedKey *key;
993 key = GNUNET_new (struct CadetTunnelSkippedKey);
994 key->timestamp = GNUNET_TIME_absolute_get ();
997 t_hmac_derive_key (&t->ax.CKr,
1001 t_hmac_derive_key (&t->ax.CKr,
1005 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1014 * Stage skipped AX keys and calculate the message key.
1015 * Stores each HK and MK for skipped messages.
1017 * @param t Tunnel where to stage the keys.
1018 * @param HKr Header key.
1019 * @param Np Received meesage number.
1020 * @return #GNUNET_OK if keys were stored.
1021 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1024 store_ax_keys (struct CadetTunnel *t,
1025 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1030 gap = Np - t->ax.Nr;
1031 LOG (GNUNET_ERROR_TYPE_DEBUG,
1032 "Storing skipped keys [%u, %u)\n",
1035 if (MAX_KEY_GAP < gap)
1037 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1038 /* TODO: start new key exchange on return */
1039 GNUNET_break_op (0);
1040 LOG (GNUNET_ERROR_TYPE_WARNING,
1041 "Got message %u, expected %u+\n",
1044 return GNUNET_SYSERR;
1048 /* Delayed message: don't store keys, flag to try old keys. */
1049 return GNUNET_SYSERR;
1052 while (t->ax.Nr < Np)
1053 store_skipped_key (t,
1056 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1057 delete_skipped_key (t,
1058 t->ax.skipped_tail);
1064 * Decrypt and verify data with the appropriate tunnel key and verify that the
1065 * data has not been altered since it was sent by the remote peer.
1067 * @param t Tunnel whose key to use.
1068 * @param dst Destination for the plaintext.
1069 * @param src Source of the message. Can overlap with @c dst.
1070 * @param size Size of the message.
1071 * @return Size of the decrypted data, -1 if an error was encountered.
1074 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1076 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1079 struct CadetTunnelAxolotl *ax;
1080 struct GNUNET_ShortHashCode msg_hmac;
1081 struct GNUNET_HashCode hmac;
1082 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1085 size_t esize; /* Size of encryped payload */
1087 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1090 /* Try current HK */
1092 AX_HEADER_SIZE + esize,
1095 if (0 != memcmp (&msg_hmac,
1099 static const char ctx[] = "axolotl ratchet";
1100 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1101 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1102 struct GNUNET_HashCode dh;
1103 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1107 AX_HEADER_SIZE + esize,
1111 if (0 != memcmp (&msg_hmac,
1115 /* Try the skipped keys, if that fails, we're out of luck. */
1116 return try_old_ax_keys (t,
1126 Np = ntohl (plaintext_header.Ns);
1127 PNp = ntohl (plaintext_header.PNs);
1128 DHRp = &plaintext_header.DHRs;
1133 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1134 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1137 t_ax_hmac_hash (&ax->RK,
1140 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1142 &hmac, sizeof (hmac),
1145 /* Commit "purported" keys */
1151 ax->ratchet_allowed = GNUNET_YES;
1158 Np = ntohl (plaintext_header.Ns);
1159 PNp = ntohl (plaintext_header.PNs);
1161 if ( (Np != ax->Nr) &&
1162 (GNUNET_OK != store_ax_keys (t,
1166 /* Try the skipped keys, if that fails, we're out of luck. */
1167 return try_old_ax_keys (t,
1183 * Our tunnel became ready for the first time, notify channels
1184 * that have been waiting.
1186 * @param cls our tunnel, not used
1187 * @param key unique ID of the channel, not used
1188 * @param value the `struct CadetChannel` to notify
1189 * @return #GNUNET_OK (continue to iterate)
1192 notify_tunnel_up_cb (void *cls,
1196 struct CadetChannel *ch = value;
1198 GCCH_tunnel_up (ch);
1204 * Change the tunnel encryption state.
1205 * If the encryption state changes to OK, stop the rekey task.
1207 * @param t Tunnel whose encryption state to change, or NULL.
1208 * @param state New encryption state.
1211 GCT_change_estate (struct CadetTunnel *t,
1212 enum CadetTunnelEState state)
1214 enum CadetTunnelEState old = t->estate;
1217 LOG (GNUNET_ERROR_TYPE_DEBUG,
1218 "Tunnel %s estate changed from %d to %d\n",
1223 if ( (CADET_TUNNEL_KEY_OK != old) &&
1224 (CADET_TUNNEL_KEY_OK == t->estate) )
1226 if (NULL != t->kx_task)
1228 GNUNET_SCHEDULER_cancel (t->kx_task);
1231 if (CADET_TUNNEL_KEY_REKEY != old)
1233 /* notify all channels that have been waiting */
1234 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1235 ¬ify_tunnel_up_cb,
1239 /* FIXME: schedule rekey task! */
1245 * Send a KX message.
1247 * FIXME: does not take care of sender-authentication yet!
1249 * @param t Tunnel on which to send it.
1250 * @param force_reply Force the other peer to reply with a KX message.
1253 send_kx (struct CadetTunnel *t,
1256 struct CadetTunnelAxolotl *ax = &t->ax;
1257 struct CadetTConnection *ct;
1258 struct CadetConnection *cc;
1259 struct GNUNET_MQ_Envelope *env;
1260 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1261 enum GNUNET_CADET_KX_Flags flags;
1263 ct = get_ready_connection (t);
1266 LOG (GNUNET_ERROR_TYPE_DEBUG,
1267 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1272 LOG (GNUNET_ERROR_TYPE_DEBUG,
1273 "Sending KX on tunnel %s using connection %s\n",
1277 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1278 env = GNUNET_MQ_msg (msg,
1279 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1280 flags = GNUNET_CADET_KX_FLAG_NONE;
1281 if (GNUNET_YES == force_reply)
1282 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1283 msg->flags = htonl (flags);
1284 msg->cid = *GCC_get_id (cc);
1285 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1286 &msg->ephemeral_key);
1287 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1289 ct->is_ready = GNUNET_NO;
1292 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1293 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1294 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1295 GCT_change_estate (t,
1296 CADET_TUNNEL_KEY_SENT);
1301 * Handle KX message.
1303 * FIXME: sender-authentication in KX is missing!
1305 * @param ct connection/tunnel combo that received encrypted message
1306 * @param msg the key exchange message
1309 GCT_handle_kx (struct CadetTConnection *ct,
1310 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1312 struct CadetTunnel *t = ct->t;
1313 struct CadetTunnelAxolotl *ax = &t->ax;
1314 struct GNUNET_HashCode key_material[3];
1315 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1316 const char salt[] = "CADET Axolotl salt";
1317 const struct GNUNET_PeerIdentity *pid;
1320 pid = GCP_get_id (t->destination);
1321 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1323 am_I_alice = GNUNET_YES;
1324 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1326 am_I_alice = GNUNET_NO;
1329 GNUNET_break_op (0);
1333 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1335 if (NULL != t->kx_task)
1337 GNUNET_SCHEDULER_cancel (t->kx_task);
1344 if (0 == memcmp (&ax->DHRr,
1346 sizeof (msg->ratchet_key)))
1348 LOG (GNUNET_ERROR_TYPE_DEBUG,
1349 " known ratchet key, exit\n");
1353 ax->DHRr = msg->ratchet_key;
1356 if (GNUNET_YES == am_I_alice)
1358 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1359 &msg->ephemeral_key, /* B0 */
1364 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1365 &pid->public_key, /* A */
1370 if (GNUNET_YES == am_I_alice)
1372 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1373 &pid->public_key, /* B */
1378 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1379 &msg->ephemeral_key, /* B0 */
1386 /* (This is the triple-DH, we could probably safely skip this,
1387 as A0/B0 are already in the key material.) */
1388 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1389 &msg->ephemeral_key, /* B0 or A0 */
1393 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1394 salt, sizeof (salt),
1395 &key_material, sizeof (key_material),
1398 if (0 == memcmp (&ax->RK,
1402 LOG (GNUNET_ERROR_TYPE_INFO,
1403 " known handshake key, exit\n");
1406 LOG (GNUNET_ERROR_TYPE_DEBUG,
1407 "Handling KX message for tunnel %s\n",
1411 if (GNUNET_YES == am_I_alice)
1417 ax->ratchet_flag = GNUNET_YES;
1425 ax->ratchet_flag = GNUNET_NO;
1426 ax->ratchet_allowed = GNUNET_NO;
1427 ax->ratchet_counter = 0;
1428 ax->ratchet_expiration
1429 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1438 case CADET_TUNNEL_KEY_UNINITIALIZED:
1439 GCT_change_estate (t,
1440 CADET_TUNNEL_KEY_PING);
1442 case CADET_TUNNEL_KEY_SENT:
1443 /* Got a response to us sending our key; now
1444 we can start transmitting! */
1445 GCT_change_estate (t,
1446 CADET_TUNNEL_KEY_OK);
1447 if (NULL != t->send_task)
1448 GNUNET_SCHEDULER_cancel (t->send_task);
1449 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1452 case CADET_TUNNEL_KEY_PING:
1453 /* Got a key yet again; need encrypted payload to advance */
1455 case CADET_TUNNEL_KEY_OK:
1456 /* Did not expect a key, but so what. */
1458 case CADET_TUNNEL_KEY_REKEY:
1459 /* Got a key yet again; need encrypted payload to advance */
1465 /* ************************************** end core crypto ***************************** */
1469 * Compute the next free channel tunnel number for this tunnel.
1471 * @param t the tunnel
1472 * @return unused number that can uniquely identify a channel in the tunnel
1474 static struct GNUNET_CADET_ChannelTunnelNumber
1475 get_next_free_ctn (struct CadetTunnel *t)
1477 #define HIGH_BIT 0x8000000
1478 struct GNUNET_CADET_ChannelTunnelNumber ret;
1483 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1484 GCP_get_id (GCT_get_destination (t)));
1490 GNUNET_assert (0); // loopback must never go here!
1491 ctn = ntohl (t->next_ctn.cn);
1493 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1496 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1498 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1499 ret.cn = ntohl (ctn);
1505 * Add a channel to a tunnel, and notify channel that we are ready
1506 * for transmission if we are already up. Otherwise that notification
1507 * will be done later in #notify_tunnel_up_cb().
1511 * @return unique number identifying @a ch within @a t
1513 struct GNUNET_CADET_ChannelTunnelNumber
1514 GCT_add_channel (struct CadetTunnel *t,
1515 struct CadetChannel *ch)
1517 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1519 ctn = get_next_free_ctn (t);
1520 GNUNET_assert (GNUNET_YES ==
1521 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1524 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1525 LOG (GNUNET_ERROR_TYPE_DEBUG,
1526 "Adding channel %s to tunnel %s\n",
1529 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1530 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1531 GCCH_tunnel_up (ch);
1537 * This tunnel is no longer used, destroy it.
1539 * @param cls the idle tunnel
1542 destroy_tunnel (void *cls)
1544 struct CadetTunnel *t = cls;
1545 struct CadetTConnection *ct;
1546 struct CadetTunnelQueueEntry *tq;
1548 t->destroy_task = NULL;
1549 LOG (GNUNET_ERROR_TYPE_DEBUG,
1550 "Destroying idle tunnel %s\n",
1552 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1553 while (NULL != (ct = t->connection_head))
1555 GNUNET_assert (ct->t == t);
1556 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1559 GCC_destroy (ct->cc);
1562 while (NULL != (tq = t->tq_head))
1564 if (NULL != tq->cont)
1565 tq->cont (tq->cont_cls);
1566 GCT_send_cancel (tq);
1568 GCP_drop_tunnel (t->destination,
1570 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1571 if (NULL != t->maintain_connections_task)
1573 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1574 t->maintain_connections_task = NULL;
1576 if (NULL != t->send_task)
1578 GNUNET_SCHEDULER_cancel (t->send_task);
1579 t->send_task = NULL;
1581 if (NULL != t->kx_task)
1583 GNUNET_SCHEDULER_cancel (t->kx_task);
1586 GNUNET_MST_destroy (t->mst);
1587 GNUNET_MQ_destroy (t->mq);
1588 while (NULL != t->ax.skipped_head)
1589 delete_skipped_key (t,
1590 t->ax.skipped_head);
1591 GNUNET_assert (0 == t->ax.skipped);
1592 GNUNET_free_non_null (t->ax.kx_0);
1593 GNUNET_free_non_null (t->ax.DHRs);
1599 * Remove a channel from a tunnel.
1603 * @param ctn unique number identifying @a ch within @a t
1606 GCT_remove_channel (struct CadetTunnel *t,
1607 struct CadetChannel *ch,
1608 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1610 LOG (GNUNET_ERROR_TYPE_DEBUG,
1611 "Removing channel %s from tunnel %s\n",
1614 GNUNET_assert (GNUNET_YES ==
1615 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1619 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1621 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1629 * Destroy remaining channels during shutdown.
1631 * @param cls the `struct CadetTunnel` of the channel
1632 * @param key key of the channel
1633 * @param value the `struct CadetChannel`
1634 * @return #GNUNET_OK (continue to iterate)
1637 destroy_remaining_channels (void *cls,
1641 struct CadetChannel *ch = value;
1643 GCCH_handle_remote_destroy (ch);
1649 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1651 * @param t tunnel to destroy
1654 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1656 GNUNET_assert (GNUNET_YES == shutting_down);
1657 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1658 &destroy_remaining_channels,
1661 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1662 if (NULL != t->destroy_task)
1664 GNUNET_SCHEDULER_cancel (t->destroy_task);
1665 t->destroy_task = NULL;
1672 * It's been a while, we should try to redo the KX, if we can.
1674 * @param cls the `struct CadetTunnel` to do KX for.
1677 retry_kx (void *cls)
1679 struct CadetTunnel *t = cls;
1683 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1684 (CADET_TUNNEL_KEY_SENT == t->estate) )
1691 * Send normal payload from queue in @a t via connection @a ct.
1692 * Does nothing if our payload queue is empty.
1694 * @param t tunnel to send data from
1695 * @param ct connection to use for transmission (is ready)
1698 try_send_normal_payload (struct CadetTunnel *t,
1699 struct CadetTConnection *ct)
1701 struct CadetTunnelQueueEntry *tq;
1703 GNUNET_assert (GNUNET_YES == ct->is_ready);
1707 /* no messages pending right now */
1708 LOG (GNUNET_ERROR_TYPE_DEBUG,
1709 "Not sending payload of %s on ready %s (nothing pending)\n",
1714 /* ready to send message 'tq' on tunnel 'ct' */
1715 GNUNET_assert (t == tq->t);
1716 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1719 if (NULL != tq->cid)
1720 *tq->cid = *GCC_get_id (ct->cc);
1721 ct->is_ready = GNUNET_NO;
1722 LOG (GNUNET_ERROR_TYPE_DEBUG,
1723 "Sending payload of %s on %s\n",
1726 GCC_transmit (ct->cc,
1728 if (NULL != tq->cont)
1729 tq->cont (tq->cont_cls);
1735 * A connection is @a is_ready for transmission. Looks at our message
1736 * queue and if there is a message, sends it out via the connection.
1738 * @param cls the `struct CadetTConnection` that is @a is_ready
1739 * @param is_ready #GNUNET_YES if connection are now ready,
1740 * #GNUNET_NO if connection are no longer ready
1743 connection_ready_cb (void *cls,
1746 struct CadetTConnection *ct = cls;
1747 struct CadetTunnel *t = ct->t;
1749 if (GNUNET_NO == is_ready)
1751 LOG (GNUNET_ERROR_TYPE_DEBUG,
1752 "Connection %s no longer ready for tunnel %s\n",
1755 ct->is_ready = GNUNET_NO;
1758 ct->is_ready = GNUNET_YES;
1759 LOG (GNUNET_ERROR_TYPE_DEBUG,
1760 "Connection %s now ready for tunnel %s in state %s\n",
1763 estate2s (t->estate));
1766 case CADET_TUNNEL_KEY_UNINITIALIZED:
1770 case CADET_TUNNEL_KEY_SENT:
1771 case CADET_TUNNEL_KEY_PING:
1772 /* opportunity to #retry_kx() starts now, schedule job */
1773 if (NULL == t->kx_task)
1776 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1781 case CADET_TUNNEL_KEY_OK:
1782 try_send_normal_payload (t,
1785 case CADET_TUNNEL_KEY_REKEY:
1788 t->estate = CADET_TUNNEL_KEY_OK;
1795 * Called when either we have a new connection, or a new message in the
1796 * queue, or some existing connection has transmission capacity. Looks
1797 * at our message queue and if there is a message, picks a connection
1800 * @param cls the `struct CadetTunnel` to process messages on
1803 trigger_transmissions (void *cls)
1805 struct CadetTunnel *t = cls;
1806 struct CadetTConnection *ct;
1808 t->send_task = NULL;
1809 if (NULL == t->tq_head)
1810 return; /* no messages pending right now */
1811 ct = get_ready_connection (t);
1813 return; /* no connections ready */
1814 try_send_normal_payload (t,
1820 * Consider using the path @a p for the tunnel @a t.
1821 * The tunnel destination is at offset @a off in path @a p.
1823 * @param cls our tunnel
1824 * @param path a path to our destination
1825 * @param off offset of the destination on path @a path
1826 * @return #GNUNET_YES (should keep iterating)
1829 consider_path_cb (void *cls,
1830 struct CadetPeerPath *path,
1833 struct CadetTunnel *t = cls;
1834 unsigned int min_length = UINT_MAX;
1835 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1836 struct CadetTConnection *ct;
1838 /* Check if we care about the new path. */
1839 for (ct = t->connection_head;
1843 struct CadetPeerPath *ps;
1845 ps = GCC_get_path (ct->cc);
1848 LOG (GNUNET_ERROR_TYPE_DEBUG,
1849 "Ignoring duplicate path %s for tunnel %s.\n",
1852 return GNUNET_YES; /* duplicate */
1854 min_length = GNUNET_MIN (min_length,
1855 GCPP_get_length (ps));
1856 max_desire = GNUNET_MAX (max_desire,
1857 GCPP_get_desirability (ps));
1860 /* FIXME: not sure we should really just count
1861 'num_connections' here, as they may all have
1862 consistently failed to connect. */
1864 /* We iterate by increasing path length; if we have enough paths and
1865 this one is more than twice as long than what we are currently
1866 using, then ignore all of these super-long ones! */
1867 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1868 (min_length * 2 < off) )
1870 LOG (GNUNET_ERROR_TYPE_DEBUG,
1871 "Ignoring paths of length %u, they are way too long.\n",
1875 /* If we have enough paths and this one looks no better, ignore it. */
1876 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1877 (min_length < GCPP_get_length (path)) &&
1878 (max_desire > GCPP_get_desirability (path)) )
1880 LOG (GNUNET_ERROR_TYPE_DEBUG,
1881 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1882 GCPP_get_length (path),
1883 (unsigned long long) GCPP_get_desirability (path),
1884 GCP_2s (t->destination));
1888 /* Path is interesting (better by some metric, or we don't have
1889 enough paths yet). */
1890 ct = GNUNET_new (struct CadetTConnection);
1891 ct->created = GNUNET_TIME_absolute_get ();
1893 ct->cc = GCC_create (t->destination,
1896 &connection_ready_cb,
1898 /* FIXME: schedule job to kill connection (and path?) if it takes
1899 too long to get ready! (And track performance data on how long
1900 other connections took with the tunnel!)
1901 => Note: to be done within 'connection'-logic! */
1902 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1905 t->num_connections++;
1906 LOG (GNUNET_ERROR_TYPE_DEBUG,
1907 "Found interesting path %s for tunnel %s, created connection %s\n",
1916 * Function called to maintain the connections underlying our tunnel.
1917 * Tries to maintain (incl. tear down) connections for the tunnel, and
1918 * if there is a significant change, may trigger transmissions.
1920 * Basically, needs to check if there are connections that perform
1921 * badly, and if so eventually kill them and trigger a replacement.
1922 * The strategy is to open one more connection than
1923 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1924 * least-performing one, and then inquire for new ones.
1926 * @param cls the `struct CadetTunnel`
1929 maintain_connections_cb (void *cls)
1931 struct CadetTunnel *t = cls;
1933 t->maintain_connections_task = NULL;
1934 LOG (GNUNET_ERROR_TYPE_DEBUG,
1935 "Performing connection maintenance for tunnel %s.\n",
1938 (void) GCP_iterate_paths (t->destination,
1942 GNUNET_break (0); // FIXME: implement!
1947 * Consider using the path @a p for the tunnel @a t.
1948 * The tunnel destination is at offset @a off in path @a p.
1950 * @param cls our tunnel
1951 * @param path a path to our destination
1952 * @param off offset of the destination on path @a path
1955 GCT_consider_path (struct CadetTunnel *t,
1956 struct CadetPeerPath *p,
1959 (void) consider_path_cb (t,
1968 * @param cls the `struct CadetTunnel` for which we decrypted the message
1969 * @param msg the message we received on the tunnel
1972 handle_plaintext_keepalive (void *cls,
1973 const struct GNUNET_MessageHeader *msg)
1975 struct CadetTunnel *t = cls;
1977 GNUNET_break (0); // FIXME
1982 * Check that @a msg is well-formed.
1984 * @param cls the `struct CadetTunnel` for which we decrypted the message
1985 * @param msg the message we received on the tunnel
1986 * @return #GNUNET_OK (any variable-size payload goes)
1989 check_plaintext_data (void *cls,
1990 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1997 * We received payload data for a channel. Locate the channel
1998 * and process the data, or return an error if the channel is unknown.
2000 * @param cls the `struct CadetTunnel` for which we decrypted the message
2001 * @param msg the message we received on the tunnel
2004 handle_plaintext_data (void *cls,
2005 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2007 struct CadetTunnel *t = cls;
2008 struct CadetChannel *ch;
2010 ch = lookup_channel (t,
2014 /* We don't know about such a channel, might have been destroyed on our
2015 end in the meantime, or never existed. Send back a DESTROY. */
2016 LOG (GNUNET_ERROR_TYPE_DEBUG,
2017 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2018 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2019 ntohl (msg->ctn.cn));
2020 GCT_send_channel_destroy (t,
2024 GCCH_handle_channel_plaintext_data (ch,
2030 * We received an acknowledgement for data we sent on a channel.
2031 * Locate the channel and process it, or return an error if the
2032 * channel is unknown.
2034 * @param cls the `struct CadetTunnel` for which we decrypted the message
2035 * @param ack the message we received on the tunnel
2038 handle_plaintext_data_ack (void *cls,
2039 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2041 struct CadetTunnel *t = cls;
2042 struct CadetChannel *ch;
2044 ch = lookup_channel (t,
2048 /* We don't know about such a channel, might have been destroyed on our
2049 end in the meantime, or never existed. Send back a DESTROY. */
2050 LOG (GNUNET_ERROR_TYPE_DEBUG,
2051 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2052 ntohl (ack->ctn.cn));
2053 GCT_send_channel_destroy (t,
2057 GCCH_handle_channel_plaintext_data_ack (ch,
2063 * We have received a request to open a channel to a port from
2064 * another peer. Creates the incoming channel.
2066 * @param cls the `struct CadetTunnel` for which we decrypted the message
2067 * @param copen the message we received on the tunnel
2070 handle_plaintext_channel_open (void *cls,
2071 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2073 struct CadetTunnel *t = cls;
2074 struct CadetChannel *ch;
2076 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2077 ntohl (copen->ctn.cn));
2080 LOG (GNUNET_ERROR_TYPE_DEBUG,
2081 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2082 GNUNET_h2s (&copen->port),
2085 GCCH_handle_duplicate_open (ch);
2088 LOG (GNUNET_ERROR_TYPE_DEBUG,
2089 "Receicved channel OPEN on port %s from %s\n",
2090 GNUNET_h2s (&copen->port),
2092 ch = GCCH_channel_incoming_new (t,
2095 ntohl (copen->opt));
2096 GNUNET_assert (GNUNET_OK ==
2097 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2098 ntohl (copen->ctn.cn),
2100 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2105 * Send a DESTROY message via the tunnel.
2107 * @param t the tunnel to transmit over
2108 * @param ctn ID of the channel to destroy
2111 GCT_send_channel_destroy (struct CadetTunnel *t,
2112 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2114 struct GNUNET_CADET_ChannelManageMessage msg;
2116 LOG (GNUNET_ERROR_TYPE_DEBUG,
2117 "Sending DESTORY message for channel ID %u\n",
2119 msg.header.size = htons (sizeof (msg));
2120 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2121 msg.reserved = htonl (0);
2131 * We have received confirmation from the target peer that the
2132 * given channel could be established (the port is open).
2135 * @param cls the `struct CadetTunnel` for which we decrypted the message
2136 * @param cm the message we received on the tunnel
2139 handle_plaintext_channel_open_ack (void *cls,
2140 const struct GNUNET_CADET_ChannelManageMessage *cm)
2142 struct CadetTunnel *t = cls;
2143 struct CadetChannel *ch;
2145 ch = lookup_channel (t,
2149 /* We don't know about such a channel, might have been destroyed on our
2150 end in the meantime, or never existed. Send back a DESTROY. */
2151 LOG (GNUNET_ERROR_TYPE_DEBUG,
2152 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2153 ntohl (cm->ctn.cn));
2154 GCT_send_channel_destroy (t,
2158 LOG (GNUNET_ERROR_TYPE_DEBUG,
2159 "Received channel OPEN_ACK on channel %s from %s\n",
2162 GCCH_handle_channel_open_ack (ch);
2167 * We received a message saying that a channel should be destroyed.
2168 * Pass it on to the correct channel.
2170 * @param cls the `struct CadetTunnel` for which we decrypted the message
2171 * @param cm the message we received on the tunnel
2174 handle_plaintext_channel_destroy (void *cls,
2175 const struct GNUNET_CADET_ChannelManageMessage *cm)
2177 struct CadetTunnel *t = cls;
2178 struct CadetChannel *ch;
2180 ch = lookup_channel (t,
2184 /* We don't know about such a channel, might have been destroyed on our
2185 end in the meantime, or never existed. */
2186 LOG (GNUNET_ERROR_TYPE_DEBUG,
2187 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2188 ntohl (cm->ctn.cn));
2191 LOG (GNUNET_ERROR_TYPE_DEBUG,
2192 "Receicved channel DESTROY on %s from %s\n",
2195 GCCH_handle_remote_destroy (ch);
2200 * Handles a message we decrypted, by injecting it into
2201 * our message queue (which will do the dispatching).
2203 * @param cls the `struct CadetTunnel` that got the message
2204 * @param msg the message
2205 * @return #GNUNET_OK (continue to process)
2208 handle_decrypted (void *cls,
2209 const struct GNUNET_MessageHeader *msg)
2211 struct CadetTunnel *t = cls;
2213 GNUNET_MQ_inject_message (t->mq,
2220 * Function called if we had an error processing
2221 * an incoming decrypted message.
2223 * @param cls the `struct CadetTunnel`
2224 * @param error error code
2227 decrypted_error_cb (void *cls,
2228 enum GNUNET_MQ_Error error)
2230 GNUNET_break_op (0);
2235 * Create a tunnel to @a destionation. Must only be called
2236 * from within #GCP_get_tunnel().
2238 * @param destination where to create the tunnel to
2239 * @return new tunnel to @a destination
2241 struct CadetTunnel *
2242 GCT_create_tunnel (struct CadetPeer *destination)
2244 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2245 struct GNUNET_MQ_MessageHandler handlers[] = {
2246 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2247 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2248 struct GNUNET_MessageHeader,
2250 GNUNET_MQ_hd_var_size (plaintext_data,
2251 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2252 struct GNUNET_CADET_ChannelAppDataMessage,
2254 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2255 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2256 struct GNUNET_CADET_ChannelDataAckMessage,
2258 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2259 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2260 struct GNUNET_CADET_ChannelOpenMessage,
2262 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2263 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2264 struct GNUNET_CADET_ChannelManageMessage,
2266 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2267 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2268 struct GNUNET_CADET_ChannelManageMessage,
2270 GNUNET_MQ_handler_end ()
2274 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2275 t->destination = destination;
2276 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2277 t->maintain_connections_task
2278 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2280 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2285 &decrypted_error_cb,
2287 t->mst = GNUNET_MST_create (&handle_decrypted,
2294 * Add a @a connection to the @a tunnel.
2297 * @param cid connection identifer to use for the connection
2298 * @param path path to use for the connection
2301 GCT_add_inbound_connection (struct CadetTunnel *t,
2302 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2303 struct CadetPeerPath *path)
2305 struct CadetTConnection *ct;
2307 ct = GNUNET_new (struct CadetTConnection);
2308 ct->created = GNUNET_TIME_absolute_get ();
2310 ct->cc = GCC_create_inbound (t->destination,
2314 &connection_ready_cb,
2316 /* FIXME: schedule job to kill connection (and path?) if it takes
2317 too long to get ready! (And track performance data on how long
2318 other connections took with the tunnel!)
2319 => Note: to be done within 'connection'-logic! */
2320 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2323 t->num_connections++;
2324 LOG (GNUNET_ERROR_TYPE_DEBUG,
2325 "Tunnel %s has new connection %s\n",
2332 * Handle encrypted message.
2334 * @param ct connection/tunnel combo that received encrypted message
2335 * @param msg the encrypted message to decrypt
2338 GCT_handle_encrypted (struct CadetTConnection *ct,
2339 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2341 struct CadetTunnel *t = ct->t;
2342 uint16_t size = ntohs (msg->header.size);
2343 char cbuf [size] GNUNET_ALIGN;
2344 ssize_t decrypted_size;
2346 LOG (GNUNET_ERROR_TYPE_DEBUG,
2347 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2349 (unsigned int) size,
2354 case CADET_TUNNEL_KEY_UNINITIALIZED:
2355 /* We did not even SEND our KX, how can the other peer
2356 send us encrypted data? */
2357 GNUNET_break_op (0);
2359 case CADET_TUNNEL_KEY_SENT:
2360 /* We did not get the KX of the other peer, but that
2361 might have been lost. Ask for KX again. */
2362 GNUNET_STATISTICS_update (stats,
2363 "# received encrypted without KX",
2366 if (NULL != t->kx_task)
2367 GNUNET_SCHEDULER_cancel (t->kx_task);
2368 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2371 case CADET_TUNNEL_KEY_PING:
2372 /* Great, first payload, we might graduate to OK */
2373 case CADET_TUNNEL_KEY_OK:
2374 case CADET_TUNNEL_KEY_REKEY:
2378 GNUNET_STATISTICS_update (stats,
2379 "# received encrypted",
2382 decrypted_size = t_ax_decrypt_and_validate (t,
2387 if (-1 == decrypted_size)
2389 GNUNET_break_op (0);
2390 LOG (GNUNET_ERROR_TYPE_WARNING,
2391 "Tunnel %s failed to decrypt and validate encrypted data\n",
2393 GNUNET_STATISTICS_update (stats,
2394 "# unable to decrypt",
2399 if (CADET_TUNNEL_KEY_PING == t->estate)
2401 GCT_change_estate (t,
2402 CADET_TUNNEL_KEY_OK);
2403 if (NULL != t->send_task)
2404 GNUNET_SCHEDULER_cancel (t->send_task);
2405 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2408 /* The MST will ultimately call #handle_decrypted() on each message. */
2409 GNUNET_break_op (GNUNET_OK ==
2410 GNUNET_MST_from_buffer (t->mst,
2419 * Sends an already built message on a tunnel, encrypting it and
2420 * choosing the best connection if not provided.
2422 * @param message Message to send. Function modifies it.
2423 * @param t Tunnel on which this message is transmitted.
2424 * @param cont Continuation to call once message is really sent.
2425 * @param cont_cls Closure for @c cont.
2426 * @return Handle to cancel message. NULL if @c cont is NULL.
2428 struct CadetTunnelQueueEntry *
2429 GCT_send (struct CadetTunnel *t,
2430 const struct GNUNET_MessageHeader *message,
2431 GNUNET_SCHEDULER_TaskCallback cont,
2434 struct CadetTunnelQueueEntry *tq;
2435 uint16_t payload_size;
2436 struct GNUNET_MQ_Envelope *env;
2437 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2439 payload_size = ntohs (message->size);
2440 LOG (GNUNET_ERROR_TYPE_DEBUG,
2441 "Encrypting %u bytes for tunnel %s\n",
2442 (unsigned int) payload_size,
2444 env = GNUNET_MQ_msg_extra (ax_msg,
2446 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2451 ax_msg->Ns = htonl (t->ax.Ns++);
2452 ax_msg->PNs = htonl (t->ax.PNs);
2453 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2457 t_hmac (&ax_msg->Ns,
2458 AX_HEADER_SIZE + payload_size,
2463 tq = GNUNET_malloc (sizeof (*tq));
2466 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2468 tq->cont_cls = cont_cls;
2469 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2472 if (NULL != t->send_task)
2473 GNUNET_SCHEDULER_cancel (t->send_task);
2475 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2482 * Cancel a previously sent message while it's in the queue.
2484 * ONLY can be called before the continuation given to the send
2485 * function is called. Once the continuation is called, the message is
2486 * no longer in the queue!
2488 * @param tq Handle to the queue entry to cancel.
2491 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2493 struct CadetTunnel *t = tq->t;
2495 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2498 GNUNET_MQ_discard (tq->env);
2504 * Iterate over all connections of a tunnel.
2506 * @param t Tunnel whose connections to iterate.
2507 * @param iter Iterator.
2508 * @param iter_cls Closure for @c iter.
2511 GCT_iterate_connections (struct CadetTunnel *t,
2512 GCT_ConnectionIterator iter,
2515 for (struct CadetTConnection *ct = t->connection_head;
2524 * Closure for #iterate_channels_cb.
2531 GCT_ChannelIterator iter;
2534 * Closure for @e iter.
2541 * Helper function for #GCT_iterate_channels.
2543 * @param cls the `struct ChanIterCls`
2545 * @param value a `struct CadetChannel`
2546 * @return #GNUNET_OK
2549 iterate_channels_cb (void *cls,
2553 struct ChanIterCls *ctx = cls;
2554 struct CadetChannel *ch = value;
2556 ctx->iter (ctx->iter_cls,
2563 * Iterate over all channels of a tunnel.
2565 * @param t Tunnel whose channels to iterate.
2566 * @param iter Iterator.
2567 * @param iter_cls Closure for @c iter.
2570 GCT_iterate_channels (struct CadetTunnel *t,
2571 GCT_ChannelIterator iter,
2574 struct ChanIterCls ctx;
2577 ctx.iter_cls = iter_cls;
2578 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2579 &iterate_channels_cb,
2586 * Call #GCCH_debug() on a channel.
2588 * @param cls points to the log level to use
2590 * @param value the `struct CadetChannel` to dump
2591 * @return #GNUNET_OK (continue iteration)
2594 debug_channel (void *cls,
2598 const enum GNUNET_ErrorType *level = cls;
2599 struct CadetChannel *ch = value;
2601 GCCH_debug (ch, *level);
2606 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2610 * Log all possible info about the tunnel state.
2612 * @param t Tunnel to debug.
2613 * @param level Debug level to use.
2616 GCT_debug (const struct CadetTunnel *t,
2617 enum GNUNET_ErrorType level)
2619 struct CadetTConnection *iter_c;
2622 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2624 __FILE__, __FUNCTION__, __LINE__);
2629 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2631 estate2s (t->estate),
2633 t->num_connections);
2634 #if DUMP_KEYS_TO_STDERR
2635 ax_debug (t->ax, level);
2639 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2643 "TTT connections:\n");
2644 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2645 GCC_debug (iter_c->cc,
2649 "TTT TUNNEL END\n");
2653 /* end of gnunet-service-cadet-new_tunnels.c */