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 #define HIGH_BIT 0x8000000
1476 struct GNUNET_CADET_ChannelTunnelNumber ret;
1481 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1482 GCP_get_id (GCT_get_destination (t)));
1488 GNUNET_assert (0); // loopback must never go here!
1489 ctn = ntohl (t->next_ctn.cn);
1491 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1494 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1496 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1497 ret.cn = ntohl (ctn);
1503 * Add a channel to a tunnel, and notify channel that we are ready
1504 * for transmission if we are already up. Otherwise that notification
1505 * will be done later in #notify_tunnel_up_cb().
1509 * @return unique number identifying @a ch within @a t
1511 struct GNUNET_CADET_ChannelTunnelNumber
1512 GCT_add_channel (struct CadetTunnel *t,
1513 struct CadetChannel *ch)
1515 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1517 ctn = get_next_free_ctn (t);
1518 GNUNET_assert (GNUNET_YES ==
1519 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1522 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1523 LOG (GNUNET_ERROR_TYPE_DEBUG,
1524 "Adding channel %s to tunnel %s\n",
1527 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1528 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1529 GCCH_tunnel_up (ch);
1535 * This tunnel is no longer used, destroy it.
1537 * @param cls the idle tunnel
1540 destroy_tunnel (void *cls)
1542 struct CadetTunnel *t = cls;
1543 struct CadetTConnection *ct;
1544 struct CadetTunnelQueueEntry *tq;
1546 t->destroy_task = NULL;
1547 LOG (GNUNET_ERROR_TYPE_DEBUG,
1548 "Destroying idle tunnel %s\n",
1550 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1551 while (NULL != (ct = t->connection_head))
1553 GNUNET_assert (ct->t == t);
1554 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1557 GCC_destroy (ct->cc);
1560 while (NULL != (tq = t->tq_head))
1562 if (NULL != tq->cont)
1563 tq->cont (tq->cont_cls);
1564 GCT_send_cancel (tq);
1566 GCP_drop_tunnel (t->destination,
1568 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1569 if (NULL != t->maintain_connections_task)
1571 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1572 t->maintain_connections_task = NULL;
1574 if (NULL != t->send_task)
1576 GNUNET_SCHEDULER_cancel (t->send_task);
1577 t->send_task = NULL;
1579 if (NULL != t->kx_task)
1581 GNUNET_SCHEDULER_cancel (t->kx_task);
1584 GNUNET_MST_destroy (t->mst);
1585 GNUNET_MQ_destroy (t->mq);
1586 while (NULL != t->ax.skipped_head)
1587 delete_skipped_key (t,
1588 t->ax.skipped_head);
1589 GNUNET_assert (0 == t->ax.skipped);
1590 GNUNET_free_non_null (t->ax.kx_0);
1591 GNUNET_free_non_null (t->ax.DHRs);
1597 * Remove a channel from a tunnel.
1601 * @param ctn unique number identifying @a ch within @a t
1604 GCT_remove_channel (struct CadetTunnel *t,
1605 struct CadetChannel *ch,
1606 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1608 LOG (GNUNET_ERROR_TYPE_DEBUG,
1609 "Removing channel %s from tunnel %s\n",
1612 GNUNET_assert (GNUNET_YES ==
1613 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1617 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1619 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1627 * Destroy remaining channels during shutdown.
1629 * @param cls the `struct CadetTunnel` of the channel
1630 * @param key key of the channel
1631 * @param value the `struct CadetChannel`
1632 * @return #GNUNET_OK (continue to iterate)
1635 destroy_remaining_channels (void *cls,
1639 struct CadetChannel *ch = value;
1641 GCCH_handle_remote_destroy (ch);
1647 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1649 * @param t tunnel to destroy
1652 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1654 GNUNET_assert (GNUNET_YES == shutting_down);
1655 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1656 &destroy_remaining_channels,
1659 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1660 if (NULL != t->destroy_task)
1662 GNUNET_SCHEDULER_cancel (t->destroy_task);
1663 t->destroy_task = NULL;
1670 * It's been a while, we should try to redo the KX, if we can.
1672 * @param cls the `struct CadetTunnel` to do KX for.
1675 retry_kx (void *cls)
1677 struct CadetTunnel *t = cls;
1681 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1682 (CADET_TUNNEL_KEY_SENT == t->estate) )
1689 * Send normal payload from queue in @a t via connection @a ct.
1690 * Does nothing if our payload queue is empty.
1692 * @param t tunnel to send data from
1693 * @param ct connection to use for transmission (is ready)
1696 try_send_normal_payload (struct CadetTunnel *t,
1697 struct CadetTConnection *ct)
1699 struct CadetTunnelQueueEntry *tq;
1701 GNUNET_assert (GNUNET_YES == ct->is_ready);
1705 /* no messages pending right now */
1706 LOG (GNUNET_ERROR_TYPE_DEBUG,
1707 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1712 /* ready to send message 'tq' on tunnel 'ct' */
1713 GNUNET_assert (t == tq->t);
1714 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1717 if (NULL != tq->cid)
1718 *tq->cid = *GCC_get_id (ct->cc);
1719 ct->is_ready = GNUNET_NO;
1720 LOG (GNUNET_ERROR_TYPE_DEBUG,
1721 "Sending payload of tunnel %s on connection %s\n",
1724 GCC_transmit (ct->cc,
1726 if (NULL != tq->cont)
1727 tq->cont (tq->cont_cls);
1733 * A connection is @a is_ready for transmission. Looks at our message
1734 * queue and if there is a message, sends it out via the connection.
1736 * @param cls the `struct CadetTConnection` that is @a is_ready
1737 * @param is_ready #GNUNET_YES if connection are now ready,
1738 * #GNUNET_NO if connection are no longer ready
1741 connection_ready_cb (void *cls,
1744 struct CadetTConnection *ct = cls;
1745 struct CadetTunnel *t = ct->t;
1747 if (GNUNET_NO == is_ready)
1749 LOG (GNUNET_ERROR_TYPE_DEBUG,
1750 "Connection %s no longer ready for tunnel %s\n",
1753 ct->is_ready = GNUNET_NO;
1756 ct->is_ready = GNUNET_YES;
1757 LOG (GNUNET_ERROR_TYPE_DEBUG,
1758 "Connection %s now ready for tunnel %s in state %s\n",
1761 estate2s (t->estate));
1764 case CADET_TUNNEL_KEY_UNINITIALIZED:
1768 case CADET_TUNNEL_KEY_SENT:
1769 case CADET_TUNNEL_KEY_PING:
1770 /* opportunity to #retry_kx() starts now, schedule job */
1771 if (NULL == t->kx_task)
1774 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1779 case CADET_TUNNEL_KEY_OK:
1780 try_send_normal_payload (t,
1783 case CADET_TUNNEL_KEY_REKEY:
1786 t->estate = CADET_TUNNEL_KEY_OK;
1793 * Called when either we have a new connection, or a new message in the
1794 * queue, or some existing connection has transmission capacity. Looks
1795 * at our message queue and if there is a message, picks a connection
1798 * @param cls the `struct CadetTunnel` to process messages on
1801 trigger_transmissions (void *cls)
1803 struct CadetTunnel *t = cls;
1804 struct CadetTConnection *ct;
1806 t->send_task = NULL;
1807 if (NULL == t->tq_head)
1808 return; /* no messages pending right now */
1809 ct = get_ready_connection (t);
1811 return; /* no connections ready */
1812 try_send_normal_payload (t,
1818 * Consider using the path @a p for the tunnel @a t.
1819 * The tunnel destination is at offset @a off in path @a p.
1821 * @param cls our tunnel
1822 * @param path a path to our destination
1823 * @param off offset of the destination on path @a path
1824 * @return #GNUNET_YES (should keep iterating)
1827 consider_path_cb (void *cls,
1828 struct CadetPeerPath *path,
1831 struct CadetTunnel *t = cls;
1832 unsigned int min_length = UINT_MAX;
1833 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1834 struct CadetTConnection *ct;
1836 /* Check if we care about the new path. */
1837 for (ct = t->connection_head;
1841 struct CadetPeerPath *ps;
1843 ps = GCC_get_path (ct->cc);
1846 LOG (GNUNET_ERROR_TYPE_DEBUG,
1847 "Ignoring duplicate path %s for tunnel %s.\n",
1850 return GNUNET_YES; /* duplicate */
1852 min_length = GNUNET_MIN (min_length,
1853 GCPP_get_length (ps));
1854 max_desire = GNUNET_MAX (max_desire,
1855 GCPP_get_desirability (ps));
1858 /* FIXME: not sure we should really just count
1859 'num_connections' here, as they may all have
1860 consistently failed to connect. */
1862 /* We iterate by increasing path length; if we have enough paths and
1863 this one is more than twice as long than what we are currently
1864 using, then ignore all of these super-long ones! */
1865 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1866 (min_length * 2 < off) )
1868 LOG (GNUNET_ERROR_TYPE_DEBUG,
1869 "Ignoring paths of length %u, they are way too long.\n",
1873 /* If we have enough paths and this one looks no better, ignore it. */
1874 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1875 (min_length < GCPP_get_length (path)) &&
1876 (max_desire > GCPP_get_desirability (path)) )
1878 LOG (GNUNET_ERROR_TYPE_DEBUG,
1879 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1880 GCPP_get_length (path),
1881 (unsigned long long) GCPP_get_desirability (path),
1882 GCP_2s (t->destination));
1886 /* Path is interesting (better by some metric, or we don't have
1887 enough paths yet). */
1888 ct = GNUNET_new (struct CadetTConnection);
1889 ct->created = GNUNET_TIME_absolute_get ();
1891 ct->cc = GCC_create (t->destination,
1894 &connection_ready_cb,
1896 /* FIXME: schedule job to kill connection (and path?) if it takes
1897 too long to get ready! (And track performance data on how long
1898 other connections took with the tunnel!)
1899 => Note: to be done within 'connection'-logic! */
1900 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1903 t->num_connections++;
1904 LOG (GNUNET_ERROR_TYPE_DEBUG,
1905 "Found interesting path %s for tunnel %s, created connection %s\n",
1914 * Function called to maintain the connections underlying our tunnel.
1915 * Tries to maintain (incl. tear down) connections for the tunnel, and
1916 * if there is a significant change, may trigger transmissions.
1918 * Basically, needs to check if there are connections that perform
1919 * badly, and if so eventually kill them and trigger a replacement.
1920 * The strategy is to open one more connection than
1921 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1922 * least-performing one, and then inquire for new ones.
1924 * @param cls the `struct CadetTunnel`
1927 maintain_connections_cb (void *cls)
1929 struct CadetTunnel *t = cls;
1931 t->maintain_connections_task = NULL;
1932 LOG (GNUNET_ERROR_TYPE_DEBUG,
1933 "Performing connection maintenance for tunnel %s.\n",
1936 (void) GCP_iterate_paths (t->destination,
1940 GNUNET_break (0); // FIXME: implement!
1945 * Consider using the path @a p for the tunnel @a t.
1946 * The tunnel destination is at offset @a off in path @a p.
1948 * @param cls our tunnel
1949 * @param path a path to our destination
1950 * @param off offset of the destination on path @a path
1953 GCT_consider_path (struct CadetTunnel *t,
1954 struct CadetPeerPath *p,
1957 (void) consider_path_cb (t,
1966 * @param cls the `struct CadetTunnel` for which we decrypted the message
1967 * @param msg the message we received on the tunnel
1970 handle_plaintext_keepalive (void *cls,
1971 const struct GNUNET_MessageHeader *msg)
1973 struct CadetTunnel *t = cls;
1975 GNUNET_break (0); // FIXME
1980 * Check that @a msg is well-formed.
1982 * @param cls the `struct CadetTunnel` for which we decrypted the message
1983 * @param msg the message we received on the tunnel
1984 * @return #GNUNET_OK (any variable-size payload goes)
1987 check_plaintext_data (void *cls,
1988 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1995 * We received payload data for a channel. Locate the channel
1996 * and process the data, or return an error if the channel is unknown.
1998 * @param cls the `struct CadetTunnel` for which we decrypted the message
1999 * @param msg the message we received on the tunnel
2002 handle_plaintext_data (void *cls,
2003 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2005 struct CadetTunnel *t = cls;
2006 struct CadetChannel *ch;
2008 ch = lookup_channel (t,
2012 /* We don't know about such a channel, might have been destroyed on our
2013 end in the meantime, or never existed. Send back a DESTROY. */
2014 LOG (GNUNET_ERROR_TYPE_DEBUG,
2015 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2016 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2017 ntohl (msg->ctn.cn));
2018 GCT_send_channel_destroy (t,
2022 GCCH_handle_channel_plaintext_data (ch,
2028 * We received an acknowledgement for data we sent on a channel.
2029 * Locate the channel and process it, or return an error if the
2030 * channel is unknown.
2032 * @param cls the `struct CadetTunnel` for which we decrypted the message
2033 * @param ack the message we received on the tunnel
2036 handle_plaintext_data_ack (void *cls,
2037 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2039 struct CadetTunnel *t = cls;
2040 struct CadetChannel *ch;
2042 ch = lookup_channel (t,
2046 /* We don't know about such a channel, might have been destroyed on our
2047 end in the meantime, or never existed. Send back a DESTROY. */
2048 LOG (GNUNET_ERROR_TYPE_DEBUG,
2049 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2050 ntohl (ack->ctn.cn));
2051 GCT_send_channel_destroy (t,
2055 GCCH_handle_channel_plaintext_data_ack (ch,
2061 * We have received a request to open a channel to a port from
2062 * another peer. Creates the incoming channel.
2064 * @param cls the `struct CadetTunnel` for which we decrypted the message
2065 * @param copen the message we received on the tunnel
2068 handle_plaintext_channel_open (void *cls,
2069 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2071 struct CadetTunnel *t = cls;
2072 struct CadetChannel *ch;
2074 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2075 ntohl (copen->ctn.cn));
2078 LOG (GNUNET_ERROR_TYPE_DEBUG,
2079 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2080 GNUNET_h2s (&copen->port),
2083 GCCH_handle_duplicate_open (ch);
2086 LOG (GNUNET_ERROR_TYPE_DEBUG,
2087 "Receicved channel OPEN on port %s from %s\n",
2088 GNUNET_h2s (&copen->port),
2090 ch = GCCH_channel_incoming_new (t,
2093 ntohl (copen->opt));
2094 GNUNET_assert (GNUNET_OK ==
2095 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2096 ntohl (copen->ctn.cn),
2098 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2103 * Send a DESTROY message via the tunnel.
2105 * @param t the tunnel to transmit over
2106 * @param ctn ID of the channel to destroy
2109 GCT_send_channel_destroy (struct CadetTunnel *t,
2110 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2112 struct GNUNET_CADET_ChannelManageMessage msg;
2114 LOG (GNUNET_ERROR_TYPE_DEBUG,
2115 "Sending DESTORY message for channel ID %u\n",
2117 msg.header.size = htons (sizeof (msg));
2118 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2119 msg.reserved = htonl (0);
2129 * We have received confirmation from the target peer that the
2130 * given channel could be established (the port is open).
2133 * @param cls the `struct CadetTunnel` for which we decrypted the message
2134 * @param cm the message we received on the tunnel
2137 handle_plaintext_channel_open_ack (void *cls,
2138 const struct GNUNET_CADET_ChannelManageMessage *cm)
2140 struct CadetTunnel *t = cls;
2141 struct CadetChannel *ch;
2143 ch = lookup_channel (t,
2147 /* We don't know about such a channel, might have been destroyed on our
2148 end in the meantime, or never existed. Send back a DESTROY. */
2149 LOG (GNUNET_ERROR_TYPE_DEBUG,
2150 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2151 ntohl (cm->ctn.cn));
2152 GCT_send_channel_destroy (t,
2156 LOG (GNUNET_ERROR_TYPE_DEBUG,
2157 "Receicved channel OPEN_ACK on channel %s from %s\n",
2160 GCCH_handle_channel_open_ack (ch);
2165 * We received a message saying that a channel should be destroyed.
2166 * Pass it on to the correct channel.
2168 * @param cls the `struct CadetTunnel` for which we decrypted the message
2169 * @param cm the message we received on the tunnel
2172 handle_plaintext_channel_destroy (void *cls,
2173 const struct GNUNET_CADET_ChannelManageMessage *cm)
2175 struct CadetTunnel *t = cls;
2176 struct CadetChannel *ch;
2178 ch = lookup_channel (t,
2182 /* We don't know about such a channel, might have been destroyed on our
2183 end in the meantime, or never existed. */
2184 LOG (GNUNET_ERROR_TYPE_DEBUG,
2185 "Received channel DESTORY for unknown channel. Ignoring.\n",
2189 LOG (GNUNET_ERROR_TYPE_DEBUG,
2190 "Receicved channel DESTROY on %s from %s\n",
2193 GCCH_handle_remote_destroy (ch);
2198 * Handles a message we decrypted, by injecting it into
2199 * our message queue (which will do the dispatching).
2201 * @param cls the `struct CadetTunnel` that got the message
2202 * @param msg the message
2203 * @return #GNUNET_OK (continue to process)
2206 handle_decrypted (void *cls,
2207 const struct GNUNET_MessageHeader *msg)
2209 struct CadetTunnel *t = cls;
2211 GNUNET_MQ_inject_message (t->mq,
2218 * Function called if we had an error processing
2219 * an incoming decrypted message.
2221 * @param cls the `struct CadetTunnel`
2222 * @param error error code
2225 decrypted_error_cb (void *cls,
2226 enum GNUNET_MQ_Error error)
2228 GNUNET_break_op (0);
2233 * Create a tunnel to @a destionation. Must only be called
2234 * from within #GCP_get_tunnel().
2236 * @param destination where to create the tunnel to
2237 * @return new tunnel to @a destination
2239 struct CadetTunnel *
2240 GCT_create_tunnel (struct CadetPeer *destination)
2242 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2243 struct GNUNET_MQ_MessageHandler handlers[] = {
2244 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2245 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2246 struct GNUNET_MessageHeader,
2248 GNUNET_MQ_hd_var_size (plaintext_data,
2249 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2250 struct GNUNET_CADET_ChannelAppDataMessage,
2252 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2253 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2254 struct GNUNET_CADET_ChannelDataAckMessage,
2256 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2257 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2258 struct GNUNET_CADET_ChannelOpenMessage,
2260 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2261 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2262 struct GNUNET_CADET_ChannelManageMessage,
2264 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2265 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2266 struct GNUNET_CADET_ChannelManageMessage,
2268 GNUNET_MQ_handler_end ()
2272 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2273 t->destination = destination;
2274 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2275 t->maintain_connections_task
2276 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2278 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2283 &decrypted_error_cb,
2285 t->mst = GNUNET_MST_create (&handle_decrypted,
2292 * Add a @a connection to the @a tunnel.
2295 * @param cid connection identifer to use for the connection
2296 * @param path path to use for the connection
2299 GCT_add_inbound_connection (struct CadetTunnel *t,
2300 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2301 struct CadetPeerPath *path)
2303 struct CadetTConnection *ct;
2305 ct = GNUNET_new (struct CadetTConnection);
2306 ct->created = GNUNET_TIME_absolute_get ();
2308 ct->cc = GCC_create_inbound (t->destination,
2312 &connection_ready_cb,
2314 /* FIXME: schedule job to kill connection (and path?) if it takes
2315 too long to get ready! (And track performance data on how long
2316 other connections took with the tunnel!)
2317 => Note: to be done within 'connection'-logic! */
2318 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2321 t->num_connections++;
2322 LOG (GNUNET_ERROR_TYPE_DEBUG,
2323 "Tunnel %s has new connection %s\n",
2330 * Handle encrypted message.
2332 * @param ct connection/tunnel combo that received encrypted message
2333 * @param msg the encrypted message to decrypt
2336 GCT_handle_encrypted (struct CadetTConnection *ct,
2337 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2339 struct CadetTunnel *t = ct->t;
2340 uint16_t size = ntohs (msg->header.size);
2341 char cbuf [size] GNUNET_ALIGN;
2342 ssize_t decrypted_size;
2344 LOG (GNUNET_ERROR_TYPE_DEBUG,
2345 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2347 (unsigned int) size,
2352 case CADET_TUNNEL_KEY_UNINITIALIZED:
2353 /* We did not even SEND our KX, how can the other peer
2354 send us encrypted data? */
2355 GNUNET_break_op (0);
2357 case CADET_TUNNEL_KEY_SENT:
2358 /* We did not get the KX of the other peer, but that
2359 might have been lost. Ask for KX again. */
2360 GNUNET_STATISTICS_update (stats,
2361 "# received encrypted without KX",
2364 if (NULL != t->kx_task)
2365 GNUNET_SCHEDULER_cancel (t->kx_task);
2366 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2369 case CADET_TUNNEL_KEY_PING:
2370 /* Great, first payload, we might graduate to OK */
2371 case CADET_TUNNEL_KEY_OK:
2372 case CADET_TUNNEL_KEY_REKEY:
2376 GNUNET_STATISTICS_update (stats,
2377 "# received encrypted",
2380 decrypted_size = t_ax_decrypt_and_validate (t,
2385 if (-1 == decrypted_size)
2387 GNUNET_break_op (0);
2388 LOG (GNUNET_ERROR_TYPE_WARNING,
2389 "Tunnel %s failed to decrypt and validate encrypted data\n",
2391 GNUNET_STATISTICS_update (stats,
2392 "# unable to decrypt",
2397 if (CADET_TUNNEL_KEY_PING == t->estate)
2399 GCT_change_estate (t,
2400 CADET_TUNNEL_KEY_OK);
2401 if (NULL != t->send_task)
2402 GNUNET_SCHEDULER_cancel (t->send_task);
2403 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2406 /* The MST will ultimately call #handle_decrypted() on each message. */
2407 GNUNET_break_op (GNUNET_OK ==
2408 GNUNET_MST_from_buffer (t->mst,
2417 * Sends an already built message on a tunnel, encrypting it and
2418 * choosing the best connection if not provided.
2420 * @param message Message to send. Function modifies it.
2421 * @param t Tunnel on which this message is transmitted.
2422 * @param cont Continuation to call once message is really sent.
2423 * @param cont_cls Closure for @c cont.
2424 * @return Handle to cancel message. NULL if @c cont is NULL.
2426 struct CadetTunnelQueueEntry *
2427 GCT_send (struct CadetTunnel *t,
2428 const struct GNUNET_MessageHeader *message,
2429 GNUNET_SCHEDULER_TaskCallback cont,
2432 struct CadetTunnelQueueEntry *tq;
2433 uint16_t payload_size;
2434 struct GNUNET_MQ_Envelope *env;
2435 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2437 payload_size = ntohs (message->size);
2438 LOG (GNUNET_ERROR_TYPE_DEBUG,
2439 "Encrypting %u bytes for tunnel %s\n",
2440 (unsigned int) payload_size,
2442 env = GNUNET_MQ_msg_extra (ax_msg,
2444 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2449 ax_msg->Ns = htonl (t->ax.Ns++);
2450 ax_msg->PNs = htonl (t->ax.PNs);
2451 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2455 t_hmac (&ax_msg->Ns,
2456 AX_HEADER_SIZE + payload_size,
2461 tq = GNUNET_malloc (sizeof (*tq));
2464 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2466 tq->cont_cls = cont_cls;
2467 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2470 if (NULL != t->send_task)
2471 GNUNET_SCHEDULER_cancel (t->send_task);
2473 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2480 * Cancel a previously sent message while it's in the queue.
2482 * ONLY can be called before the continuation given to the send
2483 * function is called. Once the continuation is called, the message is
2484 * no longer in the queue!
2486 * @param tq Handle to the queue entry to cancel.
2489 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2491 struct CadetTunnel *t = tq->t;
2493 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2496 GNUNET_MQ_discard (tq->env);
2502 * Iterate over all connections of a tunnel.
2504 * @param t Tunnel whose connections to iterate.
2505 * @param iter Iterator.
2506 * @param iter_cls Closure for @c iter.
2509 GCT_iterate_connections (struct CadetTunnel *t,
2510 GCT_ConnectionIterator iter,
2513 for (struct CadetTConnection *ct = t->connection_head;
2522 * Closure for #iterate_channels_cb.
2529 GCT_ChannelIterator iter;
2532 * Closure for @e iter.
2539 * Helper function for #GCT_iterate_channels.
2541 * @param cls the `struct ChanIterCls`
2543 * @param value a `struct CadetChannel`
2544 * @return #GNUNET_OK
2547 iterate_channels_cb (void *cls,
2551 struct ChanIterCls *ctx = cls;
2552 struct CadetChannel *ch = value;
2554 ctx->iter (ctx->iter_cls,
2561 * Iterate over all channels of a tunnel.
2563 * @param t Tunnel whose channels to iterate.
2564 * @param iter Iterator.
2565 * @param iter_cls Closure for @c iter.
2568 GCT_iterate_channels (struct CadetTunnel *t,
2569 GCT_ChannelIterator iter,
2572 struct ChanIterCls ctx;
2575 ctx.iter_cls = iter_cls;
2576 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2577 &iterate_channels_cb,
2584 * Call #GCCH_debug() on a channel.
2586 * @param cls points to the log level to use
2588 * @param value the `struct CadetChannel` to dump
2589 * @return #GNUNET_OK (continue iteration)
2592 debug_channel (void *cls,
2596 const enum GNUNET_ErrorType *level = cls;
2597 struct CadetChannel *ch = value;
2599 GCCH_debug (ch, *level);
2604 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2608 * Log all possible info about the tunnel state.
2610 * @param t Tunnel to debug.
2611 * @param level Debug level to use.
2614 GCT_debug (const struct CadetTunnel *t,
2615 enum GNUNET_ErrorType level)
2617 struct CadetTConnection *iter_c;
2620 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2622 __FILE__, __FUNCTION__, __LINE__);
2627 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2629 estate2s (t->estate),
2631 t->num_connections);
2632 #if DUMP_KEYS_TO_STDERR
2633 ax_debug (t->ax, level);
2637 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2641 "TTT connections:\n");
2642 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2643 GCC_debug (iter_c->cc,
2647 "TTT TUNNEL END\n");
2651 /* end of gnunet-service-cadet-new_tunnels.c */