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 * + clean up KX logic, including adding sender authentication
29 * + implement rekeying
30 * + check KX estate machine -- make sure it is never stuck!
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 * Maximum number of skipped keys we keep in memory per tunnel.
61 #define MAX_SKIPPED_KEYS 64
64 * Maximum number of keys (and thus ratchet steps) we are willing to
65 * skip before we decide this is either a bogus packet or a DoS-attempt.
67 #define MAX_KEY_GAP 256
71 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
73 struct CadetTunnelSkippedKey
78 struct CadetTunnelSkippedKey *next;
83 struct CadetTunnelSkippedKey *prev;
86 * When was this key stored (for timeout).
88 struct GNUNET_TIME_Absolute timestamp;
93 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
98 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
101 * Key number for a given HK.
108 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
110 struct CadetTunnelAxolotl
113 * A (double linked) list of stored message keys and associated header keys
114 * for "skipped" messages, i.e. messages that have not been
115 * received despite the reception of more recent messages, (head).
117 struct CadetTunnelSkippedKey *skipped_head;
120 * Skipped messages' keys DLL, tail.
122 struct CadetTunnelSkippedKey *skipped_tail;
125 * 32-byte root key which gets updated by DH ratchet.
127 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
130 * 32-byte header key (send).
132 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
135 * 32-byte header key (recv)
137 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
140 * 32-byte next header key (send).
142 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
145 * 32-byte next header key (recv).
147 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
150 * 32-byte chain keys (used for forward-secrecy updating, send).
152 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
155 * 32-byte chain keys (used for forward-secrecy updating, recv).
157 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
160 * ECDH for key exchange (A0 / B0).
162 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
165 * ECDH Ratchet key (send).
167 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
170 * ECDH Ratchet key (recv).
172 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
175 * When does this ratchet expire and a new one is triggered.
177 struct GNUNET_TIME_Absolute ratchet_expiration;
180 * Number of elements in @a skipped_head <-> @a skipped_tail.
182 unsigned int skipped;
185 * Message number (reset to 0 with each new ratchet, next message to send).
190 * Message number (reset to 0 with each new ratchet, next message to recv).
195 * Previous message numbers (# of msgs sent under prev ratchet)
200 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
205 * Number of messages recieved since our last ratchet advance.
206 * - If this counter = 0, we cannot send a new ratchet key in next msg.
207 * - If this counter > 0, we can (but don't yet have to) send a new key.
209 unsigned int ratchet_allowed;
212 * Number of messages recieved since our last ratchet advance.
213 * - If this counter = 0, we cannot send a new ratchet key in next msg.
214 * - If this counter > 0, we can (but don't yet have to) send a new key.
216 unsigned int ratchet_counter;
222 * Struct used to save messages in a non-ready tunnel to send once connected.
224 struct CadetTunnelQueueEntry
227 * We are entries in a DLL
229 struct CadetTunnelQueueEntry *next;
232 * We are entries in a DLL
234 struct CadetTunnelQueueEntry *prev;
237 * Tunnel these messages belong in.
239 struct CadetTunnel *t;
242 * Continuation to call once sent (on the channel layer).
244 GNUNET_SCHEDULER_TaskCallback cont;
247 * Closure for @c cont.
252 * Envelope of message to send follows.
254 struct GNUNET_MQ_Envelope *env;
257 * Where to put the connection identifier into the payload
258 * of the message in @e env once we have it?
260 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
265 * Struct containing all information regarding a tunnel to a peer.
270 * Destination of the tunnel.
272 struct CadetPeer *destination;
275 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
276 * ephemeral key changes.
278 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
281 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
283 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
286 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
288 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
293 struct CadetTunnelAxolotl ax;
296 * Task scheduled if there are no more channels using the tunnel.
298 struct GNUNET_SCHEDULER_Task *destroy_task;
301 * Task to trim connections if too many are present.
303 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
306 * Task to send messages from queue (if possible).
308 struct GNUNET_SCHEDULER_Task *send_task;
311 * Task to trigger KX.
313 struct GNUNET_SCHEDULER_Task *kx_task;
316 * Tokenizer for decrypted messages.
318 struct GNUNET_MessageStreamTokenizer *mst;
321 * Dispatcher for decrypted messages only (do NOT use for sending!).
323 struct GNUNET_MQ_Handle *mq;
326 * DLL of connections that are actively used to reach the destination peer.
328 struct CadetTConnection *connection_head;
331 * DLL of connections that are actively used to reach the destination peer.
333 struct CadetTConnection *connection_tail;
336 * Channels inside this tunnel. Maps
337 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
339 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
342 * Channel ID for the next created channel in this tunnel.
344 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
347 * Queued messages, to transmit once tunnel gets connected.
349 struct CadetTunnelQueueEntry *tq_head;
352 * Queued messages, to transmit once tunnel gets connected.
354 struct CadetTunnelQueueEntry *tq_tail;
357 * How long do we wait until we retry the KX?
359 struct GNUNET_TIME_Relative kx_retry_delay;
362 * When do we try the next KX?
364 struct GNUNET_TIME_Absolute next_kx_attempt;
367 * Number of connections in the @e connection_head DLL.
369 unsigned int num_connections;
372 * Number of entries in the @e tq_head DLL.
377 * State of the tunnel encryption.
379 enum CadetTunnelEState estate;
385 * Get the static string for the peer this tunnel is directed.
389 * @return Static string the destination peer's ID.
392 GCT_2s (const struct CadetTunnel *t)
397 return "Tunnel(NULL)";
398 GNUNET_snprintf (buf,
401 GNUNET_i2s (GCP_get_id (t->destination)));
407 * Get string description for tunnel encryption state.
409 * @param es Tunnel state.
411 * @return String representation.
414 estate2s (enum CadetTunnelEState es)
420 case CADET_TUNNEL_KEY_UNINITIALIZED:
421 return "CADET_TUNNEL_KEY_UNINITIALIZED";
422 case CADET_TUNNEL_KEY_SENT:
423 return "CADET_TUNNEL_KEY_SENT";
424 case CADET_TUNNEL_KEY_PING:
425 return "CADET_TUNNEL_KEY_PING";
426 case CADET_TUNNEL_KEY_OK:
427 return "CADET_TUNNEL_KEY_OK";
428 case CADET_TUNNEL_KEY_REKEY:
429 return "CADET_TUNNEL_KEY_REKEY";
431 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
438 * Return the peer to which this tunnel goes.
441 * @return the destination of the tunnel
444 GCT_get_destination (struct CadetTunnel *t)
446 return t->destination;
451 * Count channels of a tunnel.
453 * @param t Tunnel on which to count.
455 * @return Number of channels.
458 GCT_count_channels (struct CadetTunnel *t)
460 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
465 * Lookup a channel by its @a ctn.
467 * @param t tunnel to look in
468 * @param ctn number of channel to find
469 * @return NULL if channel does not exist
471 struct CadetChannel *
472 lookup_channel (struct CadetTunnel *t,
473 struct GNUNET_CADET_ChannelTunnelNumber ctn)
475 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
481 * Count all created connections of a tunnel. Not necessarily ready connections!
483 * @param t Tunnel on which to count.
485 * @return Number of connections created, either being established or ready.
488 GCT_count_any_connections (struct CadetTunnel *t)
490 return t->num_connections;
495 * Find first connection that is ready in the list of
496 * our connections. Picks ready connections round-robin.
498 * @param t tunnel to search
499 * @return NULL if we have no connection that is ready
501 static struct CadetTConnection *
502 get_ready_connection (struct CadetTunnel *t)
504 for (struct CadetTConnection *pos = t->connection_head;
507 if (GNUNET_YES == pos->is_ready)
509 if (pos != t->connection_tail)
511 /* move 'pos' to the end, so we try other ready connections
512 first next time (round-robin, modulo availability) */
513 GNUNET_CONTAINER_DLL_remove (t->connection_head,
516 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
527 * Get the encryption state of a tunnel.
531 * @return Tunnel's encryption state.
533 enum CadetTunnelEState
534 GCT_get_estate (struct CadetTunnel *t)
541 * Create a new Axolotl ephemeral (ratchet) key.
546 new_ephemeral (struct CadetTunnel *t)
548 GNUNET_free_non_null (t->ax.DHRs);
549 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
555 * Called when either we have a new connection, or a new message in the
556 * queue, or some existing connection has transmission capacity. Looks
557 * at our message queue and if there is a message, picks a connection
560 * @param cls the `struct CadetTunnel` to process messages on
563 trigger_transmissions (void *cls);
566 /* ************************************** start core crypto ***************************** */
572 * @param plaintext Content to HMAC.
573 * @param size Size of @c plaintext.
574 * @param iv Initialization vector for the message.
575 * @param key Key to use.
576 * @param hmac[out] Destination to store the HMAC.
579 t_hmac (const void *plaintext,
582 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
583 struct GNUNET_ShortHashCode *hmac)
585 static const char ctx[] = "cadet authentication key";
586 struct GNUNET_CRYPTO_AuthKey auth_key;
587 struct GNUNET_HashCode hash;
589 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
595 /* Two step: GNUNET_ShortHash is only 256 bits,
596 GNUNET_HashCode is 512, so we truncate. */
597 GNUNET_CRYPTO_hmac (&auth_key,
610 * @param key Key to use.
611 * @param hash[out] Resulting HMAC.
612 * @param source Source key material (data to HMAC).
613 * @param len Length of @a source.
616 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
617 struct GNUNET_HashCode *hash,
621 static const char ctx[] = "axolotl HMAC-HASH";
622 struct GNUNET_CRYPTO_AuthKey auth_key;
624 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
628 GNUNET_CRYPTO_hmac (&auth_key,
636 * Derive a symmetric encryption key from an HMAC-HASH.
638 * @param key Key to use for the HMAC.
639 * @param[out] out Key to generate.
640 * @param source Source key material (data to HMAC).
641 * @param len Length of @a source.
644 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
645 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
649 static const char ctx[] = "axolotl derive key";
650 struct GNUNET_HashCode h;
656 GNUNET_CRYPTO_kdf (out, sizeof (*out),
664 * Encrypt data with the axolotl tunnel key.
666 * @param t Tunnel whose key to use.
667 * @param dst Destination with @a size bytes for the encrypted data.
668 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
669 * @param size Size of the buffers at @a src and @a dst
672 t_ax_encrypt (struct CadetTunnel *t,
677 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
678 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
679 struct CadetTunnelAxolotl *ax;
683 ax->ratchet_counter++;
684 if ( (GNUNET_YES == ax->ratchet_allowed) &&
685 ( (ratchet_messages <= ax->ratchet_counter) ||
686 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
688 ax->ratchet_flag = GNUNET_YES;
690 if (GNUNET_YES == ax->ratchet_flag)
692 /* Advance ratchet */
693 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
694 struct GNUNET_HashCode dh;
695 struct GNUNET_HashCode hmac;
696 static const char ctx[] = "axolotl ratchet";
701 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
702 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
705 t_ax_hmac_hash (&ax->RK,
709 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
711 &hmac, sizeof (hmac),
719 ax->ratchet_flag = GNUNET_NO;
720 ax->ratchet_allowed = GNUNET_NO;
721 ax->ratchet_counter = 0;
722 ax->ratchet_expiration
723 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
727 t_hmac_derive_key (&ax->CKs,
731 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
736 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
741 GNUNET_assert (size == out_size);
742 t_hmac_derive_key (&ax->CKs,
750 * Decrypt data with the axolotl tunnel key.
752 * @param t Tunnel whose key to use.
753 * @param dst Destination for the decrypted data, must contain @a size bytes.
754 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
755 * @param size Size of the @a src and @a dst buffers
758 t_ax_decrypt (struct CadetTunnel *t,
763 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
764 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
765 struct CadetTunnelAxolotl *ax;
769 t_hmac_derive_key (&ax->CKr,
773 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
777 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
778 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
783 GNUNET_assert (out_size == size);
784 t_hmac_derive_key (&ax->CKr,
792 * Encrypt header with the axolotl header key.
794 * @param t Tunnel whose key to use.
795 * @param msg Message whose header to encrypt.
798 t_h_encrypt (struct CadetTunnel *t,
799 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
801 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
802 struct CadetTunnelAxolotl *ax;
806 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
810 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header.Ns,
811 sizeof (struct GNUNET_CADET_AxHeader),
815 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
820 * Decrypt header with the current axolotl header key.
822 * @param t Tunnel whose current ax HK to use.
823 * @param src Message whose header to decrypt.
824 * @param dst Where to decrypt header to.
827 t_h_decrypt (struct CadetTunnel *t,
828 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
829 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
831 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
832 struct CadetTunnelAxolotl *ax;
836 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
840 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
841 sizeof (struct GNUNET_CADET_AxHeader),
845 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
850 * Delete a key from the list of skipped keys.
852 * @param t Tunnel to delete from.
853 * @param key Key to delete.
856 delete_skipped_key (struct CadetTunnel *t,
857 struct CadetTunnelSkippedKey *key)
859 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
868 * Decrypt and verify data with the appropriate tunnel key and verify that the
869 * data has not been altered since it was sent by the remote peer.
871 * @param t Tunnel whose key to use.
872 * @param dst Destination for the plaintext.
873 * @param src Source of the message. Can overlap with @c dst.
874 * @param size Size of the message.
875 * @return Size of the decrypted data, -1 if an error was encountered.
878 try_old_ax_keys (struct CadetTunnel *t,
880 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
883 struct CadetTunnelSkippedKey *key;
884 struct GNUNET_ShortHashCode *hmac;
885 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
886 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
887 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
893 LOG (GNUNET_ERROR_TYPE_DEBUG,
894 "Trying skipped keys\n");
895 hmac = &plaintext_header.hmac;
896 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
898 /* Find a correct Header Key */
900 for (key = t->ax.skipped_head; NULL != key; key = key->next)
902 t_hmac (&src->ax_header,
903 sizeof (struct GNUNET_CADET_AxHeader) + esize,
907 if (0 == memcmp (hmac,
918 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
919 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
920 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
921 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
924 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
928 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
929 sizeof (struct GNUNET_CADET_AxHeader),
932 &plaintext_header.ax_header.Ns);
933 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
935 /* Find the correct message key */
936 N = ntohl (plaintext_header.ax_header.Ns);
937 while ( (NULL != key) &&
940 if ( (NULL == key) ||
941 (0 != memcmp (&key->HK,
943 sizeof (*valid_HK))) )
946 /* Decrypt payload */
947 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
952 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
957 delete_skipped_key (t,
964 * Delete a key from the list of skipped keys.
966 * @param t Tunnel to delete from.
967 * @param HKr Header Key to use.
970 store_skipped_key (struct CadetTunnel *t,
971 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
973 struct CadetTunnelSkippedKey *key;
975 key = GNUNET_new (struct CadetTunnelSkippedKey);
976 key->timestamp = GNUNET_TIME_absolute_get ();
979 t_hmac_derive_key (&t->ax.CKr,
983 t_hmac_derive_key (&t->ax.CKr,
987 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
996 * Stage skipped AX keys and calculate the message key.
997 * Stores each HK and MK for skipped messages.
999 * @param t Tunnel where to stage the keys.
1000 * @param HKr Header key.
1001 * @param Np Received meesage number.
1002 * @return #GNUNET_OK if keys were stored.
1003 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1006 store_ax_keys (struct CadetTunnel *t,
1007 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1012 gap = Np - t->ax.Nr;
1013 LOG (GNUNET_ERROR_TYPE_DEBUG,
1014 "Storing skipped keys [%u, %u)\n",
1017 if (MAX_KEY_GAP < gap)
1019 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1020 /* TODO: start new key exchange on return */
1021 GNUNET_break_op (0);
1022 LOG (GNUNET_ERROR_TYPE_WARNING,
1023 "Got message %u, expected %u+\n",
1026 return GNUNET_SYSERR;
1030 /* Delayed message: don't store keys, flag to try old keys. */
1031 return GNUNET_SYSERR;
1034 while (t->ax.Nr < Np)
1035 store_skipped_key (t,
1038 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1039 delete_skipped_key (t,
1040 t->ax.skipped_tail);
1046 * Decrypt and verify data with the appropriate tunnel key and verify that the
1047 * data has not been altered since it was sent by the remote peer.
1049 * @param t Tunnel whose key to use.
1050 * @param dst Destination for the plaintext.
1051 * @param src Source of the message. Can overlap with @c dst.
1052 * @param size Size of the message.
1053 * @return Size of the decrypted data, -1 if an error was encountered.
1056 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1058 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1061 struct CadetTunnelAxolotl *ax;
1062 struct GNUNET_ShortHashCode msg_hmac;
1063 struct GNUNET_HashCode hmac;
1064 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1067 size_t esize; /* Size of encryped payload */
1069 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1072 /* Try current HK */
1073 t_hmac (&src->ax_header,
1074 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1077 if (0 != memcmp (&msg_hmac,
1081 static const char ctx[] = "axolotl ratchet";
1082 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1083 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1084 struct GNUNET_HashCode dh;
1085 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1088 t_hmac (&src->ax_header,
1089 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1093 if (0 != memcmp (&msg_hmac,
1097 /* Try the skipped keys, if that fails, we're out of luck. */
1098 return try_old_ax_keys (t,
1108 Np = ntohl (plaintext_header.ax_header.Ns);
1109 PNp = ntohl (plaintext_header.ax_header.PNs);
1110 DHRp = &plaintext_header.ax_header.DHRs;
1115 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1116 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1119 t_ax_hmac_hash (&ax->RK,
1122 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1124 &hmac, sizeof (hmac),
1127 /* Commit "purported" keys */
1133 ax->ratchet_allowed = GNUNET_YES;
1140 Np = ntohl (plaintext_header.ax_header.Ns);
1141 PNp = ntohl (plaintext_header.ax_header.PNs);
1143 if ( (Np != ax->Nr) &&
1144 (GNUNET_OK != store_ax_keys (t,
1148 /* Try the skipped keys, if that fails, we're out of luck. */
1149 return try_old_ax_keys (t,
1165 * Our tunnel became ready for the first time, notify channels
1166 * that have been waiting.
1168 * @param cls our tunnel, not used
1169 * @param key unique ID of the channel, not used
1170 * @param value the `struct CadetChannel` to notify
1171 * @return #GNUNET_OK (continue to iterate)
1174 notify_tunnel_up_cb (void *cls,
1178 struct CadetChannel *ch = value;
1180 GCCH_tunnel_up (ch);
1186 * Change the tunnel encryption state.
1187 * If the encryption state changes to OK, stop the rekey task.
1189 * @param t Tunnel whose encryption state to change, or NULL.
1190 * @param state New encryption state.
1193 GCT_change_estate (struct CadetTunnel *t,
1194 enum CadetTunnelEState state)
1196 enum CadetTunnelEState old = t->estate;
1199 LOG (GNUNET_ERROR_TYPE_DEBUG,
1200 "Tunnel %s estate changed from %d to %d\n",
1205 if ( (CADET_TUNNEL_KEY_OK != old) &&
1206 (CADET_TUNNEL_KEY_OK == t->estate) )
1208 if (NULL != t->kx_task)
1210 GNUNET_SCHEDULER_cancel (t->kx_task);
1213 if (CADET_TUNNEL_KEY_REKEY != old)
1215 /* notify all channels that have been waiting */
1216 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1217 ¬ify_tunnel_up_cb,
1221 /* FIXME: schedule rekey task! */
1227 * Send a KX message.
1229 * FIXME: does not take care of sender-authentication yet!
1231 * @param t Tunnel on which to send it.
1232 * @param force_reply Force the other peer to reply with a KX message.
1235 send_kx (struct CadetTunnel *t,
1238 struct CadetTunnelAxolotl *ax = &t->ax;
1239 struct CadetTConnection *ct;
1240 struct CadetConnection *cc;
1241 struct GNUNET_MQ_Envelope *env;
1242 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1243 enum GNUNET_CADET_KX_Flags flags;
1245 ct = get_ready_connection (t);
1248 LOG (GNUNET_ERROR_TYPE_DEBUG,
1249 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1254 LOG (GNUNET_ERROR_TYPE_DEBUG,
1255 "Sending KX on tunnel %s using connection %s\n",
1259 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1260 env = GNUNET_MQ_msg (msg,
1261 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1262 flags = GNUNET_CADET_KX_FLAG_NONE;
1263 if (GNUNET_YES == force_reply)
1264 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1265 msg->flags = htonl (flags);
1266 msg->cid = *GCC_get_id (cc);
1267 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1268 &msg->ephemeral_key);
1269 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1271 ct->is_ready = GNUNET_NO;
1274 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1275 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1276 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1277 GCT_change_estate (t,
1278 CADET_TUNNEL_KEY_SENT);
1283 * Handle KX message.
1285 * FIXME: sender-authentication in KX is missing!
1287 * @param ct connection/tunnel combo that received encrypted message
1288 * @param msg the key exchange message
1291 GCT_handle_kx (struct CadetTConnection *ct,
1292 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1294 struct CadetTunnel *t = ct->t;
1295 struct CadetTunnelAxolotl *ax = &t->ax;
1296 struct GNUNET_HashCode key_material[3];
1297 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1298 const char salt[] = "CADET Axolotl salt";
1299 const struct GNUNET_PeerIdentity *pid;
1302 pid = GCP_get_id (t->destination);
1303 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1305 am_I_alice = GNUNET_YES;
1306 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1308 am_I_alice = GNUNET_NO;
1311 GNUNET_break_op (0);
1315 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1317 if (NULL != t->kx_task)
1319 GNUNET_SCHEDULER_cancel (t->kx_task);
1326 if (0 == memcmp (&ax->DHRr,
1328 sizeof (msg->ratchet_key)))
1330 LOG (GNUNET_ERROR_TYPE_DEBUG,
1331 " known ratchet key, exit\n");
1335 ax->DHRr = msg->ratchet_key;
1338 if (GNUNET_YES == am_I_alice)
1340 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1341 &msg->ephemeral_key, /* B0 */
1346 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1347 &pid->public_key, /* A */
1352 if (GNUNET_YES == am_I_alice)
1354 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1355 &pid->public_key, /* B */
1360 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1361 &msg->ephemeral_key, /* B0 */
1368 /* (This is the triple-DH, we could probably safely skip this,
1369 as A0/B0 are already in the key material.) */
1370 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1371 &msg->ephemeral_key, /* B0 or A0 */
1375 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1376 salt, sizeof (salt),
1377 &key_material, sizeof (key_material),
1380 if (0 == memcmp (&ax->RK,
1384 LOG (GNUNET_ERROR_TYPE_INFO,
1385 " known handshake key, exit\n");
1388 LOG (GNUNET_ERROR_TYPE_DEBUG,
1389 "Handling KX message for tunnel %s\n",
1393 if (GNUNET_YES == am_I_alice)
1399 ax->ratchet_flag = GNUNET_YES;
1407 ax->ratchet_flag = GNUNET_NO;
1408 ax->ratchet_allowed = GNUNET_NO;
1409 ax->ratchet_counter = 0;
1410 ax->ratchet_expiration
1411 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1420 case CADET_TUNNEL_KEY_UNINITIALIZED:
1421 GCT_change_estate (t,
1422 CADET_TUNNEL_KEY_PING);
1424 case CADET_TUNNEL_KEY_SENT:
1425 /* Got a response to us sending our key; now
1426 we can start transmitting! */
1427 GCT_change_estate (t,
1428 CADET_TUNNEL_KEY_OK);
1429 if (NULL != t->send_task)
1430 GNUNET_SCHEDULER_cancel (t->send_task);
1431 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1434 case CADET_TUNNEL_KEY_PING:
1435 /* Got a key yet again; need encrypted payload to advance */
1437 case CADET_TUNNEL_KEY_OK:
1438 /* Did not expect a key, but so what. */
1440 case CADET_TUNNEL_KEY_REKEY:
1441 /* Got a key yet again; need encrypted payload to advance */
1447 /* ************************************** end core crypto ***************************** */
1451 * Compute the next free channel tunnel number for this tunnel.
1453 * @param t the tunnel
1454 * @return unused number that can uniquely identify a channel in the tunnel
1456 static struct GNUNET_CADET_ChannelTunnelNumber
1457 get_next_free_ctn (struct CadetTunnel *t)
1459 #define HIGH_BIT 0x8000000
1460 struct GNUNET_CADET_ChannelTunnelNumber ret;
1465 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1466 GCP_get_id (GCT_get_destination (t)));
1472 GNUNET_assert (0); // loopback must never go here!
1473 ctn = ntohl (t->next_ctn.cn);
1475 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1478 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1480 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1481 ret.cn = ntohl (ctn);
1487 * Add a channel to a tunnel, and notify channel that we are ready
1488 * for transmission if we are already up. Otherwise that notification
1489 * will be done later in #notify_tunnel_up_cb().
1493 * @return unique number identifying @a ch within @a t
1495 struct GNUNET_CADET_ChannelTunnelNumber
1496 GCT_add_channel (struct CadetTunnel *t,
1497 struct CadetChannel *ch)
1499 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1501 ctn = get_next_free_ctn (t);
1502 GNUNET_assert (GNUNET_YES ==
1503 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1506 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1507 LOG (GNUNET_ERROR_TYPE_DEBUG,
1508 "Adding channel %s to tunnel %s\n",
1511 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1512 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1513 GCCH_tunnel_up (ch);
1519 * We lost a connection, remove it from our list and clean up
1520 * the connection object itself.
1522 * @param ct binding of connection to tunnel of the connection that was lost.
1525 GCT_connection_lost (struct CadetTConnection *ct)
1527 struct CadetTunnel *t = ct->t;
1529 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1537 * This tunnel is no longer used, destroy it.
1539 * @param cls the idle tunnel
1542 destroy_tunnel (void *cls)
1544 struct CadetTunnel *t = cls;
1545 struct CadetTConnection *ct;
1546 struct CadetTunnelQueueEntry *tq;
1548 t->destroy_task = NULL;
1549 LOG (GNUNET_ERROR_TYPE_DEBUG,
1550 "Destroying idle tunnel %s\n",
1552 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1553 while (NULL != (ct = t->connection_head))
1555 struct CadetConnection *cc;
1557 GNUNET_assert (ct->t == t);
1559 GCT_connection_lost (ct);
1560 GCC_destroy_without_tunnel (cc);
1562 while (NULL != (tq = t->tq_head))
1564 if (NULL != tq->cont)
1565 tq->cont (tq->cont_cls);
1566 GCT_send_cancel (tq);
1568 GCP_drop_tunnel (t->destination,
1570 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1571 if (NULL != t->maintain_connections_task)
1573 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1574 t->maintain_connections_task = NULL;
1576 if (NULL != t->send_task)
1578 GNUNET_SCHEDULER_cancel (t->send_task);
1579 t->send_task = NULL;
1581 if (NULL != t->kx_task)
1583 GNUNET_SCHEDULER_cancel (t->kx_task);
1586 GNUNET_MST_destroy (t->mst);
1587 GNUNET_MQ_destroy (t->mq);
1588 while (NULL != t->ax.skipped_head)
1589 delete_skipped_key (t,
1590 t->ax.skipped_head);
1591 GNUNET_assert (0 == t->ax.skipped);
1592 GNUNET_free_non_null (t->ax.kx_0);
1593 GNUNET_free_non_null (t->ax.DHRs);
1599 * Remove a channel from a tunnel.
1603 * @param ctn unique number identifying @a ch within @a t
1606 GCT_remove_channel (struct CadetTunnel *t,
1607 struct CadetChannel *ch,
1608 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1610 LOG (GNUNET_ERROR_TYPE_DEBUG,
1611 "Removing channel %s from tunnel %s\n",
1614 GNUNET_assert (GNUNET_YES ==
1615 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1619 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1621 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1629 * Destroy remaining channels during shutdown.
1631 * @param cls the `struct CadetTunnel` of the channel
1632 * @param key key of the channel
1633 * @param value the `struct CadetChannel`
1634 * @return #GNUNET_OK (continue to iterate)
1637 destroy_remaining_channels (void *cls,
1641 struct CadetChannel *ch = value;
1643 GCCH_handle_remote_destroy (ch);
1649 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1651 * @param t tunnel to destroy
1654 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1656 GNUNET_assert (GNUNET_YES == shutting_down);
1657 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1658 &destroy_remaining_channels,
1661 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1662 if (NULL != t->destroy_task)
1664 GNUNET_SCHEDULER_cancel (t->destroy_task);
1665 t->destroy_task = NULL;
1672 * It's been a while, we should try to redo the KX, if we can.
1674 * @param cls the `struct CadetTunnel` to do KX for.
1677 retry_kx (void *cls)
1679 struct CadetTunnel *t = cls;
1683 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1684 (CADET_TUNNEL_KEY_SENT == t->estate) )
1691 * Send normal payload from queue in @a t via connection @a ct.
1692 * Does nothing if our payload queue is empty.
1694 * @param t tunnel to send data from
1695 * @param ct connection to use for transmission (is ready)
1698 try_send_normal_payload (struct CadetTunnel *t,
1699 struct CadetTConnection *ct)
1701 struct CadetTunnelQueueEntry *tq;
1703 GNUNET_assert (GNUNET_YES == ct->is_ready);
1707 /* no messages pending right now */
1708 LOG (GNUNET_ERROR_TYPE_DEBUG,
1709 "Not sending payload of %s on ready %s (nothing pending)\n",
1714 /* ready to send message 'tq' on tunnel 'ct' */
1715 GNUNET_assert (t == tq->t);
1716 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1719 if (NULL != tq->cid)
1720 *tq->cid = *GCC_get_id (ct->cc);
1721 ct->is_ready = GNUNET_NO;
1722 LOG (GNUNET_ERROR_TYPE_DEBUG,
1723 "Sending payload of %s on %s\n",
1726 GCC_transmit (ct->cc,
1728 if (NULL != tq->cont)
1729 tq->cont (tq->cont_cls);
1735 * A connection is @a is_ready for transmission. Looks at our message
1736 * queue and if there is a message, sends it out via the connection.
1738 * @param cls the `struct CadetTConnection` that is @a is_ready
1739 * @param is_ready #GNUNET_YES if connection are now ready,
1740 * #GNUNET_NO if connection are no longer ready
1743 connection_ready_cb (void *cls,
1746 struct CadetTConnection *ct = cls;
1747 struct CadetTunnel *t = ct->t;
1749 if (GNUNET_NO == is_ready)
1751 LOG (GNUNET_ERROR_TYPE_DEBUG,
1752 "Connection %s no longer ready for tunnel %s\n",
1755 ct->is_ready = GNUNET_NO;
1758 ct->is_ready = GNUNET_YES;
1759 LOG (GNUNET_ERROR_TYPE_DEBUG,
1760 "Connection %s now ready for tunnel %s in state %s\n",
1763 estate2s (t->estate));
1766 case CADET_TUNNEL_KEY_UNINITIALIZED:
1770 case CADET_TUNNEL_KEY_SENT:
1771 case CADET_TUNNEL_KEY_PING:
1772 /* opportunity to #retry_kx() starts now, schedule job */
1773 if (NULL == t->kx_task)
1776 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1781 case CADET_TUNNEL_KEY_OK:
1782 try_send_normal_payload (t,
1785 case CADET_TUNNEL_KEY_REKEY:
1788 t->estate = CADET_TUNNEL_KEY_OK;
1795 * Called when either we have a new connection, or a new message in the
1796 * queue, or some existing connection has transmission capacity. Looks
1797 * at our message queue and if there is a message, picks a connection
1800 * @param cls the `struct CadetTunnel` to process messages on
1803 trigger_transmissions (void *cls)
1805 struct CadetTunnel *t = cls;
1806 struct CadetTConnection *ct;
1808 t->send_task = NULL;
1809 if (NULL == t->tq_head)
1810 return; /* no messages pending right now */
1811 ct = get_ready_connection (t);
1813 return; /* no connections ready */
1814 try_send_normal_payload (t,
1820 * Consider using the path @a p for the tunnel @a t.
1821 * The tunnel destination is at offset @a off in path @a p.
1823 * @param cls our tunnel
1824 * @param path a path to our destination
1825 * @param off offset of the destination on path @a path
1826 * @return #GNUNET_YES (should keep iterating)
1829 consider_path_cb (void *cls,
1830 struct CadetPeerPath *path,
1833 struct CadetTunnel *t = cls;
1834 unsigned int min_length = UINT_MAX;
1835 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1836 struct CadetTConnection *ct;
1838 /* Check if we care about the new path. */
1839 for (ct = t->connection_head;
1843 struct CadetPeerPath *ps;
1845 ps = GCC_get_path (ct->cc);
1848 LOG (GNUNET_ERROR_TYPE_DEBUG,
1849 "Ignoring duplicate path %s for tunnel %s.\n",
1852 return GNUNET_YES; /* duplicate */
1854 min_length = GNUNET_MIN (min_length,
1855 GCPP_get_length (ps));
1856 max_desire = GNUNET_MAX (max_desire,
1857 GCPP_get_desirability (ps));
1860 /* FIXME: not sure we should really just count
1861 'num_connections' here, as they may all have
1862 consistently failed to connect. */
1864 /* We iterate by increasing path length; if we have enough paths and
1865 this one is more than twice as long than what we are currently
1866 using, then ignore all of these super-long ones! */
1867 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1868 (min_length * 2 < off) )
1870 LOG (GNUNET_ERROR_TYPE_DEBUG,
1871 "Ignoring paths of length %u, they are way too long.\n",
1875 /* If we have enough paths and this one looks no better, ignore it. */
1876 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1877 (min_length < GCPP_get_length (path)) &&
1878 (max_desire > GCPP_get_desirability (path)) )
1880 LOG (GNUNET_ERROR_TYPE_DEBUG,
1881 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1882 GCPP_get_length (path),
1883 (unsigned long long) GCPP_get_desirability (path),
1884 GCP_2s (t->destination));
1888 /* Path is interesting (better by some metric, or we don't have
1889 enough paths yet). */
1890 ct = GNUNET_new (struct CadetTConnection);
1891 ct->created = GNUNET_TIME_absolute_get ();
1893 ct->cc = GCC_create (t->destination,
1896 &connection_ready_cb,
1898 /* FIXME: schedule job to kill connection (and path?) if it takes
1899 too long to get ready! (And track performance data on how long
1900 other connections took with the tunnel!)
1901 => Note: to be done within 'connection'-logic! */
1902 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1905 t->num_connections++;
1906 LOG (GNUNET_ERROR_TYPE_DEBUG,
1907 "Found interesting path %s for tunnel %s, created connection %s\n",
1916 * Function called to maintain the connections underlying our tunnel.
1917 * Tries to maintain (incl. tear down) connections for the tunnel, and
1918 * if there is a significant change, may trigger transmissions.
1920 * Basically, needs to check if there are connections that perform
1921 * badly, and if so eventually kill them and trigger a replacement.
1922 * The strategy is to open one more connection than
1923 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1924 * least-performing one, and then inquire for new ones.
1926 * @param cls the `struct CadetTunnel`
1929 maintain_connections_cb (void *cls)
1931 struct CadetTunnel *t = cls;
1933 t->maintain_connections_task = NULL;
1934 LOG (GNUNET_ERROR_TYPE_DEBUG,
1935 "Performing connection maintenance for tunnel %s.\n",
1938 (void) GCP_iterate_paths (t->destination,
1942 GNUNET_break (0); // FIXME: implement!
1947 * Consider using the path @a p for the tunnel @a t.
1948 * The tunnel destination is at offset @a off in path @a p.
1950 * @param cls our tunnel
1951 * @param path a path to our destination
1952 * @param off offset of the destination on path @a path
1955 GCT_consider_path (struct CadetTunnel *t,
1956 struct CadetPeerPath *p,
1959 (void) consider_path_cb (t,
1966 * We got a keepalive. Track in statistics.
1968 * @param cls the `struct CadetTunnel` for which we decrypted the message
1969 * @param msg the message we received on the tunnel
1972 handle_plaintext_keepalive (void *cls,
1973 const struct GNUNET_MessageHeader *msg)
1975 struct CadetTunnel *t = cls;
1977 LOG (GNUNET_ERROR_TYPE_DEBUG,
1978 "Received KEEPALIVE on tunnel %s\n",
1980 GNUNET_STATISTICS_update (stats,
1981 "# keepalives received",
1988 * Check that @a msg is well-formed.
1990 * @param cls the `struct CadetTunnel` for which we decrypted the message
1991 * @param msg the message we received on the tunnel
1992 * @return #GNUNET_OK (any variable-size payload goes)
1995 check_plaintext_data (void *cls,
1996 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2003 * We received payload data for a channel. Locate the channel
2004 * and process the data, or return an error if the channel is unknown.
2006 * @param cls the `struct CadetTunnel` for which we decrypted the message
2007 * @param msg the message we received on the tunnel
2010 handle_plaintext_data (void *cls,
2011 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2013 struct CadetTunnel *t = cls;
2014 struct CadetChannel *ch;
2016 ch = lookup_channel (t,
2020 /* We don't know about such a channel, might have been destroyed on our
2021 end in the meantime, or never existed. Send back a DESTROY. */
2022 LOG (GNUNET_ERROR_TYPE_DEBUG,
2023 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2024 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2025 ntohl (msg->ctn.cn));
2026 GCT_send_channel_destroy (t,
2030 GCCH_handle_channel_plaintext_data (ch,
2036 * We received an acknowledgement for data we sent on a channel.
2037 * Locate the channel and process it, or return an error if the
2038 * channel is unknown.
2040 * @param cls the `struct CadetTunnel` for which we decrypted the message
2041 * @param ack the message we received on the tunnel
2044 handle_plaintext_data_ack (void *cls,
2045 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2047 struct CadetTunnel *t = cls;
2048 struct CadetChannel *ch;
2050 ch = lookup_channel (t,
2054 /* We don't know about such a channel, might have been destroyed on our
2055 end in the meantime, or never existed. Send back a DESTROY. */
2056 LOG (GNUNET_ERROR_TYPE_DEBUG,
2057 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2058 ntohl (ack->ctn.cn));
2059 GCT_send_channel_destroy (t,
2063 GCCH_handle_channel_plaintext_data_ack (ch,
2069 * We have received a request to open a channel to a port from
2070 * another peer. Creates the incoming channel.
2072 * @param cls the `struct CadetTunnel` for which we decrypted the message
2073 * @param copen the message we received on the tunnel
2076 handle_plaintext_channel_open (void *cls,
2077 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2079 struct CadetTunnel *t = cls;
2080 struct CadetChannel *ch;
2082 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2083 ntohl (copen->ctn.cn));
2086 LOG (GNUNET_ERROR_TYPE_DEBUG,
2087 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2088 GNUNET_h2s (&copen->port),
2091 GCCH_handle_duplicate_open (ch);
2094 LOG (GNUNET_ERROR_TYPE_DEBUG,
2095 "Receicved channel OPEN on port %s from %s\n",
2096 GNUNET_h2s (&copen->port),
2098 ch = GCCH_channel_incoming_new (t,
2101 ntohl (copen->opt));
2102 GNUNET_assert (GNUNET_OK ==
2103 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2104 ntohl (copen->ctn.cn),
2106 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2111 * Send a DESTROY message via the tunnel.
2113 * @param t the tunnel to transmit over
2114 * @param ctn ID of the channel to destroy
2117 GCT_send_channel_destroy (struct CadetTunnel *t,
2118 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2120 struct GNUNET_CADET_ChannelManageMessage msg;
2122 LOG (GNUNET_ERROR_TYPE_DEBUG,
2123 "Sending DESTORY message for channel ID %u\n",
2125 msg.header.size = htons (sizeof (msg));
2126 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2127 msg.reserved = htonl (0);
2137 * We have received confirmation from the target peer that the
2138 * given channel could be established (the port is open).
2141 * @param cls the `struct CadetTunnel` for which we decrypted the message
2142 * @param cm the message we received on the tunnel
2145 handle_plaintext_channel_open_ack (void *cls,
2146 const struct GNUNET_CADET_ChannelManageMessage *cm)
2148 struct CadetTunnel *t = cls;
2149 struct CadetChannel *ch;
2151 ch = lookup_channel (t,
2155 /* We don't know about such a channel, might have been destroyed on our
2156 end in the meantime, or never existed. Send back a DESTROY. */
2157 LOG (GNUNET_ERROR_TYPE_DEBUG,
2158 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2159 ntohl (cm->ctn.cn));
2160 GCT_send_channel_destroy (t,
2164 LOG (GNUNET_ERROR_TYPE_DEBUG,
2165 "Received channel OPEN_ACK on channel %s from %s\n",
2168 GCCH_handle_channel_open_ack (ch);
2173 * We received a message saying that a channel should be destroyed.
2174 * Pass it on to the correct channel.
2176 * @param cls the `struct CadetTunnel` for which we decrypted the message
2177 * @param cm the message we received on the tunnel
2180 handle_plaintext_channel_destroy (void *cls,
2181 const struct GNUNET_CADET_ChannelManageMessage *cm)
2183 struct CadetTunnel *t = cls;
2184 struct CadetChannel *ch;
2186 ch = lookup_channel (t,
2190 /* We don't know about such a channel, might have been destroyed on our
2191 end in the meantime, or never existed. */
2192 LOG (GNUNET_ERROR_TYPE_DEBUG,
2193 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2194 ntohl (cm->ctn.cn));
2197 LOG (GNUNET_ERROR_TYPE_DEBUG,
2198 "Receicved channel DESTROY on %s from %s\n",
2201 GCCH_handle_remote_destroy (ch);
2206 * Handles a message we decrypted, by injecting it into
2207 * our message queue (which will do the dispatching).
2209 * @param cls the `struct CadetTunnel` that got the message
2210 * @param msg the message
2211 * @return #GNUNET_OK (continue to process)
2214 handle_decrypted (void *cls,
2215 const struct GNUNET_MessageHeader *msg)
2217 struct CadetTunnel *t = cls;
2219 GNUNET_MQ_inject_message (t->mq,
2226 * Function called if we had an error processing
2227 * an incoming decrypted message.
2229 * @param cls the `struct CadetTunnel`
2230 * @param error error code
2233 decrypted_error_cb (void *cls,
2234 enum GNUNET_MQ_Error error)
2236 GNUNET_break_op (0);
2241 * Create a tunnel to @a destionation. Must only be called
2242 * from within #GCP_get_tunnel().
2244 * @param destination where to create the tunnel to
2245 * @return new tunnel to @a destination
2247 struct CadetTunnel *
2248 GCT_create_tunnel (struct CadetPeer *destination)
2250 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2251 struct GNUNET_MQ_MessageHandler handlers[] = {
2252 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2253 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2254 struct GNUNET_MessageHeader,
2256 GNUNET_MQ_hd_var_size (plaintext_data,
2257 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2258 struct GNUNET_CADET_ChannelAppDataMessage,
2260 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2261 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2262 struct GNUNET_CADET_ChannelDataAckMessage,
2264 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2265 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2266 struct GNUNET_CADET_ChannelOpenMessage,
2268 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2269 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2270 struct GNUNET_CADET_ChannelManageMessage,
2272 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2273 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2274 struct GNUNET_CADET_ChannelManageMessage,
2276 GNUNET_MQ_handler_end ()
2280 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2281 t->destination = destination;
2282 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2283 t->maintain_connections_task
2284 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2286 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2291 &decrypted_error_cb,
2293 t->mst = GNUNET_MST_create (&handle_decrypted,
2300 * Add a @a connection to the @a tunnel.
2303 * @param cid connection identifer to use for the connection
2304 * @param path path to use for the connection
2305 * @return #GNUNET_OK on success,
2306 * #GNUNET_SYSERR on failure (duplicate connection)
2309 GCT_add_inbound_connection (struct CadetTunnel *t,
2310 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2311 struct CadetPeerPath *path)
2313 struct CadetTConnection *ct;
2315 ct = GNUNET_new (struct CadetTConnection);
2316 ct->created = GNUNET_TIME_absolute_get ();
2318 ct->cc = GCC_create_inbound (t->destination,
2322 &connection_ready_cb,
2326 LOG (GNUNET_ERROR_TYPE_DEBUG,
2327 "Tunnel %s refused inbound connection %s (duplicate)\n",
2331 return GNUNET_SYSERR;
2333 /* FIXME: schedule job to kill connection (and path?) if it takes
2334 too long to get ready! (And track performance data on how long
2335 other connections took with the tunnel!)
2336 => Note: to be done within 'connection'-logic! */
2337 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2340 t->num_connections++;
2341 LOG (GNUNET_ERROR_TYPE_DEBUG,
2342 "Tunnel %s has new connection %s\n",
2350 * Handle encrypted message.
2352 * @param ct connection/tunnel combo that received encrypted message
2353 * @param msg the encrypted message to decrypt
2356 GCT_handle_encrypted (struct CadetTConnection *ct,
2357 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2359 struct CadetTunnel *t = ct->t;
2360 uint16_t size = ntohs (msg->header.size);
2361 char cbuf [size] GNUNET_ALIGN;
2362 ssize_t decrypted_size;
2364 LOG (GNUNET_ERROR_TYPE_DEBUG,
2365 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2367 (unsigned int) size,
2372 case CADET_TUNNEL_KEY_UNINITIALIZED:
2373 /* We did not even SEND our KX, how can the other peer
2374 send us encrypted data? */
2375 GNUNET_break_op (0);
2377 case CADET_TUNNEL_KEY_SENT:
2378 /* We did not get the KX of the other peer, but that
2379 might have been lost. Ask for KX again. */
2380 GNUNET_STATISTICS_update (stats,
2381 "# received encrypted without KX",
2384 if (NULL != t->kx_task)
2385 GNUNET_SCHEDULER_cancel (t->kx_task);
2386 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2389 case CADET_TUNNEL_KEY_PING:
2390 /* Great, first payload, we might graduate to OK */
2391 case CADET_TUNNEL_KEY_OK:
2392 case CADET_TUNNEL_KEY_REKEY:
2396 GNUNET_STATISTICS_update (stats,
2397 "# received encrypted",
2400 decrypted_size = t_ax_decrypt_and_validate (t,
2405 if (-1 == decrypted_size)
2407 GNUNET_break_op (0);
2408 LOG (GNUNET_ERROR_TYPE_WARNING,
2409 "Tunnel %s failed to decrypt and validate encrypted data\n",
2411 GNUNET_STATISTICS_update (stats,
2412 "# unable to decrypt",
2417 if (CADET_TUNNEL_KEY_PING == t->estate)
2419 GCT_change_estate (t,
2420 CADET_TUNNEL_KEY_OK);
2421 if (NULL != t->send_task)
2422 GNUNET_SCHEDULER_cancel (t->send_task);
2423 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2426 /* The MST will ultimately call #handle_decrypted() on each message. */
2427 GNUNET_break_op (GNUNET_OK ==
2428 GNUNET_MST_from_buffer (t->mst,
2437 * Sends an already built message on a tunnel, encrypting it and
2438 * choosing the best connection if not provided.
2440 * @param message Message to send. Function modifies it.
2441 * @param t Tunnel on which this message is transmitted.
2442 * @param cont Continuation to call once message is really sent.
2443 * @param cont_cls Closure for @c cont.
2444 * @return Handle to cancel message. NULL if @c cont is NULL.
2446 struct CadetTunnelQueueEntry *
2447 GCT_send (struct CadetTunnel *t,
2448 const struct GNUNET_MessageHeader *message,
2449 GNUNET_SCHEDULER_TaskCallback cont,
2452 struct CadetTunnelQueueEntry *tq;
2453 uint16_t payload_size;
2454 struct GNUNET_MQ_Envelope *env;
2455 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2457 payload_size = ntohs (message->size);
2458 LOG (GNUNET_ERROR_TYPE_DEBUG,
2459 "Encrypting %u bytes for tunnel %s\n",
2460 (unsigned int) payload_size,
2462 env = GNUNET_MQ_msg_extra (ax_msg,
2464 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2469 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2470 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2471 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2472 &ax_msg->ax_header.DHRs);
2475 t_hmac (&ax_msg->ax_header,
2476 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2481 tq = GNUNET_malloc (sizeof (*tq));
2484 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2486 tq->cont_cls = cont_cls;
2487 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2490 if (NULL != t->send_task)
2491 GNUNET_SCHEDULER_cancel (t->send_task);
2493 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2500 * Cancel a previously sent message while it's in the queue.
2502 * ONLY can be called before the continuation given to the send
2503 * function is called. Once the continuation is called, the message is
2504 * no longer in the queue!
2506 * @param tq Handle to the queue entry to cancel.
2509 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2511 struct CadetTunnel *t = tq->t;
2513 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2516 GNUNET_MQ_discard (tq->env);
2522 * Iterate over all connections of a tunnel.
2524 * @param t Tunnel whose connections to iterate.
2525 * @param iter Iterator.
2526 * @param iter_cls Closure for @c iter.
2529 GCT_iterate_connections (struct CadetTunnel *t,
2530 GCT_ConnectionIterator iter,
2533 for (struct CadetTConnection *ct = t->connection_head;
2542 * Closure for #iterate_channels_cb.
2549 GCT_ChannelIterator iter;
2552 * Closure for @e iter.
2559 * Helper function for #GCT_iterate_channels.
2561 * @param cls the `struct ChanIterCls`
2563 * @param value a `struct CadetChannel`
2564 * @return #GNUNET_OK
2567 iterate_channels_cb (void *cls,
2571 struct ChanIterCls *ctx = cls;
2572 struct CadetChannel *ch = value;
2574 ctx->iter (ctx->iter_cls,
2581 * Iterate over all channels of a tunnel.
2583 * @param t Tunnel whose channels to iterate.
2584 * @param iter Iterator.
2585 * @param iter_cls Closure for @c iter.
2588 GCT_iterate_channels (struct CadetTunnel *t,
2589 GCT_ChannelIterator iter,
2592 struct ChanIterCls ctx;
2595 ctx.iter_cls = iter_cls;
2596 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2597 &iterate_channels_cb,
2604 * Call #GCCH_debug() on a channel.
2606 * @param cls points to the log level to use
2608 * @param value the `struct CadetChannel` to dump
2609 * @return #GNUNET_OK (continue iteration)
2612 debug_channel (void *cls,
2616 const enum GNUNET_ErrorType *level = cls;
2617 struct CadetChannel *ch = value;
2619 GCCH_debug (ch, *level);
2624 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2628 * Log all possible info about the tunnel state.
2630 * @param t Tunnel to debug.
2631 * @param level Debug level to use.
2634 GCT_debug (const struct CadetTunnel *t,
2635 enum GNUNET_ErrorType level)
2637 struct CadetTConnection *iter_c;
2640 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2642 __FILE__, __FUNCTION__, __LINE__);
2647 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2649 estate2s (t->estate),
2651 t->num_connections);
2652 #if DUMP_KEYS_TO_STDERR
2653 ax_debug (t->ax, level);
2657 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2661 "TTT connections:\n");
2662 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2663 GCC_debug (iter_c->cc,
2667 "TTT TUNNEL END\n");
2671 /* end of gnunet-service-cadet-new_tunnels.c */