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 * - check KX estate machine -- make sure it is never stuck!
28 * - clean up KX logic, including adding sender authentication
29 * - implement connection management (evaluate, kill old ones,
30 * search for new ones)
31 * - when managing connections, distinguish those that
32 * have (recently) had traffic from those that were
33 * never ready (or not recently)
36 #include "gnunet_util_lib.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "cadet_protocol.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
52 * How long do we wait until tearing down an idle tunnel?
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
57 * Yuck, replace by 'offsetof' expression?
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
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 * Task scheduled if there are no more channels using the tunnel.
304 struct GNUNET_SCHEDULER_Task *destroy_task;
307 * Task to trim connections if too many are present.
309 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
312 * Task to send messages from queue (if possible).
314 struct GNUNET_SCHEDULER_Task *send_task;
317 * Task to trigger KX.
319 struct GNUNET_SCHEDULER_Task *kx_task;
322 * Tokenizer for decrypted messages.
324 struct GNUNET_MessageStreamTokenizer *mst;
327 * Dispatcher for decrypted messages only (do NOT use for sending!).
329 struct GNUNET_MQ_Handle *mq;
332 * DLL of connections that are actively used to reach the destination peer.
334 struct CadetTConnection *connection_head;
337 * DLL of connections that are actively used to reach the destination peer.
339 struct CadetTConnection *connection_tail;
342 * Channels inside this tunnel. Maps
343 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
345 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
348 * Channel ID for the next created channel in this tunnel.
350 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
353 * Queued messages, to transmit once tunnel gets connected.
355 struct CadetTunnelQueueEntry *tq_head;
358 * Queued messages, to transmit once tunnel gets connected.
360 struct CadetTunnelQueueEntry *tq_tail;
364 * Ephemeral message in the queue (to avoid queueing more than one).
366 struct CadetConnectionQueue *ephm_hKILL;
369 * Pong message in the queue.
371 struct CadetConnectionQueue *pong_hKILL;
374 * How long do we wait until we retry the KX?
376 struct GNUNET_TIME_Relative kx_retry_delay;
379 * When do we try the next KX?
381 struct GNUNET_TIME_Absolute next_kx_attempt;
384 * Number of connections in the @e connection_head DLL.
386 unsigned int num_connections;
389 * Number of entries in the @e tq_head DLL.
394 * State of the tunnel encryption.
396 enum CadetTunnelEState estate;
402 * Get the static string for the peer this tunnel is directed.
406 * @return Static string the destination peer's ID.
409 GCT_2s (const struct CadetTunnel *t)
414 return "Tunnel(NULL)";
415 GNUNET_snprintf (buf,
418 GNUNET_i2s (GCP_get_id (t->destination)));
424 * Get string description for tunnel encryption state.
426 * @param es Tunnel state.
428 * @return String representation.
431 estate2s (enum CadetTunnelEState es)
437 case CADET_TUNNEL_KEY_UNINITIALIZED:
438 return "CADET_TUNNEL_KEY_UNINITIALIZED";
439 case CADET_TUNNEL_KEY_SENT:
440 return "CADET_TUNNEL_KEY_SENT";
441 case CADET_TUNNEL_KEY_PING:
442 return "CADET_TUNNEL_KEY_PING";
443 case CADET_TUNNEL_KEY_OK:
444 return "CADET_TUNNEL_KEY_OK";
445 case CADET_TUNNEL_KEY_REKEY:
446 return "CADET_TUNNEL_KEY_REKEY";
448 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
455 * Return the peer to which this tunnel goes.
458 * @return the destination of the tunnel
461 GCT_get_destination (struct CadetTunnel *t)
463 return t->destination;
468 * Count channels of a tunnel.
470 * @param t Tunnel on which to count.
472 * @return Number of channels.
475 GCT_count_channels (struct CadetTunnel *t)
477 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
482 * Lookup a channel by its @a ctn.
484 * @param t tunnel to look in
485 * @param ctn number of channel to find
486 * @return NULL if channel does not exist
488 struct CadetChannel *
489 lookup_channel (struct CadetTunnel *t,
490 struct GNUNET_CADET_ChannelTunnelNumber ctn)
492 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
498 * Count all created connections of a tunnel. Not necessarily ready connections!
500 * @param t Tunnel on which to count.
502 * @return Number of connections created, either being established or ready.
505 GCT_count_any_connections (struct CadetTunnel *t)
507 return t->num_connections;
512 * Find first connection that is ready in the list of
513 * our connections. Picks ready connections round-robin.
515 * @param t tunnel to search
516 * @return NULL if we have no connection that is ready
518 static struct CadetTConnection *
519 get_ready_connection (struct CadetTunnel *t)
521 for (struct CadetTConnection *pos = t->connection_head;
524 if (GNUNET_YES == pos->is_ready)
526 if (pos != t->connection_tail)
528 /* move 'pos' to the end, so we try other ready connections
529 first next time (round-robin, modulo availability) */
530 GNUNET_CONTAINER_DLL_remove (t->connection_head,
533 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
544 * Get the encryption state of a tunnel.
548 * @return Tunnel's encryption state.
550 enum CadetTunnelEState
551 GCT_get_estate (struct CadetTunnel *t)
558 * Create a new Axolotl ephemeral (ratchet) key.
563 new_ephemeral (struct CadetTunnel *t)
565 GNUNET_free_non_null (t->ax.DHRs);
566 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
572 * Called when either we have a new connection, or a new message in the
573 * queue, or some existing connection has transmission capacity. Looks
574 * at our message queue and if there is a message, picks a connection
577 * @param cls the `struct CadetTunnel` to process messages on
580 trigger_transmissions (void *cls);
583 /* ************************************** start core crypto ***************************** */
589 * @param plaintext Content to HMAC.
590 * @param size Size of @c plaintext.
591 * @param iv Initialization vector for the message.
592 * @param key Key to use.
593 * @param hmac[out] Destination to store the HMAC.
596 t_hmac (const void *plaintext,
599 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
600 struct GNUNET_ShortHashCode *hmac)
602 static const char ctx[] = "cadet authentication key";
603 struct GNUNET_CRYPTO_AuthKey auth_key;
604 struct GNUNET_HashCode hash;
606 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
612 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
613 GNUNET_CRYPTO_hmac (&auth_key,
626 * @param key Key to use.
627 * @param hash[out] Resulting HMAC.
628 * @param source Source key material (data to HMAC).
629 * @param len Length of @a source.
632 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
633 struct GNUNET_HashCode *hash,
637 static const char ctx[] = "axolotl HMAC-HASH";
638 struct GNUNET_CRYPTO_AuthKey auth_key;
640 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
644 GNUNET_CRYPTO_hmac (&auth_key,
652 * Derive a symmetric encryption key from an HMAC-HASH.
654 * @param key Key to use for the HMAC.
655 * @param[out] out Key to generate.
656 * @param source Source key material (data to HMAC).
657 * @param len Length of @a source.
660 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
661 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
665 static const char ctx[] = "axolotl derive key";
666 struct GNUNET_HashCode h;
672 GNUNET_CRYPTO_kdf (out, sizeof (*out),
680 * Encrypt data with the axolotl tunnel key.
682 * @param t Tunnel whose key to use.
683 * @param dst Destination with @a size bytes for the encrypted data.
684 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
685 * @param size Size of the buffers at @a src and @a dst
688 t_ax_encrypt (struct CadetTunnel *t,
693 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
694 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
695 struct CadetTunnelAxolotl *ax;
699 ax->ratchet_counter++;
700 if ( (GNUNET_YES == ax->ratchet_allowed) &&
701 ( (ratchet_messages <= ax->ratchet_counter) ||
702 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
704 ax->ratchet_flag = GNUNET_YES;
706 if (GNUNET_YES == ax->ratchet_flag)
708 /* Advance ratchet */
709 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
710 struct GNUNET_HashCode dh;
711 struct GNUNET_HashCode hmac;
712 static const char ctx[] = "axolotl ratchet";
717 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
718 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
721 t_ax_hmac_hash (&ax->RK,
725 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
727 &hmac, sizeof (hmac),
735 ax->ratchet_flag = GNUNET_NO;
736 ax->ratchet_allowed = GNUNET_NO;
737 ax->ratchet_counter = 0;
738 ax->ratchet_expiration
739 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
743 t_hmac_derive_key (&ax->CKs,
747 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
752 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
757 GNUNET_assert (size == out_size);
758 t_hmac_derive_key (&ax->CKs,
766 * Decrypt data with the axolotl tunnel key.
768 * @param t Tunnel whose key to use.
769 * @param dst Destination for the decrypted data, must contain @a size bytes.
770 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
771 * @param size Size of the @a src and @a dst buffers
774 t_ax_decrypt (struct CadetTunnel *t,
779 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
780 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
781 struct CadetTunnelAxolotl *ax;
785 t_hmac_derive_key (&ax->CKr,
789 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
793 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
794 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
799 GNUNET_assert (out_size == size);
800 t_hmac_derive_key (&ax->CKr,
808 * Encrypt header with the axolotl header key.
810 * @param t Tunnel whose key to use.
811 * @param msg Message whose header to encrypt.
814 t_h_encrypt (struct CadetTunnel *t,
815 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
817 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
818 struct CadetTunnelAxolotl *ax;
822 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
826 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
831 GNUNET_assert (AX_HEADER_SIZE == out_size);
836 * Decrypt header with the current axolotl header key.
838 * @param t Tunnel whose current ax HK to use.
839 * @param src Message whose header to decrypt.
840 * @param dst Where to decrypt header to.
843 t_h_decrypt (struct CadetTunnel *t,
844 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
845 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
847 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
848 struct CadetTunnelAxolotl *ax;
852 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
856 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
861 GNUNET_assert (AX_HEADER_SIZE == out_size);
866 * Delete a key from the list of skipped keys.
868 * @param t Tunnel to delete from.
869 * @param key Key to delete.
872 delete_skipped_key (struct CadetTunnel *t,
873 struct CadetTunnelSkippedKey *key)
875 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
884 * Decrypt and verify data with the appropriate tunnel key and verify that the
885 * data has not been altered since it was sent by the remote peer.
887 * @param t Tunnel whose key to use.
888 * @param dst Destination for the plaintext.
889 * @param src Source of the message. Can overlap with @c dst.
890 * @param size Size of the message.
891 * @return Size of the decrypted data, -1 if an error was encountered.
894 try_old_ax_keys (struct CadetTunnel *t,
896 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
899 struct CadetTunnelSkippedKey *key;
900 struct GNUNET_ShortHashCode *hmac;
901 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
902 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
903 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
909 LOG (GNUNET_ERROR_TYPE_DEBUG,
910 "Trying skipped keys\n");
911 hmac = &plaintext_header.hmac;
912 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
914 /* Find a correct Header Key */
916 for (key = t->ax.skipped_head; NULL != key; key = key->next)
919 AX_HEADER_SIZE + esize,
923 if (0 == memcmp (hmac,
934 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
935 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
936 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
937 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
940 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
944 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
948 &plaintext_header.Ns);
949 GNUNET_assert (AX_HEADER_SIZE == res);
951 /* Find the correct message key */
952 N = ntohl (plaintext_header.Ns);
953 while ( (NULL != key) &&
956 if ( (NULL == key) ||
957 (0 != memcmp (&key->HK,
959 sizeof (*valid_HK))) )
962 /* Decrypt payload */
963 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
968 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
973 delete_skipped_key (t,
980 * Delete a key from the list of skipped keys.
982 * @param t Tunnel to delete from.
983 * @param HKr Header Key to use.
986 store_skipped_key (struct CadetTunnel *t,
987 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
989 struct CadetTunnelSkippedKey *key;
991 key = GNUNET_new (struct CadetTunnelSkippedKey);
992 key->timestamp = GNUNET_TIME_absolute_get ();
995 t_hmac_derive_key (&t->ax.CKr,
999 t_hmac_derive_key (&t->ax.CKr,
1003 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1012 * Stage skipped AX keys and calculate the message key.
1013 * Stores each HK and MK for skipped messages.
1015 * @param t Tunnel where to stage the keys.
1016 * @param HKr Header key.
1017 * @param Np Received meesage number.
1018 * @return #GNUNET_OK if keys were stored.
1019 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1022 store_ax_keys (struct CadetTunnel *t,
1023 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1028 gap = Np - t->ax.Nr;
1029 LOG (GNUNET_ERROR_TYPE_DEBUG,
1030 "Storing skipped keys [%u, %u)\n",
1033 if (MAX_KEY_GAP < gap)
1035 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1036 /* TODO: start new key exchange on return */
1037 GNUNET_break_op (0);
1038 LOG (GNUNET_ERROR_TYPE_WARNING,
1039 "Got message %u, expected %u+\n",
1042 return GNUNET_SYSERR;
1046 /* Delayed message: don't store keys, flag to try old keys. */
1047 return GNUNET_SYSERR;
1050 while (t->ax.Nr < Np)
1051 store_skipped_key (t,
1054 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1055 delete_skipped_key (t,
1056 t->ax.skipped_tail);
1062 * Decrypt and verify data with the appropriate tunnel key and verify that the
1063 * data has not been altered since it was sent by the remote peer.
1065 * @param t Tunnel whose key to use.
1066 * @param dst Destination for the plaintext.
1067 * @param src Source of the message. Can overlap with @c dst.
1068 * @param size Size of the message.
1069 * @return Size of the decrypted data, -1 if an error was encountered.
1072 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1074 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1077 struct CadetTunnelAxolotl *ax;
1078 struct GNUNET_ShortHashCode msg_hmac;
1079 struct GNUNET_HashCode hmac;
1080 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1083 size_t esize; /* Size of encryped payload */
1085 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1088 /* Try current HK */
1090 AX_HEADER_SIZE + esize,
1093 if (0 != memcmp (&msg_hmac,
1097 static const char ctx[] = "axolotl ratchet";
1098 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1099 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1100 struct GNUNET_HashCode dh;
1101 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1105 AX_HEADER_SIZE + esize,
1109 if (0 != memcmp (&msg_hmac,
1113 /* Try the skipped keys, if that fails, we're out of luck. */
1114 return try_old_ax_keys (t,
1124 Np = ntohl (plaintext_header.Ns);
1125 PNp = ntohl (plaintext_header.PNs);
1126 DHRp = &plaintext_header.DHRs;
1131 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1132 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1135 t_ax_hmac_hash (&ax->RK,
1138 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1140 &hmac, sizeof (hmac),
1143 /* Commit "purported" keys */
1149 ax->ratchet_allowed = GNUNET_YES;
1156 Np = ntohl (plaintext_header.Ns);
1157 PNp = ntohl (plaintext_header.PNs);
1159 if ( (Np != ax->Nr) &&
1160 (GNUNET_OK != store_ax_keys (t,
1164 /* Try the skipped keys, if that fails, we're out of luck. */
1165 return try_old_ax_keys (t,
1181 * Our tunnel became ready for the first time, notify channels
1182 * that have been waiting.
1184 * @param cls our tunnel, not used
1185 * @param key unique ID of the channel, not used
1186 * @param value the `struct CadetChannel` to notify
1187 * @return #GNUNET_OK (continue to iterate)
1190 notify_tunnel_up_cb (void *cls,
1194 struct CadetChannel *ch = value;
1196 GCCH_tunnel_up (ch);
1202 * Change the tunnel encryption state.
1203 * If the encryption state changes to OK, stop the rekey task.
1205 * @param t Tunnel whose encryption state to change, or NULL.
1206 * @param state New encryption state.
1209 GCT_change_estate (struct CadetTunnel *t,
1210 enum CadetTunnelEState state)
1212 enum CadetTunnelEState old = t->estate;
1215 LOG (GNUNET_ERROR_TYPE_DEBUG,
1216 "Tunnel %s estate changed from %d to %d\n",
1221 if ( (CADET_TUNNEL_KEY_OK != old) &&
1222 (CADET_TUNNEL_KEY_OK == t->estate) )
1224 if (NULL != t->kx_task)
1226 GNUNET_SCHEDULER_cancel (t->kx_task);
1229 if (CADET_TUNNEL_KEY_REKEY != old)
1231 /* notify all channels that have been waiting */
1232 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1233 ¬ify_tunnel_up_cb,
1237 /* FIXME: schedule rekey task! */
1243 * Send a KX message.
1245 * FIXME: does not take care of sender-authentication yet!
1247 * @param t Tunnel on which to send it.
1248 * @param force_reply Force the other peer to reply with a KX message.
1251 send_kx (struct CadetTunnel *t,
1254 struct CadetTunnelAxolotl *ax = &t->ax;
1255 struct CadetTConnection *ct;
1256 struct CadetConnection *cc;
1257 struct GNUNET_MQ_Envelope *env;
1258 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1259 enum GNUNET_CADET_KX_Flags flags;
1261 ct = get_ready_connection (t);
1264 LOG (GNUNET_ERROR_TYPE_DEBUG,
1265 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1270 LOG (GNUNET_ERROR_TYPE_DEBUG,
1271 "Sending KX on tunnel %s using connection %s\n",
1275 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1276 env = GNUNET_MQ_msg (msg,
1277 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1278 flags = GNUNET_CADET_KX_FLAG_NONE;
1279 if (GNUNET_YES == force_reply)
1280 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1281 msg->flags = htonl (flags);
1282 msg->cid = *GCC_get_id (cc);
1283 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1284 &msg->ephemeral_key);
1285 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1287 ct->is_ready = GNUNET_NO;
1290 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1291 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1292 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1293 GCT_change_estate (t,
1294 CADET_TUNNEL_KEY_SENT);
1299 * Handle KX message.
1301 * FIXME: sender-authentication in KX is missing!
1303 * @param ct connection/tunnel combo that received encrypted message
1304 * @param msg the key exchange message
1307 GCT_handle_kx (struct CadetTConnection *ct,
1308 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1310 struct CadetTunnel *t = ct->t;
1311 struct CadetTunnelAxolotl *ax = &t->ax;
1312 struct GNUNET_HashCode key_material[3];
1313 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1314 const char salt[] = "CADET Axolotl salt";
1315 const struct GNUNET_PeerIdentity *pid;
1318 pid = GCP_get_id (t->destination);
1319 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1321 am_I_alice = GNUNET_YES;
1322 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1324 am_I_alice = GNUNET_NO;
1327 GNUNET_break_op (0);
1331 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1333 if (NULL != t->kx_task)
1335 GNUNET_SCHEDULER_cancel (t->kx_task);
1342 if (0 == memcmp (&ax->DHRr,
1344 sizeof (msg->ratchet_key)))
1346 LOG (GNUNET_ERROR_TYPE_DEBUG,
1347 " known ratchet key, exit\n");
1351 ax->DHRr = msg->ratchet_key;
1354 if (GNUNET_YES == am_I_alice)
1356 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1357 &msg->ephemeral_key, /* B0 */
1362 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1363 &pid->public_key, /* A */
1368 if (GNUNET_YES == am_I_alice)
1370 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1371 &pid->public_key, /* B */
1376 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1377 &msg->ephemeral_key, /* B0 */
1384 /* (This is the triple-DH, we could probably safely skip this,
1385 as A0/B0 are already in the key material.) */
1386 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1387 &msg->ephemeral_key, /* B0 or A0 */
1391 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1392 salt, sizeof (salt),
1393 &key_material, sizeof (key_material),
1396 if (0 == memcmp (&ax->RK,
1400 LOG (GNUNET_ERROR_TYPE_INFO,
1401 " known handshake key, exit\n");
1404 LOG (GNUNET_ERROR_TYPE_DEBUG,
1405 "Handling KX message for tunnel %s\n",
1409 if (GNUNET_YES == am_I_alice)
1415 ax->ratchet_flag = GNUNET_YES;
1423 ax->ratchet_flag = GNUNET_NO;
1424 ax->ratchet_allowed = GNUNET_NO;
1425 ax->ratchet_counter = 0;
1426 ax->ratchet_expiration
1427 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1436 case CADET_TUNNEL_KEY_UNINITIALIZED:
1437 GCT_change_estate (t,
1438 CADET_TUNNEL_KEY_PING);
1440 case CADET_TUNNEL_KEY_SENT:
1441 /* Got a response to us sending our key; now
1442 we can start transmitting! */
1443 GCT_change_estate (t,
1444 CADET_TUNNEL_KEY_OK);
1445 if (NULL != t->send_task)
1446 GNUNET_SCHEDULER_cancel (t->send_task);
1447 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1450 case CADET_TUNNEL_KEY_PING:
1451 /* Got a key yet again; need encrypted payload to advance */
1453 case CADET_TUNNEL_KEY_OK:
1454 /* Did not expect a key, but so what. */
1456 case CADET_TUNNEL_KEY_REKEY:
1457 /* Got a key yet again; need encrypted payload to advance */
1463 /* ************************************** end core crypto ***************************** */
1467 * Compute the next free channel tunnel number for this tunnel.
1469 * @param t the tunnel
1470 * @return unused number that can uniquely identify a channel in the tunnel
1472 static struct GNUNET_CADET_ChannelTunnelNumber
1473 get_next_free_ctn (struct CadetTunnel *t)
1475 struct GNUNET_CADET_ChannelTunnelNumber ret;
1478 /* FIXME: this logic does NOT prevent both ends of the
1479 channel from picking the same CTN!
1480 Need to reserve one bit of the CTN for the
1481 direction, i.e. which side established the connection! */
1482 ctn = ntohl (t->next_ctn.cn);
1484 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1487 t->next_ctn.cn = htonl (ctn + 1);
1488 ret.cn = ntohl (ctn);
1494 * Add a channel to a tunnel, and notify channel that we are ready
1495 * for transmission if we are already up. Otherwise that notification
1496 * will be done later in #notify_tunnel_up_cb().
1500 * @return unique number identifying @a ch within @a t
1502 struct GNUNET_CADET_ChannelTunnelNumber
1503 GCT_add_channel (struct CadetTunnel *t,
1504 struct CadetChannel *ch)
1506 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1508 ctn = get_next_free_ctn (t);
1509 GNUNET_assert (GNUNET_YES ==
1510 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1513 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1514 LOG (GNUNET_ERROR_TYPE_DEBUG,
1515 "Adding channel %s to tunnel %s\n",
1518 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1519 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1520 GCCH_tunnel_up (ch);
1526 * This tunnel is no longer used, destroy it.
1528 * @param cls the idle tunnel
1531 destroy_tunnel (void *cls)
1533 struct CadetTunnel *t = cls;
1534 struct CadetTConnection *ct;
1535 struct CadetTunnelQueueEntry *tq;
1537 t->destroy_task = NULL;
1538 LOG (GNUNET_ERROR_TYPE_DEBUG,
1539 "Destroying idle tunnel %s\n",
1541 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1542 while (NULL != (ct = t->connection_head))
1544 GNUNET_assert (ct->t == t);
1545 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1548 GCC_destroy (ct->cc);
1551 while (NULL != (tq = t->tq_head))
1553 if (NULL != tq->cont)
1554 tq->cont (tq->cont_cls);
1555 GCT_send_cancel (tq);
1557 GCP_drop_tunnel (t->destination,
1559 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1560 if (NULL != t->maintain_connections_task)
1562 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1563 t->maintain_connections_task = NULL;
1565 if (NULL != t->send_task)
1567 GNUNET_SCHEDULER_cancel (t->send_task);
1568 t->send_task = NULL;
1570 if (NULL != t->kx_task)
1572 GNUNET_SCHEDULER_cancel (t->kx_task);
1575 GNUNET_MST_destroy (t->mst);
1576 GNUNET_MQ_destroy (t->mq);
1577 while (NULL != t->ax.skipped_head)
1578 delete_skipped_key (t,
1579 t->ax.skipped_head);
1580 GNUNET_assert (0 == t->ax.skipped);
1581 GNUNET_free_non_null (t->ax.kx_0);
1582 GNUNET_free_non_null (t->ax.DHRs);
1588 * Remove a channel from a tunnel.
1592 * @param ctn unique number identifying @a ch within @a t
1595 GCT_remove_channel (struct CadetTunnel *t,
1596 struct CadetChannel *ch,
1597 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1599 LOG (GNUNET_ERROR_TYPE_DEBUG,
1600 "Removing channel %s from tunnel %s\n",
1603 GNUNET_assert (GNUNET_YES ==
1604 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1608 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1610 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1618 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1620 * @param t tunnel to destroy
1623 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1626 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1627 if (NULL != t->destroy_task)
1629 GNUNET_SCHEDULER_cancel (t->destroy_task);
1630 t->destroy_task = NULL;
1637 * It's been a while, we should try to redo the KX, if we can.
1639 * @param cls the `struct CadetTunnel` to do KX for.
1642 retry_kx (void *cls)
1644 struct CadetTunnel *t = cls;
1648 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1649 (CADET_TUNNEL_KEY_SENT == t->estate) )
1656 * Send normal payload from queue in @a t via connection @a ct.
1657 * Does nothing if our payload queue is empty.
1659 * @param t tunnel to send data from
1660 * @param ct connection to use for transmission (is ready)
1663 try_send_normal_payload (struct CadetTunnel *t,
1664 struct CadetTConnection *ct)
1666 struct CadetTunnelQueueEntry *tq;
1668 GNUNET_assert (GNUNET_YES == ct->is_ready);
1672 /* no messages pending right now */
1673 LOG (GNUNET_ERROR_TYPE_DEBUG,
1674 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1679 /* ready to send message 'tq' on tunnel 'ct' */
1680 GNUNET_assert (t == tq->t);
1681 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1684 if (NULL != tq->cid)
1685 *tq->cid = *GCC_get_id (ct->cc);
1686 ct->is_ready = GNUNET_NO;
1687 LOG (GNUNET_ERROR_TYPE_DEBUG,
1688 "Sending payload of tunnel %s on connection %s\n",
1691 GCC_transmit (ct->cc,
1693 if (NULL != tq->cont)
1694 tq->cont (tq->cont_cls);
1700 * A connection is @a is_ready for transmission. Looks at our message
1701 * queue and if there is a message, sends it out via the connection.
1703 * @param cls the `struct CadetTConnection` that is @a is_ready
1704 * @param is_ready #GNUNET_YES if connection are now ready,
1705 * #GNUNET_NO if connection are no longer ready
1708 connection_ready_cb (void *cls,
1711 struct CadetTConnection *ct = cls;
1712 struct CadetTunnel *t = ct->t;
1714 if (GNUNET_NO == is_ready)
1716 LOG (GNUNET_ERROR_TYPE_DEBUG,
1717 "Connection %s no longer ready for tunnel %s\n",
1720 ct->is_ready = GNUNET_NO;
1723 ct->is_ready = GNUNET_YES;
1724 LOG (GNUNET_ERROR_TYPE_DEBUG,
1725 "Connection %s now ready for tunnel %s in state %s\n",
1728 estate2s (t->estate));
1731 case CADET_TUNNEL_KEY_UNINITIALIZED:
1735 case CADET_TUNNEL_KEY_SENT:
1736 case CADET_TUNNEL_KEY_PING:
1737 /* opportunity to #retry_kx() starts now, schedule job */
1738 if (NULL == t->kx_task)
1741 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1746 case CADET_TUNNEL_KEY_OK:
1747 try_send_normal_payload (t,
1750 case CADET_TUNNEL_KEY_REKEY:
1753 t->estate = CADET_TUNNEL_KEY_OK;
1760 * Called when either we have a new connection, or a new message in the
1761 * queue, or some existing connection has transmission capacity. Looks
1762 * at our message queue and if there is a message, picks a connection
1765 * @param cls the `struct CadetTunnel` to process messages on
1768 trigger_transmissions (void *cls)
1770 struct CadetTunnel *t = cls;
1771 struct CadetTConnection *ct;
1773 t->send_task = NULL;
1774 if (NULL == t->tq_head)
1775 return; /* no messages pending right now */
1776 ct = get_ready_connection (t);
1778 return; /* no connections ready */
1779 try_send_normal_payload (t,
1785 * Consider using the path @a p for the tunnel @a t.
1786 * The tunnel destination is at offset @a off in path @a p.
1788 * @param cls our tunnel
1789 * @param path a path to our destination
1790 * @param off offset of the destination on path @a path
1791 * @return #GNUNET_YES (should keep iterating)
1794 consider_path_cb (void *cls,
1795 struct CadetPeerPath *path,
1798 struct CadetTunnel *t = cls;
1799 unsigned int min_length = UINT_MAX;
1800 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1801 struct CadetTConnection *ct;
1803 /* Check if we care about the new path. */
1804 for (ct = t->connection_head;
1808 struct CadetPeerPath *ps;
1810 ps = GCC_get_path (ct->cc);
1813 LOG (GNUNET_ERROR_TYPE_DEBUG,
1814 "Ignoring duplicate path %s for tunnel %s.\n",
1817 return GNUNET_YES; /* duplicate */
1819 min_length = GNUNET_MIN (min_length,
1820 GCPP_get_length (ps));
1821 max_desire = GNUNET_MAX (max_desire,
1822 GCPP_get_desirability (ps));
1825 /* FIXME: not sure we should really just count
1826 'num_connections' here, as they may all have
1827 consistently failed to connect. */
1829 /* We iterate by increasing path length; if we have enough paths and
1830 this one is more than twice as long than what we are currently
1831 using, then ignore all of these super-long ones! */
1832 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1833 (min_length * 2 < off) )
1835 LOG (GNUNET_ERROR_TYPE_DEBUG,
1836 "Ignoring paths of length %u, they are way too long.\n",
1840 /* If we have enough paths and this one looks no better, ignore it. */
1841 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1842 (min_length < GCPP_get_length (path)) &&
1843 (max_desire > GCPP_get_desirability (path)) )
1845 LOG (GNUNET_ERROR_TYPE_DEBUG,
1846 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1847 GCPP_get_length (path),
1848 (unsigned long long) GCPP_get_desirability (path),
1849 GCP_2s (t->destination));
1853 /* Path is interesting (better by some metric, or we don't have
1854 enough paths yet). */
1855 ct = GNUNET_new (struct CadetTConnection);
1856 ct->created = GNUNET_TIME_absolute_get ();
1858 ct->cc = GCC_create (t->destination,
1861 &connection_ready_cb,
1863 /* FIXME: schedule job to kill connection (and path?) if it takes
1864 too long to get ready! (And track performance data on how long
1865 other connections took with the tunnel!)
1866 => Note: to be done within 'connection'-logic! */
1867 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1870 t->num_connections++;
1871 LOG (GNUNET_ERROR_TYPE_DEBUG,
1872 "Found interesting path %s for tunnel %s, created connection %s\n",
1881 * Function called to maintain the connections underlying our tunnel.
1882 * Tries to maintain (incl. tear down) connections for the tunnel, and
1883 * if there is a significant change, may trigger transmissions.
1885 * Basically, needs to check if there are connections that perform
1886 * badly, and if so eventually kill them and trigger a replacement.
1887 * The strategy is to open one more connection than
1888 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1889 * least-performing one, and then inquire for new ones.
1891 * @param cls the `struct CadetTunnel`
1894 maintain_connections_cb (void *cls)
1896 struct CadetTunnel *t = cls;
1898 t->maintain_connections_task = NULL;
1899 LOG (GNUNET_ERROR_TYPE_DEBUG,
1900 "Performing connection maintenance for tunnel %s.\n",
1903 (void) GCP_iterate_paths (t->destination,
1907 GNUNET_break (0); // FIXME: implement!
1912 * Consider using the path @a p for the tunnel @a t.
1913 * The tunnel destination is at offset @a off in path @a p.
1915 * @param cls our tunnel
1916 * @param path a path to our destination
1917 * @param off offset of the destination on path @a path
1920 GCT_consider_path (struct CadetTunnel *t,
1921 struct CadetPeerPath *p,
1924 (void) consider_path_cb (t,
1933 * @param cls the `struct CadetTunnel` for which we decrypted the message
1934 * @param msg the message we received on the tunnel
1937 handle_plaintext_keepalive (void *cls,
1938 const struct GNUNET_MessageHeader *msg)
1940 struct CadetTunnel *t = cls;
1942 GNUNET_break (0); // FIXME
1947 * Check that @a msg is well-formed.
1949 * @param cls the `struct CadetTunnel` for which we decrypted the message
1950 * @param msg the message we received on the tunnel
1951 * @return #GNUNET_OK (any variable-size payload goes)
1954 check_plaintext_data (void *cls,
1955 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1962 * We received payload data for a channel. Locate the channel
1963 * and process the data, or return an error if the channel is unknown.
1965 * @param cls the `struct CadetTunnel` for which we decrypted the message
1966 * @param msg the message we received on the tunnel
1969 handle_plaintext_data (void *cls,
1970 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1972 struct CadetTunnel *t = cls;
1973 struct CadetChannel *ch;
1975 ch = lookup_channel (t,
1979 /* We don't know about such a channel, might have been destroyed on our
1980 end in the meantime, or never existed. Send back a DESTROY. */
1981 LOG (GNUNET_ERROR_TYPE_DEBUG,
1982 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
1983 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
1984 ntohl (msg->ctn.cn));
1985 GCT_send_channel_destroy (t,
1989 GCCH_handle_channel_plaintext_data (ch,
1995 * We received an acknowledgement for data we sent on a channel.
1996 * Locate the channel and process it, or return an error if the
1997 * channel is unknown.
1999 * @param cls the `struct CadetTunnel` for which we decrypted the message
2000 * @param ack the message we received on the tunnel
2003 handle_plaintext_data_ack (void *cls,
2004 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2006 struct CadetTunnel *t = cls;
2007 struct CadetChannel *ch;
2009 ch = lookup_channel (t,
2013 /* We don't know about such a channel, might have been destroyed on our
2014 end in the meantime, or never existed. Send back a DESTROY. */
2015 LOG (GNUNET_ERROR_TYPE_DEBUG,
2016 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2017 ntohl (ack->ctn.cn));
2018 GCT_send_channel_destroy (t,
2022 GCCH_handle_channel_plaintext_data_ack (ch,
2028 * We have received a request to open a channel to a port from
2029 * another peer. Creates the incoming channel.
2031 * @param cls the `struct CadetTunnel` for which we decrypted the message
2032 * @param cc the message we received on the tunnel
2035 handle_plaintext_channel_open (void *cls,
2036 const struct GNUNET_CADET_ChannelOpenMessage *cc)
2038 struct CadetTunnel *t = cls;
2039 struct CadetChannel *ch;
2040 struct GNUNET_CADET_ChannelTunnelNumber ctn;
2042 LOG (GNUNET_ERROR_TYPE_DEBUG,
2043 "Receicved channel OPEN on port %s from peer %s\n",
2044 GNUNET_h2s (&cc->port),
2045 GCP_2s (GCT_get_destination (t)));
2046 ctn = get_next_free_ctn (t);
2047 ch = GCCH_channel_incoming_new (t,
2051 GNUNET_assert (GNUNET_OK ==
2052 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2055 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2060 * Send a DESTROY message via the tunnel.
2062 * @param t the tunnel to transmit over
2063 * @param ctn ID of the channel to destroy
2066 GCT_send_channel_destroy (struct CadetTunnel *t,
2067 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2069 struct GNUNET_CADET_ChannelManageMessage msg;
2071 LOG (GNUNET_ERROR_TYPE_DEBUG,
2072 "Sending DESTORY message for channel ID %u\n",
2074 msg.header.size = htons (sizeof (msg));
2075 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2076 msg.reserved = htonl (0);
2086 * We have received confirmation from the target peer that the
2087 * given channel could be established (the port is open).
2090 * @param cls the `struct CadetTunnel` for which we decrypted the message
2091 * @param cm the message we received on the tunnel
2094 handle_plaintext_channel_open_ack (void *cls,
2095 const struct GNUNET_CADET_ChannelManageMessage *cm)
2097 struct CadetTunnel *t = cls;
2098 struct CadetChannel *ch;
2100 ch = lookup_channel (t,
2104 /* We don't know about such a channel, might have been destroyed on our
2105 end in the meantime, or never existed. Send back a DESTROY. */
2106 LOG (GNUNET_ERROR_TYPE_DEBUG,
2107 "Received channel OPEN_ACK for unknown channel, sending DESTROY\n",
2109 GCT_send_channel_destroy (t,
2113 GCCH_handle_channel_open_ack (ch);
2118 * We received a message saying that a channel should be destroyed.
2119 * Pass it on to the correct channel.
2121 * @param cls the `struct CadetTunnel` for which we decrypted the message
2122 * @param cm the message we received on the tunnel
2125 handle_plaintext_channel_destroy (void *cls,
2126 const struct GNUNET_CADET_ChannelManageMessage *cm)
2128 struct CadetTunnel *t = cls;
2129 struct CadetChannel *ch;
2131 ch = lookup_channel (t,
2135 /* We don't know about such a channel, might have been destroyed on our
2136 end in the meantime, or never existed. */
2137 LOG (GNUNET_ERROR_TYPE_DEBUG,
2138 "Received channel DESTORY for unknown channel. Ignoring.\n",
2142 GCCH_handle_remote_destroy (ch);
2147 * Handles a message we decrypted, by injecting it into
2148 * our message queue (which will do the dispatching).
2150 * @param cls the `struct CadetTunnel` that got the message
2151 * @param msg the message
2152 * @return #GNUNET_OK (continue to process)
2155 handle_decrypted (void *cls,
2156 const struct GNUNET_MessageHeader *msg)
2158 struct CadetTunnel *t = cls;
2160 GNUNET_MQ_inject_message (t->mq,
2167 * Function called if we had an error processing
2168 * an incoming decrypted message.
2170 * @param cls the `struct CadetTunnel`
2171 * @param error error code
2174 decrypted_error_cb (void *cls,
2175 enum GNUNET_MQ_Error error)
2177 GNUNET_break_op (0);
2182 * Create a tunnel to @a destionation. Must only be called
2183 * from within #GCP_get_tunnel().
2185 * @param destination where to create the tunnel to
2186 * @return new tunnel to @a destination
2188 struct CadetTunnel *
2189 GCT_create_tunnel (struct CadetPeer *destination)
2191 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2192 struct GNUNET_MQ_MessageHandler handlers[] = {
2193 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2194 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2195 struct GNUNET_MessageHeader,
2197 GNUNET_MQ_hd_var_size (plaintext_data,
2198 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2199 struct GNUNET_CADET_ChannelAppDataMessage,
2201 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2202 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2203 struct GNUNET_CADET_ChannelDataAckMessage,
2205 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2206 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2207 struct GNUNET_CADET_ChannelOpenMessage,
2209 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2210 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2211 struct GNUNET_CADET_ChannelManageMessage,
2213 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2214 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2215 struct GNUNET_CADET_ChannelManageMessage,
2217 GNUNET_MQ_handler_end ()
2221 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2222 t->destination = destination;
2223 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2224 t->maintain_connections_task
2225 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2227 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2232 &decrypted_error_cb,
2234 t->mst = GNUNET_MST_create (&handle_decrypted,
2241 * Add a @a connection to the @a tunnel.
2244 * @param cid connection identifer to use for the connection
2245 * @param path path to use for the connection
2248 GCT_add_inbound_connection (struct CadetTunnel *t,
2249 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2250 struct CadetPeerPath *path)
2252 struct CadetTConnection *ct;
2254 ct = GNUNET_new (struct CadetTConnection);
2255 ct->created = GNUNET_TIME_absolute_get ();
2257 ct->cc = GCC_create_inbound (t->destination,
2261 &connection_ready_cb,
2263 /* FIXME: schedule job to kill connection (and path?) if it takes
2264 too long to get ready! (And track performance data on how long
2265 other connections took with the tunnel!)
2266 => Note: to be done within 'connection'-logic! */
2267 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2270 t->num_connections++;
2271 LOG (GNUNET_ERROR_TYPE_DEBUG,
2272 "Tunnel %s has new connection %s\n",
2279 * Handle encrypted message.
2281 * @param ct connection/tunnel combo that received encrypted message
2282 * @param msg the encrypted message to decrypt
2285 GCT_handle_encrypted (struct CadetTConnection *ct,
2286 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2288 struct CadetTunnel *t = ct->t;
2289 uint16_t size = ntohs (msg->header.size);
2290 char cbuf [size] GNUNET_ALIGN;
2291 ssize_t decrypted_size;
2293 LOG (GNUNET_ERROR_TYPE_DEBUG,
2294 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2296 (unsigned int) size,
2301 case CADET_TUNNEL_KEY_UNINITIALIZED:
2302 /* We did not even SEND our KX, how can the other peer
2303 send us encrypted data? */
2304 GNUNET_break_op (0);
2306 case CADET_TUNNEL_KEY_SENT:
2307 /* We did not get the KX of the other peer, but that
2308 might have been lost. Ask for KX again. */
2309 GNUNET_STATISTICS_update (stats,
2310 "# received encrypted without KX",
2313 if (NULL != t->kx_task)
2314 GNUNET_SCHEDULER_cancel (t->kx_task);
2315 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2318 case CADET_TUNNEL_KEY_PING:
2319 /* Great, first payload, we might graduate to OK */
2320 case CADET_TUNNEL_KEY_OK:
2321 case CADET_TUNNEL_KEY_REKEY:
2325 GNUNET_STATISTICS_update (stats,
2326 "# received encrypted",
2329 decrypted_size = t_ax_decrypt_and_validate (t,
2334 if (-1 == decrypted_size)
2336 GNUNET_break_op (0);
2337 LOG (GNUNET_ERROR_TYPE_WARNING,
2338 "Tunnel %s failed to decrypt and validate encrypted data\n",
2340 GNUNET_STATISTICS_update (stats,
2341 "# unable to decrypt",
2346 if (CADET_TUNNEL_KEY_PING == t->estate)
2348 GCT_change_estate (t,
2349 CADET_TUNNEL_KEY_OK);
2350 if (NULL != t->send_task)
2351 GNUNET_SCHEDULER_cancel (t->send_task);
2352 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2355 /* The MST will ultimately call #handle_decrypted() on each message. */
2356 GNUNET_break_op (GNUNET_OK ==
2357 GNUNET_MST_from_buffer (t->mst,
2366 * Sends an already built message on a tunnel, encrypting it and
2367 * choosing the best connection if not provided.
2369 * @param message Message to send. Function modifies it.
2370 * @param t Tunnel on which this message is transmitted.
2371 * @param cont Continuation to call once message is really sent.
2372 * @param cont_cls Closure for @c cont.
2373 * @return Handle to cancel message. NULL if @c cont is NULL.
2375 struct CadetTunnelQueueEntry *
2376 GCT_send (struct CadetTunnel *t,
2377 const struct GNUNET_MessageHeader *message,
2378 GNUNET_SCHEDULER_TaskCallback cont,
2381 struct CadetTunnelQueueEntry *tq;
2382 uint16_t payload_size;
2383 struct GNUNET_MQ_Envelope *env;
2384 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2386 payload_size = ntohs (message->size);
2387 LOG (GNUNET_ERROR_TYPE_DEBUG,
2388 "Encrypting %u bytes of for tunnel %s\n",
2389 (unsigned int) payload_size,
2391 env = GNUNET_MQ_msg_extra (ax_msg,
2393 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2398 ax_msg->Ns = htonl (t->ax.Ns++);
2399 ax_msg->PNs = htonl (t->ax.PNs);
2400 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2404 t_hmac (&ax_msg->Ns,
2405 AX_HEADER_SIZE + payload_size,
2410 tq = GNUNET_malloc (sizeof (*tq));
2413 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2415 tq->cont_cls = cont_cls;
2416 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2419 if (NULL != t->send_task)
2420 GNUNET_SCHEDULER_cancel (t->send_task);
2422 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2429 * Cancel a previously sent message while it's in the queue.
2431 * ONLY can be called before the continuation given to the send
2432 * function is called. Once the continuation is called, the message is
2433 * no longer in the queue!
2435 * @param tq Handle to the queue entry to cancel.
2438 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2440 struct CadetTunnel *t = tq->t;
2442 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2445 GNUNET_MQ_discard (tq->env);
2451 * Iterate over all connections of a tunnel.
2453 * @param t Tunnel whose connections to iterate.
2454 * @param iter Iterator.
2455 * @param iter_cls Closure for @c iter.
2458 GCT_iterate_connections (struct CadetTunnel *t,
2459 GCT_ConnectionIterator iter,
2462 for (struct CadetTConnection *ct = t->connection_head;
2471 * Closure for #iterate_channels_cb.
2478 GCT_ChannelIterator iter;
2481 * Closure for @e iter.
2488 * Helper function for #GCT_iterate_channels.
2490 * @param cls the `struct ChanIterCls`
2492 * @param value a `struct CadetChannel`
2493 * @return #GNUNET_OK
2496 iterate_channels_cb (void *cls,
2500 struct ChanIterCls *ctx = cls;
2501 struct CadetChannel *ch = value;
2503 ctx->iter (ctx->iter_cls,
2510 * Iterate over all channels of a tunnel.
2512 * @param t Tunnel whose channels to iterate.
2513 * @param iter Iterator.
2514 * @param iter_cls Closure for @c iter.
2517 GCT_iterate_channels (struct CadetTunnel *t,
2518 GCT_ChannelIterator iter,
2521 struct ChanIterCls ctx;
2524 ctx.iter_cls = iter_cls;
2525 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2526 &iterate_channels_cb,
2533 * Call #GCCH_debug() on a channel.
2535 * @param cls points to the log level to use
2537 * @param value the `struct CadetChannel` to dump
2538 * @return #GNUNET_OK (continue iteration)
2541 debug_channel (void *cls,
2545 const enum GNUNET_ErrorType *level = cls;
2546 struct CadetChannel *ch = value;
2548 GCCH_debug (ch, *level);
2553 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2557 * Log all possible info about the tunnel state.
2559 * @param t Tunnel to debug.
2560 * @param level Debug level to use.
2563 GCT_debug (const struct CadetTunnel *t,
2564 enum GNUNET_ErrorType level)
2566 struct CadetTConnection *iter_c;
2569 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2571 __FILE__, __FUNCTION__, __LINE__);
2576 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2578 estate2s (t->estate),
2580 t->num_connections);
2581 #if DUMP_KEYS_TO_STDERR
2582 ax_debug (t->ax, level);
2586 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2590 "TTT connections:\n");
2591 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2592 GCC_debug (iter_c->cc,
2596 "TTT TUNNEL END\n");
2600 /* end of gnunet-service-cadet-new_tunnels.c */