2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
28 * + implement rekeying
29 * + check KX estate machine -- make sure it is never stuck!
30 * + clean up KX logic, including adding sender authentication
31 * - connection management
32 * + properly (evaluate, kill old ones, search for new ones)
33 * + when managing connections, distinguish those that
34 * have (recently) had traffic from those that were
35 * never ready (or not recently)
38 #include "gnunet_util_lib.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_signatures.h"
41 #include "gnunet-service-cadet-new.h"
42 #include "cadet_protocol.h"
43 #include "gnunet-service-cadet-new_channel.h"
44 #include "gnunet-service-cadet-new_connection.h"
45 #include "gnunet-service-cadet-new_tunnels.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
50 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
54 * How long do we wait until tearing down an idle tunnel?
56 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
59 * Yuck, replace by 'offsetof' expression?
62 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
63 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
67 * Maximum number of skipped keys we keep in memory per tunnel.
69 #define MAX_SKIPPED_KEYS 64
72 * Maximum number of keys (and thus ratchet steps) we are willing to
73 * skip before we decide this is either a bogus packet or a DoS-attempt.
75 #define MAX_KEY_GAP 256
79 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
81 struct CadetTunnelSkippedKey
86 struct CadetTunnelSkippedKey *next;
91 struct CadetTunnelSkippedKey *prev;
94 * When was this key stored (for timeout).
96 struct GNUNET_TIME_Absolute timestamp;
101 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
106 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
109 * Key number for a given HK.
116 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
118 struct CadetTunnelAxolotl
121 * A (double linked) list of stored message keys and associated header keys
122 * for "skipped" messages, i.e. messages that have not been
123 * received despite the reception of more recent messages, (head).
125 struct CadetTunnelSkippedKey *skipped_head;
128 * Skipped messages' keys DLL, tail.
130 struct CadetTunnelSkippedKey *skipped_tail;
133 * 32-byte root key which gets updated by DH ratchet.
135 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
138 * 32-byte header key (send).
140 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
143 * 32-byte header key (recv)
145 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
148 * 32-byte next header key (send).
150 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
153 * 32-byte next header key (recv).
155 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
158 * 32-byte chain keys (used for forward-secrecy updating, send).
160 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
163 * 32-byte chain keys (used for forward-secrecy updating, recv).
165 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
168 * ECDH for key exchange (A0 / B0).
170 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
173 * ECDH Ratchet key (send).
175 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
178 * ECDH Ratchet key (recv).
180 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
183 * When does this ratchet expire and a new one is triggered.
185 struct GNUNET_TIME_Absolute ratchet_expiration;
188 * Number of elements in @a skipped_head <-> @a skipped_tail.
190 unsigned int skipped;
193 * Message number (reset to 0 with each new ratchet, next message to send).
198 * Message number (reset to 0 with each new ratchet, next message to recv).
203 * Previous message numbers (# of msgs sent under prev ratchet)
208 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
213 * Number of messages recieved since our last ratchet advance.
214 * - If this counter = 0, we cannot send a new ratchet key in next msg.
215 * - If this counter > 0, we can (but don't yet have to) send a new key.
217 unsigned int ratchet_allowed;
220 * Number of messages recieved since our last ratchet advance.
221 * - If this counter = 0, we cannot send a new ratchet key in next msg.
222 * - If this counter > 0, we can (but don't yet have to) send a new key.
224 unsigned int ratchet_counter;
230 * Struct used to save messages in a non-ready tunnel to send once connected.
232 struct CadetTunnelQueueEntry
235 * We are entries in a DLL
237 struct CadetTunnelQueueEntry *next;
240 * We are entries in a DLL
242 struct CadetTunnelQueueEntry *prev;
245 * Tunnel these messages belong in.
247 struct CadetTunnel *t;
250 * Continuation to call once sent (on the channel layer).
252 GNUNET_SCHEDULER_TaskCallback cont;
255 * Closure for @c cont.
260 * Envelope of message to send follows.
262 struct GNUNET_MQ_Envelope *env;
265 * Where to put the connection identifier into the payload
266 * of the message in @e env once we have it?
268 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
273 * Struct containing all information regarding a tunnel to a peer.
278 * Destination of the tunnel.
280 struct CadetPeer *destination;
283 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
284 * ephemeral key changes.
286 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
289 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
291 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
294 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
296 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
301 struct CadetTunnelAxolotl ax;
304 * Task scheduled if there are no more channels using the tunnel.
306 struct GNUNET_SCHEDULER_Task *destroy_task;
309 * Task to trim connections if too many are present.
311 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
314 * Task to send messages from queue (if possible).
316 struct GNUNET_SCHEDULER_Task *send_task;
319 * Task to trigger KX.
321 struct GNUNET_SCHEDULER_Task *kx_task;
324 * Tokenizer for decrypted messages.
326 struct GNUNET_MessageStreamTokenizer *mst;
329 * Dispatcher for decrypted messages only (do NOT use for sending!).
331 struct GNUNET_MQ_Handle *mq;
334 * DLL of connections that are actively used to reach the destination peer.
336 struct CadetTConnection *connection_head;
339 * DLL of connections that are actively used to reach the destination peer.
341 struct CadetTConnection *connection_tail;
344 * Channels inside this tunnel. Maps
345 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
347 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
350 * Channel ID for the next created channel in this tunnel.
352 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
355 * Queued messages, to transmit once tunnel gets connected.
357 struct CadetTunnelQueueEntry *tq_head;
360 * Queued messages, to transmit once tunnel gets connected.
362 struct CadetTunnelQueueEntry *tq_tail;
365 * How long do we wait until we retry the KX?
367 struct GNUNET_TIME_Relative kx_retry_delay;
370 * When do we try the next KX?
372 struct GNUNET_TIME_Absolute next_kx_attempt;
375 * Number of connections in the @e connection_head DLL.
377 unsigned int num_connections;
380 * Number of entries in the @e tq_head DLL.
385 * State of the tunnel encryption.
387 enum CadetTunnelEState estate;
393 * Get the static string for the peer this tunnel is directed.
397 * @return Static string the destination peer's ID.
400 GCT_2s (const struct CadetTunnel *t)
405 return "Tunnel(NULL)";
406 GNUNET_snprintf (buf,
409 GNUNET_i2s (GCP_get_id (t->destination)));
415 * Get string description for tunnel encryption state.
417 * @param es Tunnel state.
419 * @return String representation.
422 estate2s (enum CadetTunnelEState es)
428 case CADET_TUNNEL_KEY_UNINITIALIZED:
429 return "CADET_TUNNEL_KEY_UNINITIALIZED";
430 case CADET_TUNNEL_KEY_SENT:
431 return "CADET_TUNNEL_KEY_SENT";
432 case CADET_TUNNEL_KEY_PING:
433 return "CADET_TUNNEL_KEY_PING";
434 case CADET_TUNNEL_KEY_OK:
435 return "CADET_TUNNEL_KEY_OK";
436 case CADET_TUNNEL_KEY_REKEY:
437 return "CADET_TUNNEL_KEY_REKEY";
439 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
446 * Return the peer to which this tunnel goes.
449 * @return the destination of the tunnel
452 GCT_get_destination (struct CadetTunnel *t)
454 return t->destination;
459 * Count channels of a tunnel.
461 * @param t Tunnel on which to count.
463 * @return Number of channels.
466 GCT_count_channels (struct CadetTunnel *t)
468 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
473 * Lookup a channel by its @a ctn.
475 * @param t tunnel to look in
476 * @param ctn number of channel to find
477 * @return NULL if channel does not exist
479 struct CadetChannel *
480 lookup_channel (struct CadetTunnel *t,
481 struct GNUNET_CADET_ChannelTunnelNumber ctn)
483 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
489 * Count all created connections of a tunnel. Not necessarily ready connections!
491 * @param t Tunnel on which to count.
493 * @return Number of connections created, either being established or ready.
496 GCT_count_any_connections (struct CadetTunnel *t)
498 return t->num_connections;
503 * Find first connection that is ready in the list of
504 * our connections. Picks ready connections round-robin.
506 * @param t tunnel to search
507 * @return NULL if we have no connection that is ready
509 static struct CadetTConnection *
510 get_ready_connection (struct CadetTunnel *t)
512 for (struct CadetTConnection *pos = t->connection_head;
515 if (GNUNET_YES == pos->is_ready)
517 if (pos != t->connection_tail)
519 /* move 'pos' to the end, so we try other ready connections
520 first next time (round-robin, modulo availability) */
521 GNUNET_CONTAINER_DLL_remove (t->connection_head,
524 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
535 * Get the encryption state of a tunnel.
539 * @return Tunnel's encryption state.
541 enum CadetTunnelEState
542 GCT_get_estate (struct CadetTunnel *t)
549 * Create a new Axolotl ephemeral (ratchet) key.
554 new_ephemeral (struct CadetTunnel *t)
556 GNUNET_free_non_null (t->ax.DHRs);
557 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
563 * Called when either we have a new connection, or a new message in the
564 * queue, or some existing connection has transmission capacity. Looks
565 * at our message queue and if there is a message, picks a connection
568 * @param cls the `struct CadetTunnel` to process messages on
571 trigger_transmissions (void *cls);
574 /* ************************************** start core crypto ***************************** */
580 * @param plaintext Content to HMAC.
581 * @param size Size of @c plaintext.
582 * @param iv Initialization vector for the message.
583 * @param key Key to use.
584 * @param hmac[out] Destination to store the HMAC.
587 t_hmac (const void *plaintext,
590 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
591 struct GNUNET_ShortHashCode *hmac)
593 static const char ctx[] = "cadet authentication key";
594 struct GNUNET_CRYPTO_AuthKey auth_key;
595 struct GNUNET_HashCode hash;
597 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
603 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
604 GNUNET_CRYPTO_hmac (&auth_key,
617 * @param key Key to use.
618 * @param hash[out] Resulting HMAC.
619 * @param source Source key material (data to HMAC).
620 * @param len Length of @a source.
623 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
624 struct GNUNET_HashCode *hash,
628 static const char ctx[] = "axolotl HMAC-HASH";
629 struct GNUNET_CRYPTO_AuthKey auth_key;
631 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
635 GNUNET_CRYPTO_hmac (&auth_key,
643 * Derive a symmetric encryption key from an HMAC-HASH.
645 * @param key Key to use for the HMAC.
646 * @param[out] out Key to generate.
647 * @param source Source key material (data to HMAC).
648 * @param len Length of @a source.
651 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
652 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
656 static const char ctx[] = "axolotl derive key";
657 struct GNUNET_HashCode h;
663 GNUNET_CRYPTO_kdf (out, sizeof (*out),
671 * Encrypt data with the axolotl tunnel key.
673 * @param t Tunnel whose key to use.
674 * @param dst Destination with @a size bytes for the encrypted data.
675 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
676 * @param size Size of the buffers at @a src and @a dst
679 t_ax_encrypt (struct CadetTunnel *t,
684 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
685 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
686 struct CadetTunnelAxolotl *ax;
690 ax->ratchet_counter++;
691 if ( (GNUNET_YES == ax->ratchet_allowed) &&
692 ( (ratchet_messages <= ax->ratchet_counter) ||
693 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
695 ax->ratchet_flag = GNUNET_YES;
697 if (GNUNET_YES == ax->ratchet_flag)
699 /* Advance ratchet */
700 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
701 struct GNUNET_HashCode dh;
702 struct GNUNET_HashCode hmac;
703 static const char ctx[] = "axolotl ratchet";
708 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
709 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
712 t_ax_hmac_hash (&ax->RK,
716 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
718 &hmac, sizeof (hmac),
726 ax->ratchet_flag = GNUNET_NO;
727 ax->ratchet_allowed = GNUNET_NO;
728 ax->ratchet_counter = 0;
729 ax->ratchet_expiration
730 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
734 t_hmac_derive_key (&ax->CKs,
738 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
743 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
748 GNUNET_assert (size == out_size);
749 t_hmac_derive_key (&ax->CKs,
757 * Decrypt data with the axolotl tunnel key.
759 * @param t Tunnel whose key to use.
760 * @param dst Destination for the decrypted data, must contain @a size bytes.
761 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
762 * @param size Size of the @a src and @a dst buffers
765 t_ax_decrypt (struct CadetTunnel *t,
770 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
771 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
772 struct CadetTunnelAxolotl *ax;
776 t_hmac_derive_key (&ax->CKr,
780 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
784 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
785 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
790 GNUNET_assert (out_size == size);
791 t_hmac_derive_key (&ax->CKr,
799 * Encrypt header with the axolotl header key.
801 * @param t Tunnel whose key to use.
802 * @param msg Message whose header to encrypt.
805 t_h_encrypt (struct CadetTunnel *t,
806 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
808 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
809 struct CadetTunnelAxolotl *ax;
813 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
817 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
822 GNUNET_assert (AX_HEADER_SIZE == out_size);
827 * Decrypt header with the current axolotl header key.
829 * @param t Tunnel whose current ax HK to use.
830 * @param src Message whose header to decrypt.
831 * @param dst Where to decrypt header to.
834 t_h_decrypt (struct CadetTunnel *t,
835 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
836 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
838 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
839 struct CadetTunnelAxolotl *ax;
843 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
847 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
852 GNUNET_assert (AX_HEADER_SIZE == out_size);
857 * Delete a key from the list of skipped keys.
859 * @param t Tunnel to delete from.
860 * @param key Key to delete.
863 delete_skipped_key (struct CadetTunnel *t,
864 struct CadetTunnelSkippedKey *key)
866 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
875 * Decrypt and verify data with the appropriate tunnel key and verify that the
876 * data has not been altered since it was sent by the remote peer.
878 * @param t Tunnel whose key to use.
879 * @param dst Destination for the plaintext.
880 * @param src Source of the message. Can overlap with @c dst.
881 * @param size Size of the message.
882 * @return Size of the decrypted data, -1 if an error was encountered.
885 try_old_ax_keys (struct CadetTunnel *t,
887 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
890 struct CadetTunnelSkippedKey *key;
891 struct GNUNET_ShortHashCode *hmac;
892 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
893 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
894 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
900 LOG (GNUNET_ERROR_TYPE_DEBUG,
901 "Trying skipped keys\n");
902 hmac = &plaintext_header.hmac;
903 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
905 /* Find a correct Header Key */
907 for (key = t->ax.skipped_head; NULL != key; key = key->next)
910 AX_HEADER_SIZE + esize,
914 if (0 == memcmp (hmac,
925 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
926 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
927 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
928 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
931 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
935 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
939 &plaintext_header.Ns);
940 GNUNET_assert (AX_HEADER_SIZE == res);
942 /* Find the correct message key */
943 N = ntohl (plaintext_header.Ns);
944 while ( (NULL != key) &&
947 if ( (NULL == key) ||
948 (0 != memcmp (&key->HK,
950 sizeof (*valid_HK))) )
953 /* Decrypt payload */
954 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
959 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
964 delete_skipped_key (t,
971 * Delete a key from the list of skipped keys.
973 * @param t Tunnel to delete from.
974 * @param HKr Header Key to use.
977 store_skipped_key (struct CadetTunnel *t,
978 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
980 struct CadetTunnelSkippedKey *key;
982 key = GNUNET_new (struct CadetTunnelSkippedKey);
983 key->timestamp = GNUNET_TIME_absolute_get ();
986 t_hmac_derive_key (&t->ax.CKr,
990 t_hmac_derive_key (&t->ax.CKr,
994 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1003 * Stage skipped AX keys and calculate the message key.
1004 * Stores each HK and MK for skipped messages.
1006 * @param t Tunnel where to stage the keys.
1007 * @param HKr Header key.
1008 * @param Np Received meesage number.
1009 * @return #GNUNET_OK if keys were stored.
1010 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1013 store_ax_keys (struct CadetTunnel *t,
1014 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1019 gap = Np - t->ax.Nr;
1020 LOG (GNUNET_ERROR_TYPE_DEBUG,
1021 "Storing skipped keys [%u, %u)\n",
1024 if (MAX_KEY_GAP < gap)
1026 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1027 /* TODO: start new key exchange on return */
1028 GNUNET_break_op (0);
1029 LOG (GNUNET_ERROR_TYPE_WARNING,
1030 "Got message %u, expected %u+\n",
1033 return GNUNET_SYSERR;
1037 /* Delayed message: don't store keys, flag to try old keys. */
1038 return GNUNET_SYSERR;
1041 while (t->ax.Nr < Np)
1042 store_skipped_key (t,
1045 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1046 delete_skipped_key (t,
1047 t->ax.skipped_tail);
1053 * Decrypt and verify data with the appropriate tunnel key and verify that the
1054 * data has not been altered since it was sent by the remote peer.
1056 * @param t Tunnel whose key to use.
1057 * @param dst Destination for the plaintext.
1058 * @param src Source of the message. Can overlap with @c dst.
1059 * @param size Size of the message.
1060 * @return Size of the decrypted data, -1 if an error was encountered.
1063 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1065 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1068 struct CadetTunnelAxolotl *ax;
1069 struct GNUNET_ShortHashCode msg_hmac;
1070 struct GNUNET_HashCode hmac;
1071 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1074 size_t esize; /* Size of encryped payload */
1076 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1079 /* Try current HK */
1081 AX_HEADER_SIZE + esize,
1084 if (0 != memcmp (&msg_hmac,
1088 static const char ctx[] = "axolotl ratchet";
1089 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1090 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1091 struct GNUNET_HashCode dh;
1092 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1096 AX_HEADER_SIZE + esize,
1100 if (0 != memcmp (&msg_hmac,
1104 /* Try the skipped keys, if that fails, we're out of luck. */
1105 return try_old_ax_keys (t,
1115 Np = ntohl (plaintext_header.Ns);
1116 PNp = ntohl (plaintext_header.PNs);
1117 DHRp = &plaintext_header.DHRs;
1122 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1123 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1126 t_ax_hmac_hash (&ax->RK,
1129 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1131 &hmac, sizeof (hmac),
1134 /* Commit "purported" keys */
1140 ax->ratchet_allowed = GNUNET_YES;
1147 Np = ntohl (plaintext_header.Ns);
1148 PNp = ntohl (plaintext_header.PNs);
1150 if ( (Np != ax->Nr) &&
1151 (GNUNET_OK != store_ax_keys (t,
1155 /* Try the skipped keys, if that fails, we're out of luck. */
1156 return try_old_ax_keys (t,
1172 * Our tunnel became ready for the first time, notify channels
1173 * that have been waiting.
1175 * @param cls our tunnel, not used
1176 * @param key unique ID of the channel, not used
1177 * @param value the `struct CadetChannel` to notify
1178 * @return #GNUNET_OK (continue to iterate)
1181 notify_tunnel_up_cb (void *cls,
1185 struct CadetChannel *ch = value;
1187 GCCH_tunnel_up (ch);
1193 * Change the tunnel encryption state.
1194 * If the encryption state changes to OK, stop the rekey task.
1196 * @param t Tunnel whose encryption state to change, or NULL.
1197 * @param state New encryption state.
1200 GCT_change_estate (struct CadetTunnel *t,
1201 enum CadetTunnelEState state)
1203 enum CadetTunnelEState old = t->estate;
1206 LOG (GNUNET_ERROR_TYPE_DEBUG,
1207 "Tunnel %s estate changed from %d to %d\n",
1212 if ( (CADET_TUNNEL_KEY_OK != old) &&
1213 (CADET_TUNNEL_KEY_OK == t->estate) )
1215 if (NULL != t->kx_task)
1217 GNUNET_SCHEDULER_cancel (t->kx_task);
1220 if (CADET_TUNNEL_KEY_REKEY != old)
1222 /* notify all channels that have been waiting */
1223 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1224 ¬ify_tunnel_up_cb,
1228 /* FIXME: schedule rekey task! */
1234 * Send a KX message.
1236 * FIXME: does not take care of sender-authentication yet!
1238 * @param t Tunnel on which to send it.
1239 * @param force_reply Force the other peer to reply with a KX message.
1242 send_kx (struct CadetTunnel *t,
1245 struct CadetTunnelAxolotl *ax = &t->ax;
1246 struct CadetTConnection *ct;
1247 struct CadetConnection *cc;
1248 struct GNUNET_MQ_Envelope *env;
1249 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1250 enum GNUNET_CADET_KX_Flags flags;
1252 ct = get_ready_connection (t);
1255 LOG (GNUNET_ERROR_TYPE_DEBUG,
1256 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1261 LOG (GNUNET_ERROR_TYPE_DEBUG,
1262 "Sending KX on tunnel %s using connection %s\n",
1266 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1267 env = GNUNET_MQ_msg (msg,
1268 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1269 flags = GNUNET_CADET_KX_FLAG_NONE;
1270 if (GNUNET_YES == force_reply)
1271 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1272 msg->flags = htonl (flags);
1273 msg->cid = *GCC_get_id (cc);
1274 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1275 &msg->ephemeral_key);
1276 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1278 ct->is_ready = GNUNET_NO;
1281 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1282 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1283 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1284 GCT_change_estate (t,
1285 CADET_TUNNEL_KEY_SENT);
1290 * Handle KX message.
1292 * FIXME: sender-authentication in KX is missing!
1294 * @param ct connection/tunnel combo that received encrypted message
1295 * @param msg the key exchange message
1298 GCT_handle_kx (struct CadetTConnection *ct,
1299 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1301 struct CadetTunnel *t = ct->t;
1302 struct CadetTunnelAxolotl *ax = &t->ax;
1303 struct GNUNET_HashCode key_material[3];
1304 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1305 const char salt[] = "CADET Axolotl salt";
1306 const struct GNUNET_PeerIdentity *pid;
1309 pid = GCP_get_id (t->destination);
1310 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1312 am_I_alice = GNUNET_YES;
1313 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1315 am_I_alice = GNUNET_NO;
1318 GNUNET_break_op (0);
1322 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1324 if (NULL != t->kx_task)
1326 GNUNET_SCHEDULER_cancel (t->kx_task);
1333 if (0 == memcmp (&ax->DHRr,
1335 sizeof (msg->ratchet_key)))
1337 LOG (GNUNET_ERROR_TYPE_DEBUG,
1338 " known ratchet key, exit\n");
1342 ax->DHRr = msg->ratchet_key;
1345 if (GNUNET_YES == am_I_alice)
1347 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1348 &msg->ephemeral_key, /* B0 */
1353 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1354 &pid->public_key, /* A */
1359 if (GNUNET_YES == am_I_alice)
1361 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1362 &pid->public_key, /* B */
1367 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1368 &msg->ephemeral_key, /* B0 */
1375 /* (This is the triple-DH, we could probably safely skip this,
1376 as A0/B0 are already in the key material.) */
1377 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1378 &msg->ephemeral_key, /* B0 or A0 */
1382 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1383 salt, sizeof (salt),
1384 &key_material, sizeof (key_material),
1387 if (0 == memcmp (&ax->RK,
1391 LOG (GNUNET_ERROR_TYPE_INFO,
1392 " known handshake key, exit\n");
1395 LOG (GNUNET_ERROR_TYPE_DEBUG,
1396 "Handling KX message for tunnel %s\n",
1400 if (GNUNET_YES == am_I_alice)
1406 ax->ratchet_flag = GNUNET_YES;
1414 ax->ratchet_flag = GNUNET_NO;
1415 ax->ratchet_allowed = GNUNET_NO;
1416 ax->ratchet_counter = 0;
1417 ax->ratchet_expiration
1418 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1427 case CADET_TUNNEL_KEY_UNINITIALIZED:
1428 GCT_change_estate (t,
1429 CADET_TUNNEL_KEY_PING);
1431 case CADET_TUNNEL_KEY_SENT:
1432 /* Got a response to us sending our key; now
1433 we can start transmitting! */
1434 GCT_change_estate (t,
1435 CADET_TUNNEL_KEY_OK);
1436 if (NULL != t->send_task)
1437 GNUNET_SCHEDULER_cancel (t->send_task);
1438 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1441 case CADET_TUNNEL_KEY_PING:
1442 /* Got a key yet again; need encrypted payload to advance */
1444 case CADET_TUNNEL_KEY_OK:
1445 /* Did not expect a key, but so what. */
1447 case CADET_TUNNEL_KEY_REKEY:
1448 /* Got a key yet again; need encrypted payload to advance */
1454 /* ************************************** end core crypto ***************************** */
1458 * Compute the next free channel tunnel number for this tunnel.
1460 * @param t the tunnel
1461 * @return unused number that can uniquely identify a channel in the tunnel
1463 static struct GNUNET_CADET_ChannelTunnelNumber
1464 get_next_free_ctn (struct CadetTunnel *t)
1466 #define HIGH_BIT 0x8000000
1467 struct GNUNET_CADET_ChannelTunnelNumber ret;
1472 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1473 GCP_get_id (GCT_get_destination (t)));
1479 GNUNET_assert (0); // loopback must never go here!
1480 ctn = ntohl (t->next_ctn.cn);
1482 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1485 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1487 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
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 * We lost a connection, remove it from our list and clean up
1527 * the connection object itself.
1529 * @param ct binding of connection to tunnel of the connection that was lost.
1532 GCT_connection_lost (struct CadetTConnection *ct)
1534 struct CadetTunnel *t = ct->t;
1536 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1544 * This tunnel is no longer used, destroy it.
1546 * @param cls the idle tunnel
1549 destroy_tunnel (void *cls)
1551 struct CadetTunnel *t = cls;
1552 struct CadetTConnection *ct;
1553 struct CadetTunnelQueueEntry *tq;
1555 t->destroy_task = NULL;
1556 LOG (GNUNET_ERROR_TYPE_DEBUG,
1557 "Destroying idle tunnel %s\n",
1559 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1560 while (NULL != (ct = t->connection_head))
1562 struct CadetConnection *cc;
1564 GNUNET_assert (ct->t == t);
1566 GCT_connection_lost (ct);
1567 GCC_destroy_without_tunnel (cc);
1569 while (NULL != (tq = t->tq_head))
1571 if (NULL != tq->cont)
1572 tq->cont (tq->cont_cls);
1573 GCT_send_cancel (tq);
1575 GCP_drop_tunnel (t->destination,
1577 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1578 if (NULL != t->maintain_connections_task)
1580 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1581 t->maintain_connections_task = NULL;
1583 if (NULL != t->send_task)
1585 GNUNET_SCHEDULER_cancel (t->send_task);
1586 t->send_task = NULL;
1588 if (NULL != t->kx_task)
1590 GNUNET_SCHEDULER_cancel (t->kx_task);
1593 GNUNET_MST_destroy (t->mst);
1594 GNUNET_MQ_destroy (t->mq);
1595 while (NULL != t->ax.skipped_head)
1596 delete_skipped_key (t,
1597 t->ax.skipped_head);
1598 GNUNET_assert (0 == t->ax.skipped);
1599 GNUNET_free_non_null (t->ax.kx_0);
1600 GNUNET_free_non_null (t->ax.DHRs);
1606 * Remove a channel from a tunnel.
1610 * @param ctn unique number identifying @a ch within @a t
1613 GCT_remove_channel (struct CadetTunnel *t,
1614 struct CadetChannel *ch,
1615 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1617 LOG (GNUNET_ERROR_TYPE_DEBUG,
1618 "Removing channel %s from tunnel %s\n",
1621 GNUNET_assert (GNUNET_YES ==
1622 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1626 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1628 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1636 * Destroy remaining channels during shutdown.
1638 * @param cls the `struct CadetTunnel` of the channel
1639 * @param key key of the channel
1640 * @param value the `struct CadetChannel`
1641 * @return #GNUNET_OK (continue to iterate)
1644 destroy_remaining_channels (void *cls,
1648 struct CadetChannel *ch = value;
1650 GCCH_handle_remote_destroy (ch);
1656 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1658 * @param t tunnel to destroy
1661 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1663 GNUNET_assert (GNUNET_YES == shutting_down);
1664 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1665 &destroy_remaining_channels,
1668 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1669 if (NULL != t->destroy_task)
1671 GNUNET_SCHEDULER_cancel (t->destroy_task);
1672 t->destroy_task = NULL;
1679 * It's been a while, we should try to redo the KX, if we can.
1681 * @param cls the `struct CadetTunnel` to do KX for.
1684 retry_kx (void *cls)
1686 struct CadetTunnel *t = cls;
1690 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1691 (CADET_TUNNEL_KEY_SENT == t->estate) )
1698 * Send normal payload from queue in @a t via connection @a ct.
1699 * Does nothing if our payload queue is empty.
1701 * @param t tunnel to send data from
1702 * @param ct connection to use for transmission (is ready)
1705 try_send_normal_payload (struct CadetTunnel *t,
1706 struct CadetTConnection *ct)
1708 struct CadetTunnelQueueEntry *tq;
1710 GNUNET_assert (GNUNET_YES == ct->is_ready);
1714 /* no messages pending right now */
1715 LOG (GNUNET_ERROR_TYPE_DEBUG,
1716 "Not sending payload of %s on ready %s (nothing pending)\n",
1721 /* ready to send message 'tq' on tunnel 'ct' */
1722 GNUNET_assert (t == tq->t);
1723 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1726 if (NULL != tq->cid)
1727 *tq->cid = *GCC_get_id (ct->cc);
1728 ct->is_ready = GNUNET_NO;
1729 LOG (GNUNET_ERROR_TYPE_DEBUG,
1730 "Sending payload of %s on %s\n",
1733 GCC_transmit (ct->cc,
1735 if (NULL != tq->cont)
1736 tq->cont (tq->cont_cls);
1742 * A connection is @a is_ready for transmission. Looks at our message
1743 * queue and if there is a message, sends it out via the connection.
1745 * @param cls the `struct CadetTConnection` that is @a is_ready
1746 * @param is_ready #GNUNET_YES if connection are now ready,
1747 * #GNUNET_NO if connection are no longer ready
1750 connection_ready_cb (void *cls,
1753 struct CadetTConnection *ct = cls;
1754 struct CadetTunnel *t = ct->t;
1756 if (GNUNET_NO == is_ready)
1758 LOG (GNUNET_ERROR_TYPE_DEBUG,
1759 "Connection %s no longer ready for tunnel %s\n",
1762 ct->is_ready = GNUNET_NO;
1765 ct->is_ready = GNUNET_YES;
1766 LOG (GNUNET_ERROR_TYPE_DEBUG,
1767 "Connection %s now ready for tunnel %s in state %s\n",
1770 estate2s (t->estate));
1773 case CADET_TUNNEL_KEY_UNINITIALIZED:
1777 case CADET_TUNNEL_KEY_SENT:
1778 case CADET_TUNNEL_KEY_PING:
1779 /* opportunity to #retry_kx() starts now, schedule job */
1780 if (NULL == t->kx_task)
1783 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1788 case CADET_TUNNEL_KEY_OK:
1789 try_send_normal_payload (t,
1792 case CADET_TUNNEL_KEY_REKEY:
1795 t->estate = CADET_TUNNEL_KEY_OK;
1802 * Called when either we have a new connection, or a new message in the
1803 * queue, or some existing connection has transmission capacity. Looks
1804 * at our message queue and if there is a message, picks a connection
1807 * @param cls the `struct CadetTunnel` to process messages on
1810 trigger_transmissions (void *cls)
1812 struct CadetTunnel *t = cls;
1813 struct CadetTConnection *ct;
1815 t->send_task = NULL;
1816 if (NULL == t->tq_head)
1817 return; /* no messages pending right now */
1818 ct = get_ready_connection (t);
1820 return; /* no connections ready */
1821 try_send_normal_payload (t,
1827 * Consider using the path @a p for the tunnel @a t.
1828 * The tunnel destination is at offset @a off in path @a p.
1830 * @param cls our tunnel
1831 * @param path a path to our destination
1832 * @param off offset of the destination on path @a path
1833 * @return #GNUNET_YES (should keep iterating)
1836 consider_path_cb (void *cls,
1837 struct CadetPeerPath *path,
1840 struct CadetTunnel *t = cls;
1841 unsigned int min_length = UINT_MAX;
1842 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1843 struct CadetTConnection *ct;
1845 /* Check if we care about the new path. */
1846 for (ct = t->connection_head;
1850 struct CadetPeerPath *ps;
1852 ps = GCC_get_path (ct->cc);
1855 LOG (GNUNET_ERROR_TYPE_DEBUG,
1856 "Ignoring duplicate path %s for tunnel %s.\n",
1859 return GNUNET_YES; /* duplicate */
1861 min_length = GNUNET_MIN (min_length,
1862 GCPP_get_length (ps));
1863 max_desire = GNUNET_MAX (max_desire,
1864 GCPP_get_desirability (ps));
1867 /* FIXME: not sure we should really just count
1868 'num_connections' here, as they may all have
1869 consistently failed to connect. */
1871 /* We iterate by increasing path length; if we have enough paths and
1872 this one is more than twice as long than what we are currently
1873 using, then ignore all of these super-long ones! */
1874 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1875 (min_length * 2 < off) )
1877 LOG (GNUNET_ERROR_TYPE_DEBUG,
1878 "Ignoring paths of length %u, they are way too long.\n",
1882 /* If we have enough paths and this one looks no better, ignore it. */
1883 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1884 (min_length < GCPP_get_length (path)) &&
1885 (max_desire > GCPP_get_desirability (path)) )
1887 LOG (GNUNET_ERROR_TYPE_DEBUG,
1888 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1889 GCPP_get_length (path),
1890 (unsigned long long) GCPP_get_desirability (path),
1891 GCP_2s (t->destination));
1895 /* Path is interesting (better by some metric, or we don't have
1896 enough paths yet). */
1897 ct = GNUNET_new (struct CadetTConnection);
1898 ct->created = GNUNET_TIME_absolute_get ();
1900 ct->cc = GCC_create (t->destination,
1903 &connection_ready_cb,
1905 /* FIXME: schedule job to kill connection (and path?) if it takes
1906 too long to get ready! (And track performance data on how long
1907 other connections took with the tunnel!)
1908 => Note: to be done within 'connection'-logic! */
1909 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1912 t->num_connections++;
1913 LOG (GNUNET_ERROR_TYPE_DEBUG,
1914 "Found interesting path %s for tunnel %s, created connection %s\n",
1923 * Function called to maintain the connections underlying our tunnel.
1924 * Tries to maintain (incl. tear down) connections for the tunnel, and
1925 * if there is a significant change, may trigger transmissions.
1927 * Basically, needs to check if there are connections that perform
1928 * badly, and if so eventually kill them and trigger a replacement.
1929 * The strategy is to open one more connection than
1930 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1931 * least-performing one, and then inquire for new ones.
1933 * @param cls the `struct CadetTunnel`
1936 maintain_connections_cb (void *cls)
1938 struct CadetTunnel *t = cls;
1940 t->maintain_connections_task = NULL;
1941 LOG (GNUNET_ERROR_TYPE_DEBUG,
1942 "Performing connection maintenance for tunnel %s.\n",
1945 (void) GCP_iterate_paths (t->destination,
1949 GNUNET_break (0); // FIXME: implement!
1954 * Consider using the path @a p for the tunnel @a t.
1955 * The tunnel destination is at offset @a off in path @a p.
1957 * @param cls our tunnel
1958 * @param path a path to our destination
1959 * @param off offset of the destination on path @a path
1962 GCT_consider_path (struct CadetTunnel *t,
1963 struct CadetPeerPath *p,
1966 (void) consider_path_cb (t,
1973 * We got a keepalive. Track in statistics.
1975 * @param cls the `struct CadetTunnel` for which we decrypted the message
1976 * @param msg the message we received on the tunnel
1979 handle_plaintext_keepalive (void *cls,
1980 const struct GNUNET_MessageHeader *msg)
1982 struct CadetTunnel *t = cls;
1984 LOG (GNUNET_ERROR_TYPE_DEBUG,
1985 "Received KEEPALIVE on tunnel %s\n",
1987 GNUNET_STATISTICS_update (stats,
1988 "# keepalives received",
1995 * Check that @a msg is well-formed.
1997 * @param cls the `struct CadetTunnel` for which we decrypted the message
1998 * @param msg the message we received on the tunnel
1999 * @return #GNUNET_OK (any variable-size payload goes)
2002 check_plaintext_data (void *cls,
2003 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2010 * We received payload data for a channel. Locate the channel
2011 * and process the data, or return an error if the channel is unknown.
2013 * @param cls the `struct CadetTunnel` for which we decrypted the message
2014 * @param msg the message we received on the tunnel
2017 handle_plaintext_data (void *cls,
2018 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2020 struct CadetTunnel *t = cls;
2021 struct CadetChannel *ch;
2023 ch = lookup_channel (t,
2027 /* We don't know about such a channel, might have been destroyed on our
2028 end in the meantime, or never existed. Send back a DESTROY. */
2029 LOG (GNUNET_ERROR_TYPE_DEBUG,
2030 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2031 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2032 ntohl (msg->ctn.cn));
2033 GCT_send_channel_destroy (t,
2037 GCCH_handle_channel_plaintext_data (ch,
2043 * We received an acknowledgement for data we sent on a channel.
2044 * Locate the channel and process it, or return an error if the
2045 * channel is unknown.
2047 * @param cls the `struct CadetTunnel` for which we decrypted the message
2048 * @param ack the message we received on the tunnel
2051 handle_plaintext_data_ack (void *cls,
2052 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2054 struct CadetTunnel *t = cls;
2055 struct CadetChannel *ch;
2057 ch = lookup_channel (t,
2061 /* We don't know about such a channel, might have been destroyed on our
2062 end in the meantime, or never existed. Send back a DESTROY. */
2063 LOG (GNUNET_ERROR_TYPE_DEBUG,
2064 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2065 ntohl (ack->ctn.cn));
2066 GCT_send_channel_destroy (t,
2070 GCCH_handle_channel_plaintext_data_ack (ch,
2076 * We have received a request to open a channel to a port from
2077 * another peer. Creates the incoming channel.
2079 * @param cls the `struct CadetTunnel` for which we decrypted the message
2080 * @param copen the message we received on the tunnel
2083 handle_plaintext_channel_open (void *cls,
2084 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2086 struct CadetTunnel *t = cls;
2087 struct CadetChannel *ch;
2089 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2090 ntohl (copen->ctn.cn));
2093 LOG (GNUNET_ERROR_TYPE_DEBUG,
2094 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2095 GNUNET_h2s (&copen->port),
2098 GCCH_handle_duplicate_open (ch);
2101 LOG (GNUNET_ERROR_TYPE_DEBUG,
2102 "Receicved channel OPEN on port %s from %s\n",
2103 GNUNET_h2s (&copen->port),
2105 ch = GCCH_channel_incoming_new (t,
2108 ntohl (copen->opt));
2109 GNUNET_assert (GNUNET_OK ==
2110 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2111 ntohl (copen->ctn.cn),
2113 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2118 * Send a DESTROY message via the tunnel.
2120 * @param t the tunnel to transmit over
2121 * @param ctn ID of the channel to destroy
2124 GCT_send_channel_destroy (struct CadetTunnel *t,
2125 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2127 struct GNUNET_CADET_ChannelManageMessage msg;
2129 LOG (GNUNET_ERROR_TYPE_DEBUG,
2130 "Sending DESTORY message for channel ID %u\n",
2132 msg.header.size = htons (sizeof (msg));
2133 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2134 msg.reserved = htonl (0);
2144 * We have received confirmation from the target peer that the
2145 * given channel could be established (the port is open).
2148 * @param cls the `struct CadetTunnel` for which we decrypted the message
2149 * @param cm the message we received on the tunnel
2152 handle_plaintext_channel_open_ack (void *cls,
2153 const struct GNUNET_CADET_ChannelManageMessage *cm)
2155 struct CadetTunnel *t = cls;
2156 struct CadetChannel *ch;
2158 ch = lookup_channel (t,
2162 /* We don't know about such a channel, might have been destroyed on our
2163 end in the meantime, or never existed. Send back a DESTROY. */
2164 LOG (GNUNET_ERROR_TYPE_DEBUG,
2165 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2166 ntohl (cm->ctn.cn));
2167 GCT_send_channel_destroy (t,
2171 LOG (GNUNET_ERROR_TYPE_DEBUG,
2172 "Received channel OPEN_ACK on channel %s from %s\n",
2175 GCCH_handle_channel_open_ack (ch);
2180 * We received a message saying that a channel should be destroyed.
2181 * Pass it on to the correct channel.
2183 * @param cls the `struct CadetTunnel` for which we decrypted the message
2184 * @param cm the message we received on the tunnel
2187 handle_plaintext_channel_destroy (void *cls,
2188 const struct GNUNET_CADET_ChannelManageMessage *cm)
2190 struct CadetTunnel *t = cls;
2191 struct CadetChannel *ch;
2193 ch = lookup_channel (t,
2197 /* We don't know about such a channel, might have been destroyed on our
2198 end in the meantime, or never existed. */
2199 LOG (GNUNET_ERROR_TYPE_DEBUG,
2200 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2201 ntohl (cm->ctn.cn));
2204 LOG (GNUNET_ERROR_TYPE_DEBUG,
2205 "Receicved channel DESTROY on %s from %s\n",
2208 GCCH_handle_remote_destroy (ch);
2213 * Handles a message we decrypted, by injecting it into
2214 * our message queue (which will do the dispatching).
2216 * @param cls the `struct CadetTunnel` that got the message
2217 * @param msg the message
2218 * @return #GNUNET_OK (continue to process)
2221 handle_decrypted (void *cls,
2222 const struct GNUNET_MessageHeader *msg)
2224 struct CadetTunnel *t = cls;
2226 GNUNET_MQ_inject_message (t->mq,
2233 * Function called if we had an error processing
2234 * an incoming decrypted message.
2236 * @param cls the `struct CadetTunnel`
2237 * @param error error code
2240 decrypted_error_cb (void *cls,
2241 enum GNUNET_MQ_Error error)
2243 GNUNET_break_op (0);
2248 * Create a tunnel to @a destionation. Must only be called
2249 * from within #GCP_get_tunnel().
2251 * @param destination where to create the tunnel to
2252 * @return new tunnel to @a destination
2254 struct CadetTunnel *
2255 GCT_create_tunnel (struct CadetPeer *destination)
2257 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2258 struct GNUNET_MQ_MessageHandler handlers[] = {
2259 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2260 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2261 struct GNUNET_MessageHeader,
2263 GNUNET_MQ_hd_var_size (plaintext_data,
2264 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2265 struct GNUNET_CADET_ChannelAppDataMessage,
2267 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2268 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2269 struct GNUNET_CADET_ChannelDataAckMessage,
2271 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2272 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2273 struct GNUNET_CADET_ChannelOpenMessage,
2275 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2276 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2277 struct GNUNET_CADET_ChannelManageMessage,
2279 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2280 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2281 struct GNUNET_CADET_ChannelManageMessage,
2283 GNUNET_MQ_handler_end ()
2287 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2288 t->destination = destination;
2289 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2290 t->maintain_connections_task
2291 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2293 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2298 &decrypted_error_cb,
2300 t->mst = GNUNET_MST_create (&handle_decrypted,
2307 * Add a @a connection to the @a tunnel.
2310 * @param cid connection identifer to use for the connection
2311 * @param path path to use for the connection
2312 * @return #GNUNET_OK on success,
2313 * #GNUNET_SYSERR on failure (duplicate connection)
2316 GCT_add_inbound_connection (struct CadetTunnel *t,
2317 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2318 struct CadetPeerPath *path)
2320 struct CadetTConnection *ct;
2322 ct = GNUNET_new (struct CadetTConnection);
2323 ct->created = GNUNET_TIME_absolute_get ();
2325 ct->cc = GCC_create_inbound (t->destination,
2329 &connection_ready_cb,
2333 LOG (GNUNET_ERROR_TYPE_DEBUG,
2334 "Tunnel %s refused inbound connection %s (duplicate)\n",
2338 return GNUNET_SYSERR;
2340 /* FIXME: schedule job to kill connection (and path?) if it takes
2341 too long to get ready! (And track performance data on how long
2342 other connections took with the tunnel!)
2343 => Note: to be done within 'connection'-logic! */
2344 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2347 t->num_connections++;
2348 LOG (GNUNET_ERROR_TYPE_DEBUG,
2349 "Tunnel %s has new connection %s\n",
2357 * Handle encrypted message.
2359 * @param ct connection/tunnel combo that received encrypted message
2360 * @param msg the encrypted message to decrypt
2363 GCT_handle_encrypted (struct CadetTConnection *ct,
2364 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2366 struct CadetTunnel *t = ct->t;
2367 uint16_t size = ntohs (msg->header.size);
2368 char cbuf [size] GNUNET_ALIGN;
2369 ssize_t decrypted_size;
2371 LOG (GNUNET_ERROR_TYPE_DEBUG,
2372 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2374 (unsigned int) size,
2379 case CADET_TUNNEL_KEY_UNINITIALIZED:
2380 /* We did not even SEND our KX, how can the other peer
2381 send us encrypted data? */
2382 GNUNET_break_op (0);
2384 case CADET_TUNNEL_KEY_SENT:
2385 /* We did not get the KX of the other peer, but that
2386 might have been lost. Ask for KX again. */
2387 GNUNET_STATISTICS_update (stats,
2388 "# received encrypted without KX",
2391 if (NULL != t->kx_task)
2392 GNUNET_SCHEDULER_cancel (t->kx_task);
2393 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2396 case CADET_TUNNEL_KEY_PING:
2397 /* Great, first payload, we might graduate to OK */
2398 case CADET_TUNNEL_KEY_OK:
2399 case CADET_TUNNEL_KEY_REKEY:
2403 GNUNET_STATISTICS_update (stats,
2404 "# received encrypted",
2407 decrypted_size = t_ax_decrypt_and_validate (t,
2412 if (-1 == decrypted_size)
2414 GNUNET_break_op (0);
2415 LOG (GNUNET_ERROR_TYPE_WARNING,
2416 "Tunnel %s failed to decrypt and validate encrypted data\n",
2418 GNUNET_STATISTICS_update (stats,
2419 "# unable to decrypt",
2424 if (CADET_TUNNEL_KEY_PING == t->estate)
2426 GCT_change_estate (t,
2427 CADET_TUNNEL_KEY_OK);
2428 if (NULL != t->send_task)
2429 GNUNET_SCHEDULER_cancel (t->send_task);
2430 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2433 /* The MST will ultimately call #handle_decrypted() on each message. */
2434 GNUNET_break_op (GNUNET_OK ==
2435 GNUNET_MST_from_buffer (t->mst,
2444 * Sends an already built message on a tunnel, encrypting it and
2445 * choosing the best connection if not provided.
2447 * @param message Message to send. Function modifies it.
2448 * @param t Tunnel on which this message is transmitted.
2449 * @param cont Continuation to call once message is really sent.
2450 * @param cont_cls Closure for @c cont.
2451 * @return Handle to cancel message. NULL if @c cont is NULL.
2453 struct CadetTunnelQueueEntry *
2454 GCT_send (struct CadetTunnel *t,
2455 const struct GNUNET_MessageHeader *message,
2456 GNUNET_SCHEDULER_TaskCallback cont,
2459 struct CadetTunnelQueueEntry *tq;
2460 uint16_t payload_size;
2461 struct GNUNET_MQ_Envelope *env;
2462 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2464 payload_size = ntohs (message->size);
2465 LOG (GNUNET_ERROR_TYPE_DEBUG,
2466 "Encrypting %u bytes for tunnel %s\n",
2467 (unsigned int) payload_size,
2469 env = GNUNET_MQ_msg_extra (ax_msg,
2471 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2476 ax_msg->Ns = htonl (t->ax.Ns++);
2477 ax_msg->PNs = htonl (t->ax.PNs);
2478 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2482 t_hmac (&ax_msg->Ns,
2483 AX_HEADER_SIZE + payload_size,
2488 tq = GNUNET_malloc (sizeof (*tq));
2491 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2493 tq->cont_cls = cont_cls;
2494 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2497 if (NULL != t->send_task)
2498 GNUNET_SCHEDULER_cancel (t->send_task);
2500 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2507 * Cancel a previously sent message while it's in the queue.
2509 * ONLY can be called before the continuation given to the send
2510 * function is called. Once the continuation is called, the message is
2511 * no longer in the queue!
2513 * @param tq Handle to the queue entry to cancel.
2516 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2518 struct CadetTunnel *t = tq->t;
2520 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2523 GNUNET_MQ_discard (tq->env);
2529 * Iterate over all connections of a tunnel.
2531 * @param t Tunnel whose connections to iterate.
2532 * @param iter Iterator.
2533 * @param iter_cls Closure for @c iter.
2536 GCT_iterate_connections (struct CadetTunnel *t,
2537 GCT_ConnectionIterator iter,
2540 for (struct CadetTConnection *ct = t->connection_head;
2549 * Closure for #iterate_channels_cb.
2556 GCT_ChannelIterator iter;
2559 * Closure for @e iter.
2566 * Helper function for #GCT_iterate_channels.
2568 * @param cls the `struct ChanIterCls`
2570 * @param value a `struct CadetChannel`
2571 * @return #GNUNET_OK
2574 iterate_channels_cb (void *cls,
2578 struct ChanIterCls *ctx = cls;
2579 struct CadetChannel *ch = value;
2581 ctx->iter (ctx->iter_cls,
2588 * Iterate over all channels of a tunnel.
2590 * @param t Tunnel whose channels to iterate.
2591 * @param iter Iterator.
2592 * @param iter_cls Closure for @c iter.
2595 GCT_iterate_channels (struct CadetTunnel *t,
2596 GCT_ChannelIterator iter,
2599 struct ChanIterCls ctx;
2602 ctx.iter_cls = iter_cls;
2603 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2604 &iterate_channels_cb,
2611 * Call #GCCH_debug() on a channel.
2613 * @param cls points to the log level to use
2615 * @param value the `struct CadetChannel` to dump
2616 * @return #GNUNET_OK (continue iteration)
2619 debug_channel (void *cls,
2623 const enum GNUNET_ErrorType *level = cls;
2624 struct CadetChannel *ch = value;
2626 GCCH_debug (ch, *level);
2631 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2635 * Log all possible info about the tunnel state.
2637 * @param t Tunnel to debug.
2638 * @param level Debug level to use.
2641 GCT_debug (const struct CadetTunnel *t,
2642 enum GNUNET_ErrorType level)
2644 struct CadetTConnection *iter_c;
2647 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2649 __FILE__, __FUNCTION__, __LINE__);
2654 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2656 estate2s (t->estate),
2658 t->num_connections);
2659 #if DUMP_KEYS_TO_STDERR
2660 ax_debug (t->ax, level);
2664 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2668 "TTT connections:\n");
2669 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2670 GCC_debug (iter_c->cc,
2674 "TTT TUNNEL END\n");
2678 /* end of gnunet-service-cadet-new_tunnels.c */