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 * This tunnel is no longer used, destroy it.
1528 * @param cls the idle tunnel
1531 destroy_tunnel (void *cls)
1533 struct CadetTunnel *t = cls;
1534 struct CadetTConnection *ct;
1535 struct CadetTunnelQueueEntry *tq;
1537 t->destroy_task = NULL;
1538 LOG (GNUNET_ERROR_TYPE_DEBUG,
1539 "Destroying idle tunnel %s\n",
1541 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1542 while (NULL != (ct = t->connection_head))
1544 GNUNET_assert (ct->t == t);
1545 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1548 GCC_destroy (ct->cc);
1551 while (NULL != (tq = t->tq_head))
1553 if (NULL != tq->cont)
1554 tq->cont (tq->cont_cls);
1555 GCT_send_cancel (tq);
1557 GCP_drop_tunnel (t->destination,
1559 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1560 if (NULL != t->maintain_connections_task)
1562 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1563 t->maintain_connections_task = NULL;
1565 if (NULL != t->send_task)
1567 GNUNET_SCHEDULER_cancel (t->send_task);
1568 t->send_task = NULL;
1570 if (NULL != t->kx_task)
1572 GNUNET_SCHEDULER_cancel (t->kx_task);
1575 GNUNET_MST_destroy (t->mst);
1576 GNUNET_MQ_destroy (t->mq);
1577 while (NULL != t->ax.skipped_head)
1578 delete_skipped_key (t,
1579 t->ax.skipped_head);
1580 GNUNET_assert (0 == t->ax.skipped);
1581 GNUNET_free_non_null (t->ax.kx_0);
1582 GNUNET_free_non_null (t->ax.DHRs);
1588 * Remove a channel from a tunnel.
1592 * @param ctn unique number identifying @a ch within @a t
1595 GCT_remove_channel (struct CadetTunnel *t,
1596 struct CadetChannel *ch,
1597 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1599 LOG (GNUNET_ERROR_TYPE_DEBUG,
1600 "Removing channel %s from tunnel %s\n",
1603 GNUNET_assert (GNUNET_YES ==
1604 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1608 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1610 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1618 * Destroy remaining channels during shutdown.
1620 * @param cls the `struct CadetTunnel` of the channel
1621 * @param key key of the channel
1622 * @param value the `struct CadetChannel`
1623 * @return #GNUNET_OK (continue to iterate)
1626 destroy_remaining_channels (void *cls,
1630 struct CadetChannel *ch = value;
1632 GCCH_handle_remote_destroy (ch);
1638 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1640 * @param t tunnel to destroy
1643 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1645 GNUNET_assert (GNUNET_YES == shutting_down);
1646 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1647 &destroy_remaining_channels,
1650 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1651 if (NULL != t->destroy_task)
1653 GNUNET_SCHEDULER_cancel (t->destroy_task);
1654 t->destroy_task = NULL;
1661 * It's been a while, we should try to redo the KX, if we can.
1663 * @param cls the `struct CadetTunnel` to do KX for.
1666 retry_kx (void *cls)
1668 struct CadetTunnel *t = cls;
1672 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1673 (CADET_TUNNEL_KEY_SENT == t->estate) )
1680 * Send normal payload from queue in @a t via connection @a ct.
1681 * Does nothing if our payload queue is empty.
1683 * @param t tunnel to send data from
1684 * @param ct connection to use for transmission (is ready)
1687 try_send_normal_payload (struct CadetTunnel *t,
1688 struct CadetTConnection *ct)
1690 struct CadetTunnelQueueEntry *tq;
1692 GNUNET_assert (GNUNET_YES == ct->is_ready);
1696 /* no messages pending right now */
1697 LOG (GNUNET_ERROR_TYPE_DEBUG,
1698 "Not sending payload of %s on ready %s (nothing pending)\n",
1703 /* ready to send message 'tq' on tunnel 'ct' */
1704 GNUNET_assert (t == tq->t);
1705 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1708 if (NULL != tq->cid)
1709 *tq->cid = *GCC_get_id (ct->cc);
1710 ct->is_ready = GNUNET_NO;
1711 LOG (GNUNET_ERROR_TYPE_DEBUG,
1712 "Sending payload of %s on %s\n",
1715 GCC_transmit (ct->cc,
1717 if (NULL != tq->cont)
1718 tq->cont (tq->cont_cls);
1724 * A connection is @a is_ready for transmission. Looks at our message
1725 * queue and if there is a message, sends it out via the connection.
1727 * @param cls the `struct CadetTConnection` that is @a is_ready
1728 * @param is_ready #GNUNET_YES if connection are now ready,
1729 * #GNUNET_NO if connection are no longer ready
1732 connection_ready_cb (void *cls,
1735 struct CadetTConnection *ct = cls;
1736 struct CadetTunnel *t = ct->t;
1738 if (GNUNET_NO == is_ready)
1740 LOG (GNUNET_ERROR_TYPE_DEBUG,
1741 "Connection %s no longer ready for tunnel %s\n",
1744 ct->is_ready = GNUNET_NO;
1747 ct->is_ready = GNUNET_YES;
1748 LOG (GNUNET_ERROR_TYPE_DEBUG,
1749 "Connection %s now ready for tunnel %s in state %s\n",
1752 estate2s (t->estate));
1755 case CADET_TUNNEL_KEY_UNINITIALIZED:
1759 case CADET_TUNNEL_KEY_SENT:
1760 case CADET_TUNNEL_KEY_PING:
1761 /* opportunity to #retry_kx() starts now, schedule job */
1762 if (NULL == t->kx_task)
1765 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1770 case CADET_TUNNEL_KEY_OK:
1771 try_send_normal_payload (t,
1774 case CADET_TUNNEL_KEY_REKEY:
1777 t->estate = CADET_TUNNEL_KEY_OK;
1784 * Called when either we have a new connection, or a new message in the
1785 * queue, or some existing connection has transmission capacity. Looks
1786 * at our message queue and if there is a message, picks a connection
1789 * @param cls the `struct CadetTunnel` to process messages on
1792 trigger_transmissions (void *cls)
1794 struct CadetTunnel *t = cls;
1795 struct CadetTConnection *ct;
1797 t->send_task = NULL;
1798 if (NULL == t->tq_head)
1799 return; /* no messages pending right now */
1800 ct = get_ready_connection (t);
1802 return; /* no connections ready */
1803 try_send_normal_payload (t,
1809 * Consider using the path @a p for the tunnel @a t.
1810 * The tunnel destination is at offset @a off in path @a p.
1812 * @param cls our tunnel
1813 * @param path a path to our destination
1814 * @param off offset of the destination on path @a path
1815 * @return #GNUNET_YES (should keep iterating)
1818 consider_path_cb (void *cls,
1819 struct CadetPeerPath *path,
1822 struct CadetTunnel *t = cls;
1823 unsigned int min_length = UINT_MAX;
1824 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1825 struct CadetTConnection *ct;
1827 /* Check if we care about the new path. */
1828 for (ct = t->connection_head;
1832 struct CadetPeerPath *ps;
1834 ps = GCC_get_path (ct->cc);
1837 LOG (GNUNET_ERROR_TYPE_DEBUG,
1838 "Ignoring duplicate path %s for tunnel %s.\n",
1841 return GNUNET_YES; /* duplicate */
1843 min_length = GNUNET_MIN (min_length,
1844 GCPP_get_length (ps));
1845 max_desire = GNUNET_MAX (max_desire,
1846 GCPP_get_desirability (ps));
1849 /* FIXME: not sure we should really just count
1850 'num_connections' here, as they may all have
1851 consistently failed to connect. */
1853 /* We iterate by increasing path length; if we have enough paths and
1854 this one is more than twice as long than what we are currently
1855 using, then ignore all of these super-long ones! */
1856 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1857 (min_length * 2 < off) )
1859 LOG (GNUNET_ERROR_TYPE_DEBUG,
1860 "Ignoring paths of length %u, they are way too long.\n",
1864 /* If we have enough paths and this one looks no better, ignore it. */
1865 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1866 (min_length < GCPP_get_length (path)) &&
1867 (max_desire > GCPP_get_desirability (path)) )
1869 LOG (GNUNET_ERROR_TYPE_DEBUG,
1870 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1871 GCPP_get_length (path),
1872 (unsigned long long) GCPP_get_desirability (path),
1873 GCP_2s (t->destination));
1877 /* Path is interesting (better by some metric, or we don't have
1878 enough paths yet). */
1879 ct = GNUNET_new (struct CadetTConnection);
1880 ct->created = GNUNET_TIME_absolute_get ();
1882 ct->cc = GCC_create (t->destination,
1885 &connection_ready_cb,
1887 /* FIXME: schedule job to kill connection (and path?) if it takes
1888 too long to get ready! (And track performance data on how long
1889 other connections took with the tunnel!)
1890 => Note: to be done within 'connection'-logic! */
1891 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1894 t->num_connections++;
1895 LOG (GNUNET_ERROR_TYPE_DEBUG,
1896 "Found interesting path %s for tunnel %s, created connection %s\n",
1905 * Function called to maintain the connections underlying our tunnel.
1906 * Tries to maintain (incl. tear down) connections for the tunnel, and
1907 * if there is a significant change, may trigger transmissions.
1909 * Basically, needs to check if there are connections that perform
1910 * badly, and if so eventually kill them and trigger a replacement.
1911 * The strategy is to open one more connection than
1912 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1913 * least-performing one, and then inquire for new ones.
1915 * @param cls the `struct CadetTunnel`
1918 maintain_connections_cb (void *cls)
1920 struct CadetTunnel *t = cls;
1922 t->maintain_connections_task = NULL;
1923 LOG (GNUNET_ERROR_TYPE_DEBUG,
1924 "Performing connection maintenance for tunnel %s.\n",
1927 (void) GCP_iterate_paths (t->destination,
1931 GNUNET_break (0); // FIXME: implement!
1936 * Consider using the path @a p for the tunnel @a t.
1937 * The tunnel destination is at offset @a off in path @a p.
1939 * @param cls our tunnel
1940 * @param path a path to our destination
1941 * @param off offset of the destination on path @a path
1944 GCT_consider_path (struct CadetTunnel *t,
1945 struct CadetPeerPath *p,
1948 (void) consider_path_cb (t,
1955 * We got a keepalive. Track in statistics.
1957 * @param cls the `struct CadetTunnel` for which we decrypted the message
1958 * @param msg the message we received on the tunnel
1961 handle_plaintext_keepalive (void *cls,
1962 const struct GNUNET_MessageHeader *msg)
1964 struct CadetTunnel *t = cls;
1966 LOG (GNUNET_ERROR_TYPE_DEBUG,
1967 "Received KEEPALIVE on tunnel %s\n",
1969 GNUNET_STATISTICS_update (stats,
1970 "# keepalives received",
1977 * Check that @a msg is well-formed.
1979 * @param cls the `struct CadetTunnel` for which we decrypted the message
1980 * @param msg the message we received on the tunnel
1981 * @return #GNUNET_OK (any variable-size payload goes)
1984 check_plaintext_data (void *cls,
1985 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1992 * We received payload data for a channel. Locate the channel
1993 * and process the data, or return an error if the channel is unknown.
1995 * @param cls the `struct CadetTunnel` for which we decrypted the message
1996 * @param msg the message we received on the tunnel
1999 handle_plaintext_data (void *cls,
2000 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2002 struct CadetTunnel *t = cls;
2003 struct CadetChannel *ch;
2005 ch = lookup_channel (t,
2009 /* We don't know about such a channel, might have been destroyed on our
2010 end in the meantime, or never existed. Send back a DESTROY. */
2011 LOG (GNUNET_ERROR_TYPE_DEBUG,
2012 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2013 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2014 ntohl (msg->ctn.cn));
2015 GCT_send_channel_destroy (t,
2019 GCCH_handle_channel_plaintext_data (ch,
2025 * We received an acknowledgement for data we sent on a channel.
2026 * Locate the channel and process it, or return an error if the
2027 * channel is unknown.
2029 * @param cls the `struct CadetTunnel` for which we decrypted the message
2030 * @param ack the message we received on the tunnel
2033 handle_plaintext_data_ack (void *cls,
2034 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2036 struct CadetTunnel *t = cls;
2037 struct CadetChannel *ch;
2039 ch = lookup_channel (t,
2043 /* We don't know about such a channel, might have been destroyed on our
2044 end in the meantime, or never existed. Send back a DESTROY. */
2045 LOG (GNUNET_ERROR_TYPE_DEBUG,
2046 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2047 ntohl (ack->ctn.cn));
2048 GCT_send_channel_destroy (t,
2052 GCCH_handle_channel_plaintext_data_ack (ch,
2058 * We have received a request to open a channel to a port from
2059 * another peer. Creates the incoming channel.
2061 * @param cls the `struct CadetTunnel` for which we decrypted the message
2062 * @param copen the message we received on the tunnel
2065 handle_plaintext_channel_open (void *cls,
2066 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2068 struct CadetTunnel *t = cls;
2069 struct CadetChannel *ch;
2071 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2072 ntohl (copen->ctn.cn));
2075 LOG (GNUNET_ERROR_TYPE_DEBUG,
2076 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2077 GNUNET_h2s (&copen->port),
2080 GCCH_handle_duplicate_open (ch);
2083 LOG (GNUNET_ERROR_TYPE_DEBUG,
2084 "Receicved channel OPEN on port %s from %s\n",
2085 GNUNET_h2s (&copen->port),
2087 ch = GCCH_channel_incoming_new (t,
2090 ntohl (copen->opt));
2091 GNUNET_assert (GNUNET_OK ==
2092 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2093 ntohl (copen->ctn.cn),
2095 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2100 * Send a DESTROY message via the tunnel.
2102 * @param t the tunnel to transmit over
2103 * @param ctn ID of the channel to destroy
2106 GCT_send_channel_destroy (struct CadetTunnel *t,
2107 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2109 struct GNUNET_CADET_ChannelManageMessage msg;
2111 LOG (GNUNET_ERROR_TYPE_DEBUG,
2112 "Sending DESTORY message for channel ID %u\n",
2114 msg.header.size = htons (sizeof (msg));
2115 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2116 msg.reserved = htonl (0);
2126 * We have received confirmation from the target peer that the
2127 * given channel could be established (the port is open).
2130 * @param cls the `struct CadetTunnel` for which we decrypted the message
2131 * @param cm the message we received on the tunnel
2134 handle_plaintext_channel_open_ack (void *cls,
2135 const struct GNUNET_CADET_ChannelManageMessage *cm)
2137 struct CadetTunnel *t = cls;
2138 struct CadetChannel *ch;
2140 ch = lookup_channel (t,
2144 /* We don't know about such a channel, might have been destroyed on our
2145 end in the meantime, or never existed. Send back a DESTROY. */
2146 LOG (GNUNET_ERROR_TYPE_DEBUG,
2147 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2148 ntohl (cm->ctn.cn));
2149 GCT_send_channel_destroy (t,
2153 LOG (GNUNET_ERROR_TYPE_DEBUG,
2154 "Received channel OPEN_ACK on channel %s from %s\n",
2157 GCCH_handle_channel_open_ack (ch);
2162 * We received a message saying that a channel should be destroyed.
2163 * Pass it on to the correct channel.
2165 * @param cls the `struct CadetTunnel` for which we decrypted the message
2166 * @param cm the message we received on the tunnel
2169 handle_plaintext_channel_destroy (void *cls,
2170 const struct GNUNET_CADET_ChannelManageMessage *cm)
2172 struct CadetTunnel *t = cls;
2173 struct CadetChannel *ch;
2175 ch = lookup_channel (t,
2179 /* We don't know about such a channel, might have been destroyed on our
2180 end in the meantime, or never existed. */
2181 LOG (GNUNET_ERROR_TYPE_DEBUG,
2182 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2183 ntohl (cm->ctn.cn));
2186 LOG (GNUNET_ERROR_TYPE_DEBUG,
2187 "Receicved channel DESTROY on %s from %s\n",
2190 GCCH_handle_remote_destroy (ch);
2195 * Handles a message we decrypted, by injecting it into
2196 * our message queue (which will do the dispatching).
2198 * @param cls the `struct CadetTunnel` that got the message
2199 * @param msg the message
2200 * @return #GNUNET_OK (continue to process)
2203 handle_decrypted (void *cls,
2204 const struct GNUNET_MessageHeader *msg)
2206 struct CadetTunnel *t = cls;
2208 GNUNET_MQ_inject_message (t->mq,
2215 * Function called if we had an error processing
2216 * an incoming decrypted message.
2218 * @param cls the `struct CadetTunnel`
2219 * @param error error code
2222 decrypted_error_cb (void *cls,
2223 enum GNUNET_MQ_Error error)
2225 GNUNET_break_op (0);
2230 * Create a tunnel to @a destionation. Must only be called
2231 * from within #GCP_get_tunnel().
2233 * @param destination where to create the tunnel to
2234 * @return new tunnel to @a destination
2236 struct CadetTunnel *
2237 GCT_create_tunnel (struct CadetPeer *destination)
2239 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2240 struct GNUNET_MQ_MessageHandler handlers[] = {
2241 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2242 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2243 struct GNUNET_MessageHeader,
2245 GNUNET_MQ_hd_var_size (plaintext_data,
2246 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2247 struct GNUNET_CADET_ChannelAppDataMessage,
2249 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2250 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2251 struct GNUNET_CADET_ChannelDataAckMessage,
2253 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2254 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2255 struct GNUNET_CADET_ChannelOpenMessage,
2257 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2258 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2259 struct GNUNET_CADET_ChannelManageMessage,
2261 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2262 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2263 struct GNUNET_CADET_ChannelManageMessage,
2265 GNUNET_MQ_handler_end ()
2269 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2270 t->destination = destination;
2271 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2272 t->maintain_connections_task
2273 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2275 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2280 &decrypted_error_cb,
2282 t->mst = GNUNET_MST_create (&handle_decrypted,
2289 * Add a @a connection to the @a tunnel.
2292 * @param cid connection identifer to use for the connection
2293 * @param path path to use for the connection
2296 GCT_add_inbound_connection (struct CadetTunnel *t,
2297 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2298 struct CadetPeerPath *path)
2300 struct CadetTConnection *ct;
2302 ct = GNUNET_new (struct CadetTConnection);
2303 ct->created = GNUNET_TIME_absolute_get ();
2305 ct->cc = GCC_create_inbound (t->destination,
2309 &connection_ready_cb,
2311 /* FIXME: schedule job to kill connection (and path?) if it takes
2312 too long to get ready! (And track performance data on how long
2313 other connections took with the tunnel!)
2314 => Note: to be done within 'connection'-logic! */
2315 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2318 t->num_connections++;
2319 LOG (GNUNET_ERROR_TYPE_DEBUG,
2320 "Tunnel %s has new connection %s\n",
2327 * Handle encrypted message.
2329 * @param ct connection/tunnel combo that received encrypted message
2330 * @param msg the encrypted message to decrypt
2333 GCT_handle_encrypted (struct CadetTConnection *ct,
2334 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2336 struct CadetTunnel *t = ct->t;
2337 uint16_t size = ntohs (msg->header.size);
2338 char cbuf [size] GNUNET_ALIGN;
2339 ssize_t decrypted_size;
2341 LOG (GNUNET_ERROR_TYPE_DEBUG,
2342 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2344 (unsigned int) size,
2349 case CADET_TUNNEL_KEY_UNINITIALIZED:
2350 /* We did not even SEND our KX, how can the other peer
2351 send us encrypted data? */
2352 GNUNET_break_op (0);
2354 case CADET_TUNNEL_KEY_SENT:
2355 /* We did not get the KX of the other peer, but that
2356 might have been lost. Ask for KX again. */
2357 GNUNET_STATISTICS_update (stats,
2358 "# received encrypted without KX",
2361 if (NULL != t->kx_task)
2362 GNUNET_SCHEDULER_cancel (t->kx_task);
2363 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2366 case CADET_TUNNEL_KEY_PING:
2367 /* Great, first payload, we might graduate to OK */
2368 case CADET_TUNNEL_KEY_OK:
2369 case CADET_TUNNEL_KEY_REKEY:
2373 GNUNET_STATISTICS_update (stats,
2374 "# received encrypted",
2377 decrypted_size = t_ax_decrypt_and_validate (t,
2382 if (-1 == decrypted_size)
2384 GNUNET_break_op (0);
2385 LOG (GNUNET_ERROR_TYPE_WARNING,
2386 "Tunnel %s failed to decrypt and validate encrypted data\n",
2388 GNUNET_STATISTICS_update (stats,
2389 "# unable to decrypt",
2394 if (CADET_TUNNEL_KEY_PING == t->estate)
2396 GCT_change_estate (t,
2397 CADET_TUNNEL_KEY_OK);
2398 if (NULL != t->send_task)
2399 GNUNET_SCHEDULER_cancel (t->send_task);
2400 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2403 /* The MST will ultimately call #handle_decrypted() on each message. */
2404 GNUNET_break_op (GNUNET_OK ==
2405 GNUNET_MST_from_buffer (t->mst,
2414 * Sends an already built message on a tunnel, encrypting it and
2415 * choosing the best connection if not provided.
2417 * @param message Message to send. Function modifies it.
2418 * @param t Tunnel on which this message is transmitted.
2419 * @param cont Continuation to call once message is really sent.
2420 * @param cont_cls Closure for @c cont.
2421 * @return Handle to cancel message. NULL if @c cont is NULL.
2423 struct CadetTunnelQueueEntry *
2424 GCT_send (struct CadetTunnel *t,
2425 const struct GNUNET_MessageHeader *message,
2426 GNUNET_SCHEDULER_TaskCallback cont,
2429 struct CadetTunnelQueueEntry *tq;
2430 uint16_t payload_size;
2431 struct GNUNET_MQ_Envelope *env;
2432 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2434 payload_size = ntohs (message->size);
2435 LOG (GNUNET_ERROR_TYPE_DEBUG,
2436 "Encrypting %u bytes for tunnel %s\n",
2437 (unsigned int) payload_size,
2439 env = GNUNET_MQ_msg_extra (ax_msg,
2441 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2446 ax_msg->Ns = htonl (t->ax.Ns++);
2447 ax_msg->PNs = htonl (t->ax.PNs);
2448 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2452 t_hmac (&ax_msg->Ns,
2453 AX_HEADER_SIZE + payload_size,
2458 tq = GNUNET_malloc (sizeof (*tq));
2461 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2463 tq->cont_cls = cont_cls;
2464 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2467 if (NULL != t->send_task)
2468 GNUNET_SCHEDULER_cancel (t->send_task);
2470 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2477 * Cancel a previously sent message while it's in the queue.
2479 * ONLY can be called before the continuation given to the send
2480 * function is called. Once the continuation is called, the message is
2481 * no longer in the queue!
2483 * @param tq Handle to the queue entry to cancel.
2486 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2488 struct CadetTunnel *t = tq->t;
2490 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2493 GNUNET_MQ_discard (tq->env);
2499 * Iterate over all connections of a tunnel.
2501 * @param t Tunnel whose connections to iterate.
2502 * @param iter Iterator.
2503 * @param iter_cls Closure for @c iter.
2506 GCT_iterate_connections (struct CadetTunnel *t,
2507 GCT_ConnectionIterator iter,
2510 for (struct CadetTConnection *ct = t->connection_head;
2519 * Closure for #iterate_channels_cb.
2526 GCT_ChannelIterator iter;
2529 * Closure for @e iter.
2536 * Helper function for #GCT_iterate_channels.
2538 * @param cls the `struct ChanIterCls`
2540 * @param value a `struct CadetChannel`
2541 * @return #GNUNET_OK
2544 iterate_channels_cb (void *cls,
2548 struct ChanIterCls *ctx = cls;
2549 struct CadetChannel *ch = value;
2551 ctx->iter (ctx->iter_cls,
2558 * Iterate over all channels of a tunnel.
2560 * @param t Tunnel whose channels to iterate.
2561 * @param iter Iterator.
2562 * @param iter_cls Closure for @c iter.
2565 GCT_iterate_channels (struct CadetTunnel *t,
2566 GCT_ChannelIterator iter,
2569 struct ChanIterCls ctx;
2572 ctx.iter_cls = iter_cls;
2573 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2574 &iterate_channels_cb,
2581 * Call #GCCH_debug() on a channel.
2583 * @param cls points to the log level to use
2585 * @param value the `struct CadetChannel` to dump
2586 * @return #GNUNET_OK (continue iteration)
2589 debug_channel (void *cls,
2593 const enum GNUNET_ErrorType *level = cls;
2594 struct CadetChannel *ch = value;
2596 GCCH_debug (ch, *level);
2601 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2605 * Log all possible info about the tunnel state.
2607 * @param t Tunnel to debug.
2608 * @param level Debug level to use.
2611 GCT_debug (const struct CadetTunnel *t,
2612 enum GNUNET_ErrorType level)
2614 struct CadetTConnection *iter_c;
2617 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2619 __FILE__, __FUNCTION__, __LINE__);
2624 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2626 estate2s (t->estate),
2628 t->num_connections);
2629 #if DUMP_KEYS_TO_STDERR
2630 ax_debug (t->ax, level);
2634 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2638 "TTT connections:\n");
2639 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2640 GCC_debug (iter_c->cc,
2644 "TTT TUNNEL END\n");
2648 /* end of gnunet-service-cadet-new_tunnels.c */