2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
27 * - check KX estate machine -- make sure it is never stuck!
28 * - clean up KX logic, including adding sender authentication
29 * - implement connection management (evaluate, kill old ones,
30 * search for new ones)
31 * - when managing connections, distinguish those that
32 * have (recently) had traffic from those that were
33 * never ready (or not recently)
36 #include "gnunet_util_lib.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "cadet_protocol.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
52 * How long do we wait until tearing down an idle tunnel?
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
57 * Yuck, replace by 'offsetof' expression?
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
65 * Maximum number of skipped keys we keep in memory per tunnel.
67 #define MAX_SKIPPED_KEYS 64
70 * Maximum number of keys (and thus ratchet steps) we are willing to
71 * skip before we decide this is either a bogus packet or a DoS-attempt.
73 #define MAX_KEY_GAP 256
77 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
79 struct CadetTunnelSkippedKey
84 struct CadetTunnelSkippedKey *next;
89 struct CadetTunnelSkippedKey *prev;
92 * When was this key stored (for timeout).
94 struct GNUNET_TIME_Absolute timestamp;
99 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
104 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
107 * Key number for a given HK.
114 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
116 struct CadetTunnelAxolotl
119 * A (double linked) list of stored message keys and associated header keys
120 * for "skipped" messages, i.e. messages that have not been
121 * received despite the reception of more recent messages, (head).
123 struct CadetTunnelSkippedKey *skipped_head;
126 * Skipped messages' keys DLL, tail.
128 struct CadetTunnelSkippedKey *skipped_tail;
131 * 32-byte root key which gets updated by DH ratchet.
133 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
136 * 32-byte header key (send).
138 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141 * 32-byte header key (recv)
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146 * 32-byte next header key (send).
148 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
151 * 32-byte next header key (recv).
153 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
156 * 32-byte chain keys (used for forward-secrecy updating, send).
158 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
161 * 32-byte chain keys (used for forward-secrecy updating, recv).
163 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
166 * ECDH for key exchange (A0 / B0).
168 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
171 * ECDH Ratchet key (send).
173 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
176 * ECDH Ratchet key (recv).
178 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
181 * When does this ratchet expire and a new one is triggered.
183 struct GNUNET_TIME_Absolute ratchet_expiration;
186 * Number of elements in @a skipped_head <-> @a skipped_tail.
188 unsigned int skipped;
191 * Message number (reset to 0 with each new ratchet, next message to send).
196 * Message number (reset to 0 with each new ratchet, next message to recv).
201 * Previous message numbers (# of msgs sent under prev ratchet)
206 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
211 * Number of messages recieved since our last ratchet advance.
212 * - If this counter = 0, we cannot send a new ratchet key in next msg.
213 * - If this counter > 0, we can (but don't yet have to) send a new key.
215 unsigned int ratchet_allowed;
218 * Number of messages recieved since our last ratchet advance.
219 * - If this counter = 0, we cannot send a new ratchet key in next msg.
220 * - If this counter > 0, we can (but don't yet have to) send a new key.
222 unsigned int ratchet_counter;
228 * Struct used to save messages in a non-ready tunnel to send once connected.
230 struct CadetTunnelQueueEntry
233 * We are entries in a DLL
235 struct CadetTunnelQueueEntry *next;
238 * We are entries in a DLL
240 struct CadetTunnelQueueEntry *prev;
243 * Tunnel these messages belong in.
245 struct CadetTunnel *t;
248 * Continuation to call once sent (on the channel layer).
250 GNUNET_SCHEDULER_TaskCallback cont;
253 * Closure for @c cont.
258 * Envelope of message to send follows.
260 struct GNUNET_MQ_Envelope *env;
263 * Where to put the connection identifier into the payload
264 * of the message in @e env once we have it?
266 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
271 * Struct containing all information regarding a tunnel to a peer.
276 * Destination of the tunnel.
278 struct CadetPeer *destination;
281 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282 * ephemeral key changes.
284 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
287 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
289 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
292 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
294 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
299 struct CadetTunnelAxolotl ax;
302 * Task scheduled if there are no more channels using the tunnel.
304 struct GNUNET_SCHEDULER_Task *destroy_task;
307 * Task to trim connections if too many are present.
309 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
312 * Task to trigger KX.
314 struct GNUNET_SCHEDULER_Task *kx_task;
317 * Tokenizer for decrypted messages.
319 struct GNUNET_MessageStreamTokenizer *mst;
322 * Dispatcher for decrypted messages only (do NOT use for sending!).
324 struct GNUNET_MQ_Handle *mq;
327 * DLL of connections that are actively used to reach the destination peer.
329 struct CadetTConnection *connection_head;
332 * DLL of connections that are actively used to reach the destination peer.
334 struct CadetTConnection *connection_tail;
337 * Channels inside this tunnel. Maps
338 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
340 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
343 * Channel ID for the next created channel in this tunnel.
345 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
348 * Queued messages, to transmit once tunnel gets connected.
350 struct CadetTunnelQueueEntry *tq_head;
353 * Queued messages, to transmit once tunnel gets connected.
355 struct CadetTunnelQueueEntry *tq_tail;
359 * Ephemeral message in the queue (to avoid queueing more than one).
361 struct CadetConnectionQueue *ephm_hKILL;
364 * Pong message in the queue.
366 struct CadetConnectionQueue *pong_hKILL;
369 * How long do we wait until we retry the KX?
371 struct GNUNET_TIME_Relative kx_retry_delay;
374 * When do we try the next KX?
376 struct GNUNET_TIME_Absolute next_kx_attempt;
379 * Number of connections in the @e connection_head DLL.
381 unsigned int num_connections;
384 * Number of entries in the @e tq_head DLL.
389 * State of the tunnel encryption.
391 enum CadetTunnelEState estate;
397 * Get the static string for the peer this tunnel is directed.
401 * @return Static string the destination peer's ID.
404 GCT_2s (const struct CadetTunnel *t)
411 GNUNET_snprintf (buf,
414 GCP_2s (t->destination));
420 * Get string description for tunnel encryption state.
422 * @param es Tunnel state.
424 * @return String representation.
427 estate2s (enum CadetTunnelEState es)
433 case CADET_TUNNEL_KEY_UNINITIALIZED:
434 return "CADET_TUNNEL_KEY_UNINITIALIZED";
435 case CADET_TUNNEL_KEY_SENT:
436 return "CADET_TUNNEL_KEY_SENT";
437 case CADET_TUNNEL_KEY_PING:
438 return "CADET_TUNNEL_KEY_PING";
439 case CADET_TUNNEL_KEY_OK:
440 return "CADET_TUNNEL_KEY_OK";
441 case CADET_TUNNEL_KEY_REKEY:
442 return "CADET_TUNNEL_KEY_REKEY";
444 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
451 * Return the peer to which this tunnel goes.
454 * @return the destination of the tunnel
457 GCT_get_destination (struct CadetTunnel *t)
459 return t->destination;
464 * Count channels of a tunnel.
466 * @param t Tunnel on which to count.
468 * @return Number of channels.
471 GCT_count_channels (struct CadetTunnel *t)
473 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
478 * Lookup a channel by its @a ctn.
480 * @param t tunnel to look in
481 * @param ctn number of channel to find
482 * @return NULL if channel does not exist
484 struct CadetChannel *
485 lookup_channel (struct CadetTunnel *t,
486 struct GNUNET_CADET_ChannelTunnelNumber ctn)
488 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
494 * Count all created connections of a tunnel. Not necessarily ready connections!
496 * @param t Tunnel on which to count.
498 * @return Number of connections created, either being established or ready.
501 GCT_count_any_connections (struct CadetTunnel *t)
503 return t->num_connections;
508 * Find first connection that is ready in the list of
509 * our connections. Picks ready connections round-robin.
511 * @param t tunnel to search
512 * @return NULL if we have no connection that is ready
514 static struct CadetTConnection *
515 get_ready_connection (struct CadetTunnel *t)
517 for (struct CadetTConnection *pos = t->connection_head;
520 if (GNUNET_YES == pos->is_ready)
522 if (pos != t->connection_tail)
524 /* move 'pos' to the end, so we try other ready connections
525 first next time (round-robin, modulo availability) */
526 GNUNET_CONTAINER_DLL_remove (t->connection_head,
529 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
540 * Get the encryption state of a tunnel.
544 * @return Tunnel's encryption state.
546 enum CadetTunnelEState
547 GCT_get_estate (struct CadetTunnel *t)
554 * Create a new Axolotl ephemeral (ratchet) key.
559 new_ephemeral (struct CadetTunnel *t)
561 GNUNET_free_non_null (t->ax.DHRs);
562 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
568 * Called when either we have a new connection, or a new message in the
569 * queue, or some existing connection has transmission capacity. Looks
570 * at our message queue and if there is a message, picks a connection
573 * @param t tunnel to process messages on
576 trigger_transmissions (struct CadetTunnel *t);
579 /* ************************************** start core crypto ***************************** */
585 * @param plaintext Content to HMAC.
586 * @param size Size of @c plaintext.
587 * @param iv Initialization vector for the message.
588 * @param key Key to use.
589 * @param hmac[out] Destination to store the HMAC.
592 t_hmac (const void *plaintext,
595 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
596 struct GNUNET_ShortHashCode *hmac)
598 static const char ctx[] = "cadet authentication key";
599 struct GNUNET_CRYPTO_AuthKey auth_key;
600 struct GNUNET_HashCode hash;
602 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
608 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
609 GNUNET_CRYPTO_hmac (&auth_key,
622 * @param key Key to use.
623 * @param hash[out] Resulting HMAC.
624 * @param source Source key material (data to HMAC).
625 * @param len Length of @a source.
628 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
629 struct GNUNET_HashCode *hash,
633 static const char ctx[] = "axolotl HMAC-HASH";
634 struct GNUNET_CRYPTO_AuthKey auth_key;
636 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
640 GNUNET_CRYPTO_hmac (&auth_key,
648 * Derive a symmetric encryption key from an HMAC-HASH.
650 * @param key Key to use for the HMAC.
651 * @param[out] out Key to generate.
652 * @param source Source key material (data to HMAC).
653 * @param len Length of @a source.
656 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
657 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
661 static const char ctx[] = "axolotl derive key";
662 struct GNUNET_HashCode h;
668 GNUNET_CRYPTO_kdf (out, sizeof (*out),
676 * Encrypt data with the axolotl tunnel key.
678 * @param t Tunnel whose key to use.
679 * @param dst Destination with @a size bytes for the encrypted data.
680 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
681 * @param size Size of the buffers at @a src and @a dst
684 t_ax_encrypt (struct CadetTunnel *t,
689 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
690 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
691 struct CadetTunnelAxolotl *ax;
695 ax->ratchet_counter++;
696 if ( (GNUNET_YES == ax->ratchet_allowed) &&
697 ( (ratchet_messages <= ax->ratchet_counter) ||
698 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
700 ax->ratchet_flag = GNUNET_YES;
702 if (GNUNET_YES == ax->ratchet_flag)
704 /* Advance ratchet */
705 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
706 struct GNUNET_HashCode dh;
707 struct GNUNET_HashCode hmac;
708 static const char ctx[] = "axolotl ratchet";
713 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
714 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
717 t_ax_hmac_hash (&ax->RK,
721 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
723 &hmac, sizeof (hmac),
731 ax->ratchet_flag = GNUNET_NO;
732 ax->ratchet_allowed = GNUNET_NO;
733 ax->ratchet_counter = 0;
734 ax->ratchet_expiration
735 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
739 t_hmac_derive_key (&ax->CKs,
743 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
748 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
753 GNUNET_assert (size == out_size);
754 t_hmac_derive_key (&ax->CKs,
762 * Decrypt data with the axolotl tunnel key.
764 * @param t Tunnel whose key to use.
765 * @param dst Destination for the decrypted data, must contain @a size bytes.
766 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
767 * @param size Size of the @a src and @a dst buffers
770 t_ax_decrypt (struct CadetTunnel *t,
775 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
776 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
777 struct CadetTunnelAxolotl *ax;
781 t_hmac_derive_key (&ax->CKr,
785 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
789 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
790 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
795 GNUNET_assert (out_size == size);
796 t_hmac_derive_key (&ax->CKr,
804 * Encrypt header with the axolotl header key.
806 * @param t Tunnel whose key to use.
807 * @param msg Message whose header to encrypt.
810 t_h_encrypt (struct CadetTunnel *t,
811 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
813 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
814 struct CadetTunnelAxolotl *ax;
818 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
822 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
827 GNUNET_assert (AX_HEADER_SIZE == out_size);
832 * Decrypt header with the current axolotl header key.
834 * @param t Tunnel whose current ax HK to use.
835 * @param src Message whose header to decrypt.
836 * @param dst Where to decrypt header to.
839 t_h_decrypt (struct CadetTunnel *t,
840 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
841 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
843 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
844 struct CadetTunnelAxolotl *ax;
848 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
852 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
857 GNUNET_assert (AX_HEADER_SIZE == out_size);
862 * Delete a key from the list of skipped keys.
864 * @param t Tunnel to delete from.
865 * @param key Key to delete.
868 delete_skipped_key (struct CadetTunnel *t,
869 struct CadetTunnelSkippedKey *key)
871 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
880 * Decrypt and verify data with the appropriate tunnel key and verify that the
881 * data has not been altered since it was sent by the remote peer.
883 * @param t Tunnel whose key to use.
884 * @param dst Destination for the plaintext.
885 * @param src Source of the message. Can overlap with @c dst.
886 * @param size Size of the message.
887 * @return Size of the decrypted data, -1 if an error was encountered.
890 try_old_ax_keys (struct CadetTunnel *t,
892 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
895 struct CadetTunnelSkippedKey *key;
896 struct GNUNET_ShortHashCode *hmac;
897 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
898 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
899 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
905 LOG (GNUNET_ERROR_TYPE_DEBUG,
906 "Trying skipped keys\n");
907 hmac = &plaintext_header.hmac;
908 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
910 /* Find a correct Header Key */
912 for (key = t->ax.skipped_head; NULL != key; key = key->next)
915 AX_HEADER_SIZE + esize,
919 if (0 == memcmp (hmac,
930 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
931 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
932 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
933 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
936 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
940 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
944 &plaintext_header.Ns);
945 GNUNET_assert (AX_HEADER_SIZE == res);
947 /* Find the correct message key */
948 N = ntohl (plaintext_header.Ns);
949 while ( (NULL != key) &&
952 if ( (NULL == key) ||
953 (0 != memcmp (&key->HK,
955 sizeof (*valid_HK))) )
958 /* Decrypt payload */
959 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
964 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
969 delete_skipped_key (t,
976 * Delete a key from the list of skipped keys.
978 * @param t Tunnel to delete from.
979 * @param HKr Header Key to use.
982 store_skipped_key (struct CadetTunnel *t,
983 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
985 struct CadetTunnelSkippedKey *key;
987 key = GNUNET_new (struct CadetTunnelSkippedKey);
988 key->timestamp = GNUNET_TIME_absolute_get ();
991 t_hmac_derive_key (&t->ax.CKr,
995 t_hmac_derive_key (&t->ax.CKr,
999 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1008 * Stage skipped AX keys and calculate the message key.
1009 * Stores each HK and MK for skipped messages.
1011 * @param t Tunnel where to stage the keys.
1012 * @param HKr Header key.
1013 * @param Np Received meesage number.
1014 * @return #GNUNET_OK if keys were stored.
1015 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1018 store_ax_keys (struct CadetTunnel *t,
1019 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1024 gap = Np - t->ax.Nr;
1025 LOG (GNUNET_ERROR_TYPE_DEBUG,
1026 "Storing skipped keys [%u, %u)\n",
1029 if (MAX_KEY_GAP < gap)
1031 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1032 /* TODO: start new key exchange on return */
1033 GNUNET_break_op (0);
1034 LOG (GNUNET_ERROR_TYPE_WARNING,
1035 "Got message %u, expected %u+\n",
1038 return GNUNET_SYSERR;
1042 /* Delayed message: don't store keys, flag to try old keys. */
1043 return GNUNET_SYSERR;
1046 while (t->ax.Nr < Np)
1047 store_skipped_key (t,
1050 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1051 delete_skipped_key (t,
1052 t->ax.skipped_tail);
1058 * Decrypt and verify data with the appropriate tunnel key and verify that the
1059 * data has not been altered since it was sent by the remote peer.
1061 * @param t Tunnel whose key to use.
1062 * @param dst Destination for the plaintext.
1063 * @param src Source of the message. Can overlap with @c dst.
1064 * @param size Size of the message.
1065 * @return Size of the decrypted data, -1 if an error was encountered.
1068 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1070 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1073 struct CadetTunnelAxolotl *ax;
1074 struct GNUNET_ShortHashCode msg_hmac;
1075 struct GNUNET_HashCode hmac;
1076 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1079 size_t esize; /* Size of encryped payload */
1081 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1084 /* Try current HK */
1086 AX_HEADER_SIZE + esize,
1089 if (0 != memcmp (&msg_hmac,
1093 static const char ctx[] = "axolotl ratchet";
1094 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1095 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1096 struct GNUNET_HashCode dh;
1097 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1101 AX_HEADER_SIZE + esize,
1105 if (0 != memcmp (&msg_hmac,
1109 /* Try the skipped keys, if that fails, we're out of luck. */
1110 return try_old_ax_keys (t,
1120 Np = ntohl (plaintext_header.Ns);
1121 PNp = ntohl (plaintext_header.PNs);
1122 DHRp = &plaintext_header.DHRs;
1127 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1128 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1131 t_ax_hmac_hash (&ax->RK,
1134 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1136 &hmac, sizeof (hmac),
1139 /* Commit "purported" keys */
1145 ax->ratchet_allowed = GNUNET_YES;
1152 Np = ntohl (plaintext_header.Ns);
1153 PNp = ntohl (plaintext_header.PNs);
1155 if ( (Np != ax->Nr) &&
1156 (GNUNET_OK != store_ax_keys (t,
1160 /* Try the skipped keys, if that fails, we're out of luck. */
1161 return try_old_ax_keys (t,
1177 * Change the tunnel encryption state.
1178 * If the encryption state changes to OK, stop the rekey task.
1180 * @param t Tunnel whose encryption state to change, or NULL.
1181 * @param state New encryption state.
1184 GCT_change_estate (struct CadetTunnel *t,
1185 enum CadetTunnelEState state)
1187 enum CadetTunnelEState old = t->estate;
1190 LOG (GNUNET_ERROR_TYPE_DEBUG,
1191 "Tunnel %s estate changed from %d to %d\n",
1196 if ( (CADET_TUNNEL_KEY_OK != old) &&
1197 (CADET_TUNNEL_KEY_OK == t->estate) )
1199 if (NULL != t->kx_task)
1201 GNUNET_SCHEDULER_cancel (t->kx_task);
1204 /* FIXME: schedule rekey task! */
1210 * Send a KX message.
1212 * FIXME: does not take care of sender-authentication yet!
1214 * @param t Tunnel on which to send it.
1215 * @param force_reply Force the other peer to reply with a KX message.
1218 send_kx (struct CadetTunnel *t,
1221 struct CadetTunnelAxolotl *ax = &t->ax;
1222 struct CadetTConnection *ct;
1223 struct CadetConnection *cc;
1224 struct GNUNET_MQ_Envelope *env;
1225 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1226 enum GNUNET_CADET_KX_Flags flags;
1228 ct = get_ready_connection (t);
1231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1238 "Sending KX on tunnel %s using connection %s\n",
1242 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1243 env = GNUNET_MQ_msg (msg,
1244 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1245 flags = GNUNET_CADET_KX_FLAG_NONE;
1246 if (GNUNET_YES == force_reply)
1247 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1248 msg->flags = htonl (flags);
1249 msg->cid = *GCC_get_id (cc);
1250 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1251 &msg->ephemeral_key);
1252 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1256 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1257 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1258 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1259 GCT_change_estate (t,
1260 CADET_TUNNEL_KEY_SENT);
1265 * Handle KX message.
1267 * FIXME: sender-authentication in KX is missing!
1269 * @param ct connection/tunnel combo that received encrypted message
1270 * @param msg the key exchange message
1273 GCT_handle_kx (struct CadetTConnection *ct,
1274 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1276 struct CadetTunnel *t = ct->t;
1277 struct CadetTunnelAxolotl *ax = &t->ax;
1278 struct GNUNET_HashCode key_material[3];
1279 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1280 const char salt[] = "CADET Axolotl salt";
1281 const struct GNUNET_PeerIdentity *pid;
1284 pid = GCP_get_id (t->destination);
1285 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1287 am_I_alice = GNUNET_YES;
1288 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1290 am_I_alice = GNUNET_NO;
1293 GNUNET_break_op (0);
1297 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1299 if (NULL != t->kx_task)
1301 GNUNET_SCHEDULER_cancel (t->kx_task);
1308 if (0 == memcmp (&ax->DHRr,
1310 sizeof (msg->ratchet_key)))
1312 LOG (GNUNET_ERROR_TYPE_DEBUG,
1313 " known ratchet key, exit\n");
1317 ax->DHRr = msg->ratchet_key;
1320 if (GNUNET_YES == am_I_alice)
1322 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1323 &msg->ephemeral_key, /* B0 */
1328 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1329 &pid->public_key, /* A */
1334 if (GNUNET_YES == am_I_alice)
1336 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1337 &pid->public_key, /* B */
1342 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1343 &msg->ephemeral_key, /* B0 */
1350 /* (This is the triple-DH, we could probably safely skip this,
1351 as A0/B0 are already in the key material.) */
1352 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1353 &msg->ephemeral_key, /* B0 or A0 */
1357 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1358 salt, sizeof (salt),
1359 &key_material, sizeof (key_material),
1362 if (0 == memcmp (&ax->RK,
1366 LOG (GNUNET_ERROR_TYPE_INFO,
1367 " known handshake key, exit\n");
1370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1371 "Handling KX message for tunnel %s\n",
1375 if (GNUNET_YES == am_I_alice)
1381 ax->ratchet_flag = GNUNET_YES;
1389 ax->ratchet_flag = GNUNET_NO;
1390 ax->ratchet_allowed = GNUNET_NO;
1391 ax->ratchet_counter = 0;
1392 ax->ratchet_expiration
1393 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1402 case CADET_TUNNEL_KEY_UNINITIALIZED:
1403 GCT_change_estate (t,
1404 CADET_TUNNEL_KEY_PING);
1406 case CADET_TUNNEL_KEY_SENT:
1407 /* Got a response to us sending our key; now
1408 we can start transmitting! */
1409 GCT_change_estate (t,
1410 CADET_TUNNEL_KEY_OK);
1411 trigger_transmissions (t);
1413 case CADET_TUNNEL_KEY_PING:
1414 /* Got a key yet again; need encrypted payload to advance */
1416 case CADET_TUNNEL_KEY_OK:
1417 /* Did not expect a key, but so what. */
1419 case CADET_TUNNEL_KEY_REKEY:
1420 /* Got a key yet again; need encrypted payload to advance */
1426 /* ************************************** end core crypto ***************************** */
1430 * Compute the next free channel tunnel number for this tunnel.
1432 * @param t the tunnel
1433 * @return unused number that can uniquely identify a channel in the tunnel
1435 static struct GNUNET_CADET_ChannelTunnelNumber
1436 get_next_free_ctn (struct CadetTunnel *t)
1438 struct GNUNET_CADET_ChannelTunnelNumber ret;
1441 /* FIXME: this logic does NOT prevent both ends of the
1442 channel from picking the same CTN!
1443 Need to reserve one bit of the CTN for the
1444 direction, i.e. which side established the connection! */
1445 ctn = ntohl (t->next_ctn.cn);
1447 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1450 t->next_ctn.cn = htonl (ctn + 1);
1451 ret.cn = ntohl (ctn);
1457 * Add a channel to a tunnel.
1461 * @return unique number identifying @a ch within @a t
1463 struct GNUNET_CADET_ChannelTunnelNumber
1464 GCT_add_channel (struct CadetTunnel *t,
1465 struct CadetChannel *ch)
1467 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1469 ctn = get_next_free_ctn (t);
1470 GNUNET_assert (GNUNET_YES ==
1471 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1474 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476 "Adding channel %s to tunnel %s\n",
1484 * This tunnel is no longer used, destroy it.
1486 * @param cls the idle tunnel
1489 destroy_tunnel (void *cls)
1491 struct CadetTunnel *t = cls;
1492 struct CadetTConnection *ct;
1493 struct CadetTunnelQueueEntry *tqe;
1495 t->destroy_task = NULL;
1496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1497 "Destroying idle tunnel %s\n",
1499 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1500 while (NULL != (ct = t->connection_head))
1502 GNUNET_assert (ct->t == t);
1503 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1506 GCC_destroy (ct->cc);
1509 while (NULL != (tqe = t->tq_head))
1511 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1514 GNUNET_MQ_discard (tqe->env);
1517 GCP_drop_tunnel (t->destination,
1519 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1520 if (NULL != t->maintain_connections_task)
1522 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1523 t->maintain_connections_task = NULL;
1525 GNUNET_MST_destroy (t->mst);
1526 GNUNET_MQ_destroy (t->mq);
1532 * Remove a channel from a tunnel.
1536 * @param ctn unique number identifying @a ch within @a t
1539 GCT_remove_channel (struct CadetTunnel *t,
1540 struct CadetChannel *ch,
1541 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1544 "Removing channel %s from tunnel %s\n",
1547 GNUNET_assert (GNUNET_YES ==
1548 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1552 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1554 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1562 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1564 * @param t tunnel to destroy
1567 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1570 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1571 GNUNET_SCHEDULER_cancel (t->destroy_task);
1577 * It's been a while, we should try to redo the KX, if we can.
1579 * @param cls the `struct CadetTunnel` to do KX for.
1582 retry_kx (void *cls)
1584 struct CadetTunnel *t = cls;
1588 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1589 (CADET_TUNNEL_KEY_SENT == t->estate) )
1596 * Send normal payload from queue in @a t via connection @a ct.
1597 * Does nothing if our payload queue is empty.
1599 * @param t tunnel to send data from
1600 * @param ct connection to use for transmission (is ready)
1603 try_send_normal_payload (struct CadetTunnel *t,
1604 struct CadetTConnection *ct)
1606 struct CadetTunnelQueueEntry *tq;
1608 GNUNET_assert (GNUNET_YES == ct->is_ready);
1612 /* no messages pending right now */
1613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1614 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1619 /* ready to send message 'tq' on tunnel 'ct' */
1620 GNUNET_assert (t == tq->t);
1621 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1624 if (NULL != tq->cid)
1625 *tq->cid = *GCC_get_id (ct->cc);
1626 ct->is_ready = GNUNET_NO;
1627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1628 "Sending payload of tunnel %s on connection %s\n",
1631 GCC_transmit (ct->cc,
1633 if (NULL != tq->cont)
1634 tq->cont (tq->cont_cls);
1640 * A connection is @a is_ready for transmission. Looks at our message
1641 * queue and if there is a message, sends it out via the connection.
1643 * @param cls the `struct CadetTConnection` that is @a is_ready
1644 * @param is_ready #GNUNET_YES if connection are now ready,
1645 * #GNUNET_NO if connection are no longer ready
1648 connection_ready_cb (void *cls,
1651 struct CadetTConnection *ct = cls;
1652 struct CadetTunnel *t = ct->t;
1654 if (GNUNET_NO == is_ready)
1656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1657 "Connection %s no longer ready for tunnel %s\n",
1660 ct->is_ready = GNUNET_NO;
1663 ct->is_ready = GNUNET_YES;
1664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665 "Connection %s now ready for tunnel %s in state %s\n",
1668 estate2s (t->estate));
1671 case CADET_TUNNEL_KEY_UNINITIALIZED:
1675 case CADET_TUNNEL_KEY_SENT:
1676 case CADET_TUNNEL_KEY_PING:
1677 /* opportunity to #retry_kx() starts now, schedule job */
1678 if (NULL == t->kx_task)
1681 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt),
1686 case CADET_TUNNEL_KEY_OK:
1687 try_send_normal_payload (t,
1690 case CADET_TUNNEL_KEY_REKEY:
1693 t->estate = CADET_TUNNEL_KEY_OK;
1700 * Called when either we have a new connection, or a new message in the
1701 * queue, or some existing connection has transmission capacity. Looks
1702 * at our message queue and if there is a message, picks a connection
1705 * @param t tunnel to process messages on
1708 trigger_transmissions (struct CadetTunnel *t)
1710 struct CadetTConnection *ct;
1712 if (NULL == t->tq_head)
1713 return; /* no messages pending right now */
1714 ct = get_ready_connection (t);
1716 return; /* no connections ready */
1717 try_send_normal_payload (t,
1723 * Function called to maintain the connections underlying our tunnel.
1724 * Tries to maintain (incl. tear down) connections for the tunnel, and
1725 * if there is a significant change, may trigger transmissions.
1727 * Basically, needs to check if there are connections that perform
1728 * badly, and if so eventually kill them and trigger a replacement.
1729 * The strategy is to open one more connection than
1730 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1731 * least-performing one, and then inquire for new ones.
1733 * @param cls the `struct CadetTunnel`
1736 maintain_connections_cb (void *cls)
1738 struct CadetTunnel *t = cls;
1740 t->maintain_connections_task = NULL;
1741 GNUNET_break (0); // FIXME: implement!
1746 * Consider using the path @a p for the tunnel @a t.
1747 * The tunnel destination is at offset @a off in path @a p.
1749 * @param cls our tunnel
1750 * @param path a path to our destination
1751 * @param off offset of the destination on path @a path
1752 * @return #GNUNET_YES (should keep iterating)
1755 consider_path_cb (void *cls,
1756 struct CadetPeerPath *path,
1759 struct CadetTunnel *t = cls;
1760 unsigned int min_length = UINT_MAX;
1761 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1762 struct CadetTConnection *ct;
1764 /* Check if we care about the new path. */
1765 for (ct = t->connection_head;
1769 struct CadetPeerPath *ps;
1771 ps = GCC_get_path (ct->cc);
1773 return GNUNET_YES; /* duplicate */
1774 min_length = GNUNET_MIN (min_length,
1775 GCPP_get_length (ps));
1776 max_desire = GNUNET_MAX (max_desire,
1777 GCPP_get_desirability (ps));
1780 /* FIXME: not sure we should really just count
1781 'num_connections' here, as they may all have
1782 consistently failed to connect. */
1784 /* We iterate by increasing path length; if we have enough paths and
1785 this one is more than twice as long than what we are currently
1786 using, then ignore all of these super-long ones! */
1787 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1788 (min_length * 2 < off) )
1790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1791 "Ignoring paths of length %u, they are way too long.\n",
1795 /* If we have enough paths and this one looks no better, ignore it. */
1796 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1797 (min_length < GCPP_get_length (path)) &&
1798 (max_desire > GCPP_get_desirability (path)) )
1800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1801 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1802 GCPP_get_length (path),
1803 (unsigned long long) GCPP_get_desirability (path),
1804 GCP_2s (t->destination));
1808 /* Path is interesting (better by some metric, or we don't have
1809 enough paths yet). */
1810 ct = GNUNET_new (struct CadetTConnection);
1811 ct->created = GNUNET_TIME_absolute_get ();
1813 ct->cc = GCC_create (t->destination,
1816 &connection_ready_cb,
1818 /* FIXME: schedule job to kill connection (and path?) if it takes
1819 too long to get ready! (And track performance data on how long
1820 other connections took with the tunnel!)
1821 => Note: to be done within 'connection'-logic! */
1822 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1825 t->num_connections++;
1826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827 "Found interesting path %s for tunnel %s, created connection %s\n",
1836 * Consider using the path @a p for the tunnel @a t.
1837 * The tunnel destination is at offset @a off in path @a p.
1839 * @param cls our tunnel
1840 * @param path a path to our destination
1841 * @param off offset of the destination on path @a path
1844 GCT_consider_path (struct CadetTunnel *t,
1845 struct CadetPeerPath *p,
1848 (void) consider_path_cb (t,
1857 * @param cls the `struct CadetTunnel` for which we decrypted the message
1858 * @param msg the message we received on the tunnel
1861 handle_plaintext_keepalive (void *cls,
1862 const struct GNUNET_MessageHeader *msg)
1864 struct CadetTunnel *t = cls;
1866 GNUNET_break (0); // FIXME
1871 * Check that @a msg is well-formed.
1873 * @param cls the `struct CadetTunnel` for which we decrypted the message
1874 * @param msg the message we received on the tunnel
1875 * @return #GNUNET_OK (any variable-size payload goes)
1878 check_plaintext_data (void *cls,
1879 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1886 * We received payload data for a channel. Locate the channel
1887 * and process the data, or return an error if the channel is unknown.
1889 * @param cls the `struct CadetTunnel` for which we decrypted the message
1890 * @param msg the message we received on the tunnel
1893 handle_plaintext_data (void *cls,
1894 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1896 struct CadetTunnel *t = cls;
1897 struct CadetChannel *ch;
1899 ch = lookup_channel (t,
1903 /* We don't know about such a channel, might have been destroyed on our
1904 end in the meantime, or never existed. Send back a DESTROY. */
1905 LOG (GNUNET_ERROR_TYPE_DEBUG,
1906 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
1907 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
1908 ntohl (msg->ctn.cn));
1909 GCT_send_channel_destroy (t,
1913 GCCH_handle_channel_plaintext_data (ch,
1919 * We received an acknowledgement for data we sent on a channel.
1920 * Locate the channel and process it, or return an error if the
1921 * channel is unknown.
1923 * @param cls the `struct CadetTunnel` for which we decrypted the message
1924 * @param ack the message we received on the tunnel
1927 handle_plaintext_data_ack (void *cls,
1928 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1930 struct CadetTunnel *t = cls;
1931 struct CadetChannel *ch;
1933 ch = lookup_channel (t,
1937 /* We don't know about such a channel, might have been destroyed on our
1938 end in the meantime, or never existed. Send back a DESTROY. */
1939 LOG (GNUNET_ERROR_TYPE_DEBUG,
1940 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
1941 ntohl (ack->ctn.cn));
1942 GCT_send_channel_destroy (t,
1946 GCCH_handle_channel_plaintext_data_ack (ch,
1952 * We have received a request to open a channel to a port from
1953 * another peer. Creates the incoming channel.
1955 * @param cls the `struct CadetTunnel` for which we decrypted the message
1956 * @param cc the message we received on the tunnel
1959 handle_plaintext_channel_open (void *cls,
1960 const struct GNUNET_CADET_ChannelOpenMessage *cc)
1962 struct CadetTunnel *t = cls;
1963 struct CadetChannel *ch;
1964 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1966 LOG (GNUNET_ERROR_TYPE_DEBUG,
1967 "Receicved channel OPEN on port %s from peer %s\n",
1968 GNUNET_h2s (&cc->port),
1969 GCP_2s (GCT_get_destination (t)));
1970 ctn = get_next_free_ctn (t);
1971 ch = GCCH_channel_incoming_new (t,
1975 GNUNET_assert (GNUNET_OK ==
1976 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1979 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1984 * Send a DESTROY message via the tunnel.
1986 * @param t the tunnel to transmit over
1987 * @param ctn ID of the channel to destroy
1990 GCT_send_channel_destroy (struct CadetTunnel *t,
1991 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1993 struct GNUNET_CADET_ChannelManageMessage msg;
1995 LOG (GNUNET_ERROR_TYPE_DEBUG,
1996 "Sending DESTORY message for channel ID %u\n",
1998 msg.header.size = htons (sizeof (msg));
1999 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2000 msg.reserved = htonl (0);
2010 * We have received confirmation from the target peer that the
2011 * given channel could be established (the port is open).
2014 * @param cls the `struct CadetTunnel` for which we decrypted the message
2015 * @param cm the message we received on the tunnel
2018 handle_plaintext_channel_open_ack (void *cls,
2019 const struct GNUNET_CADET_ChannelManageMessage *cm)
2021 struct CadetTunnel *t = cls;
2022 struct CadetChannel *ch;
2024 ch = lookup_channel (t,
2028 /* We don't know about such a channel, might have been destroyed on our
2029 end in the meantime, or never existed. Send back a DESTROY. */
2030 LOG (GNUNET_ERROR_TYPE_DEBUG,
2031 "Received channel OPEN_ACK for unknown channel, sending DESTROY\n",
2033 GCT_send_channel_destroy (t,
2037 GCCH_handle_channel_open_ack (ch);
2042 * We received a message saying that a channel should be destroyed.
2043 * Pass it on to the correct channel.
2045 * @param cls the `struct CadetTunnel` for which we decrypted the message
2046 * @param cm the message we received on the tunnel
2049 handle_plaintext_channel_destroy (void *cls,
2050 const struct GNUNET_CADET_ChannelManageMessage *cm)
2052 struct CadetTunnel *t = cls;
2053 struct CadetChannel *ch;
2055 ch = lookup_channel (t,
2059 /* We don't know about such a channel, might have been destroyed on our
2060 end in the meantime, or never existed. */
2061 LOG (GNUNET_ERROR_TYPE_DEBUG,
2062 "Received channel DESTORY for unknown channel. Ignoring.\n",
2066 GCCH_handle_remote_destroy (ch);
2071 * Handles a message we decrypted, by injecting it into
2072 * our message queue (which will do the dispatching).
2074 * @param cls the `struct CadetTunnel` that got the message
2075 * @param msg the message
2076 * @return #GNUNET_OK (continue to process)
2079 handle_decrypted (void *cls,
2080 const struct GNUNET_MessageHeader *msg)
2082 struct CadetTunnel *t = cls;
2084 GNUNET_MQ_inject_message (t->mq,
2091 * Function called if we had an error processing
2092 * an incoming decrypted message.
2094 * @param cls the `struct CadetTunnel`
2095 * @param error error code
2098 decrypted_error_cb (void *cls,
2099 enum GNUNET_MQ_Error error)
2101 GNUNET_break_op (0);
2106 * Create a tunnel to @a destionation. Must only be called
2107 * from within #GCP_get_tunnel().
2109 * @param destination where to create the tunnel to
2110 * @return new tunnel to @a destination
2112 struct CadetTunnel *
2113 GCT_create_tunnel (struct CadetPeer *destination)
2115 struct GNUNET_MQ_MessageHandler handlers[] = {
2116 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2117 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2118 struct GNUNET_MessageHeader,
2120 GNUNET_MQ_hd_var_size (plaintext_data,
2121 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2122 struct GNUNET_CADET_ChannelAppDataMessage,
2124 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2125 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2126 struct GNUNET_CADET_ChannelDataAckMessage,
2128 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2129 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2130 struct GNUNET_CADET_ChannelOpenMessage,
2132 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2133 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2134 struct GNUNET_CADET_ChannelManageMessage,
2136 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2137 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2138 struct GNUNET_CADET_ChannelManageMessage,
2140 GNUNET_MQ_handler_end ()
2142 struct CadetTunnel *t;
2144 t = GNUNET_new (struct CadetTunnel);
2146 t->destination = destination;
2147 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2148 (void) GCP_iterate_paths (destination,
2151 t->maintain_connections_task
2152 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2154 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2159 &decrypted_error_cb,
2161 t->mst = GNUNET_MST_create (&handle_decrypted,
2168 * Add a @a connection to the @a tunnel.
2171 * @param cid connection identifer to use for the connection
2172 * @param path path to use for the connection
2175 GCT_add_inbound_connection (struct CadetTunnel *t,
2176 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2177 struct CadetPeerPath *path)
2179 struct CadetTConnection *ct;
2181 ct = GNUNET_new (struct CadetTConnection);
2182 ct->created = GNUNET_TIME_absolute_get ();
2184 ct->cc = GCC_create_inbound (t->destination,
2188 &connection_ready_cb,
2190 /* FIXME: schedule job to kill connection (and path?) if it takes
2191 too long to get ready! (And track performance data on how long
2192 other connections took with the tunnel!)
2193 => Note: to be done within 'connection'-logic! */
2194 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2197 t->num_connections++;
2198 LOG (GNUNET_ERROR_TYPE_DEBUG,
2199 "Tunnel %s has new connection %s\n",
2206 * Handle encrypted message.
2208 * @param ct connection/tunnel combo that received encrypted message
2209 * @param msg the encrypted message to decrypt
2212 GCT_handle_encrypted (struct CadetTConnection *ct,
2213 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2215 struct CadetTunnel *t = ct->t;
2216 uint16_t size = ntohs (msg->header.size);
2217 char cbuf [size] GNUNET_ALIGN;
2218 ssize_t decrypted_size;
2220 LOG (GNUNET_ERROR_TYPE_DEBUG,
2221 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2223 (unsigned int) size,
2228 case CADET_TUNNEL_KEY_UNINITIALIZED:
2229 /* We did not even SEND our KX, how can the other peer
2230 send us encrypted data? */
2231 GNUNET_break_op (0);
2233 case CADET_TUNNEL_KEY_SENT:
2234 /* We did not get the KX of the other peer, but that
2235 might have been lost. Ask for KX again. */
2236 GNUNET_STATISTICS_update (stats,
2237 "# received encrypted without KX",
2240 if (NULL != t->kx_task)
2241 GNUNET_SCHEDULER_cancel (t->kx_task);
2242 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2245 case CADET_TUNNEL_KEY_PING:
2246 /* Great, first payload, we might graduate to OK */
2247 case CADET_TUNNEL_KEY_OK:
2248 case CADET_TUNNEL_KEY_REKEY:
2252 GNUNET_STATISTICS_update (stats,
2253 "# received encrypted",
2256 decrypted_size = t_ax_decrypt_and_validate (t,
2261 if (-1 == decrypted_size)
2263 GNUNET_break_op (0);
2264 LOG (GNUNET_ERROR_TYPE_WARNING,
2265 "Tunnel %s failed to decrypt and validate encrypted data\n",
2267 GNUNET_STATISTICS_update (stats,
2268 "# unable to decrypt",
2273 if (CADET_TUNNEL_KEY_PING == t->estate)
2275 GCT_change_estate (t,
2276 CADET_TUNNEL_KEY_OK);
2277 trigger_transmissions (t);
2279 /* The MST will ultimately call #handle_decrypted() on each message. */
2280 GNUNET_break_op (GNUNET_OK ==
2281 GNUNET_MST_from_buffer (t->mst,
2290 * Sends an already built message on a tunnel, encrypting it and
2291 * choosing the best connection if not provided.
2293 * @param message Message to send. Function modifies it.
2294 * @param t Tunnel on which this message is transmitted.
2295 * @param cont Continuation to call once message is really sent.
2296 * @param cont_cls Closure for @c cont.
2297 * @return Handle to cancel message. NULL if @c cont is NULL.
2299 struct CadetTunnelQueueEntry *
2300 GCT_send (struct CadetTunnel *t,
2301 const struct GNUNET_MessageHeader *message,
2302 GNUNET_SCHEDULER_TaskCallback cont,
2305 struct CadetTunnelQueueEntry *tq;
2306 uint16_t payload_size;
2307 struct GNUNET_MQ_Envelope *env;
2308 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2310 payload_size = ntohs (message->size);
2311 LOG (GNUNET_ERROR_TYPE_DEBUG,
2312 "Encrypting %u bytes of for tunnel %s\n",
2313 (unsigned int) payload_size,
2315 env = GNUNET_MQ_msg_extra (ax_msg,
2317 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2322 ax_msg->Ns = htonl (t->ax.Ns++);
2323 ax_msg->PNs = htonl (t->ax.PNs);
2324 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2328 t_hmac (&ax_msg->Ns,
2329 AX_HEADER_SIZE + payload_size,
2334 tq = GNUNET_malloc (sizeof (*tq));
2337 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2339 tq->cont_cls = cont_cls;
2340 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2343 trigger_transmissions (t);
2349 * Cancel a previously sent message while it's in the queue.
2351 * ONLY can be called before the continuation given to the send
2352 * function is called. Once the continuation is called, the message is
2353 * no longer in the queue!
2355 * @param q Handle to the queue entry to cancel.
2358 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
2360 struct CadetTunnel *t = q->t;
2362 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2370 * Iterate over all connections of a tunnel.
2372 * @param t Tunnel whose connections to iterate.
2373 * @param iter Iterator.
2374 * @param iter_cls Closure for @c iter.
2377 GCT_iterate_connections (struct CadetTunnel *t,
2378 GCT_ConnectionIterator iter,
2381 for (struct CadetTConnection *ct = t->connection_head;
2390 * Closure for #iterate_channels_cb.
2397 GCT_ChannelIterator iter;
2400 * Closure for @e iter.
2407 * Helper function for #GCT_iterate_channels.
2409 * @param cls the `struct ChanIterCls`
2411 * @param value a `struct CadetChannel`
2412 * @return #GNUNET_OK
2415 iterate_channels_cb (void *cls,
2419 struct ChanIterCls *ctx = cls;
2420 struct CadetChannel *ch = value;
2422 ctx->iter (ctx->iter_cls,
2429 * Iterate over all channels of a tunnel.
2431 * @param t Tunnel whose channels to iterate.
2432 * @param iter Iterator.
2433 * @param iter_cls Closure for @c iter.
2436 GCT_iterate_channels (struct CadetTunnel *t,
2437 GCT_ChannelIterator iter,
2440 struct ChanIterCls ctx;
2443 ctx.iter_cls = iter_cls;
2444 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2445 &iterate_channels_cb,
2452 * Call #GCCH_debug() on a channel.
2454 * @param cls points to the log level to use
2456 * @param value the `struct CadetChannel` to dump
2457 * @return #GNUNET_OK (continue iteration)
2460 debug_channel (void *cls,
2464 const enum GNUNET_ErrorType *level = cls;
2465 struct CadetChannel *ch = value;
2467 GCCH_debug (ch, *level);
2472 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2476 * Log all possible info about the tunnel state.
2478 * @param t Tunnel to debug.
2479 * @param level Debug level to use.
2482 GCT_debug (const struct CadetTunnel *t,
2483 enum GNUNET_ErrorType level)
2485 struct CadetTConnection *iter_c;
2488 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2490 __FILE__, __FUNCTION__, __LINE__);
2495 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2497 estate2s (t->estate),
2499 t->num_connections);
2500 #if DUMP_KEYS_TO_STDERR
2501 ax_debug (t->ax, level);
2505 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2509 "TTT connections:\n");
2510 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2511 GCC_debug (iter_c->cc,
2515 "TTT TUNNEL END\n");
2519 /* end of gnunet-service-cadet-new_tunnels.c */