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 * Called when either we have a new connection, or a new message in the
542 * queue, or some existing connection has transmission capacity. Looks
543 * at our message queue and if there is a message, picks a connection
546 * @param cls the `struct CadetTunnel` to process messages on
549 trigger_transmissions (void *cls);
552 /* ************************************** start core crypto ***************************** */
556 * Create a new Axolotl ephemeral (ratchet) key.
558 * @param ax key material to update
561 new_ephemeral (struct CadetTunnelAxolotl *ax)
563 GNUNET_free_non_null (ax->DHRs);
564 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
571 * @param plaintext Content to HMAC.
572 * @param size Size of @c plaintext.
573 * @param iv Initialization vector for the message.
574 * @param key Key to use.
575 * @param hmac[out] Destination to store the HMAC.
578 t_hmac (const void *plaintext,
581 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
582 struct GNUNET_ShortHashCode *hmac)
584 static const char ctx[] = "cadet authentication key";
585 struct GNUNET_CRYPTO_AuthKey auth_key;
586 struct GNUNET_HashCode hash;
588 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
594 /* Two step: GNUNET_ShortHash is only 256 bits,
595 GNUNET_HashCode is 512, so we truncate. */
596 GNUNET_CRYPTO_hmac (&auth_key,
609 * @param key Key to use.
610 * @param hash[out] Resulting HMAC.
611 * @param source Source key material (data to HMAC).
612 * @param len Length of @a source.
615 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
616 struct GNUNET_HashCode *hash,
620 static const char ctx[] = "axolotl HMAC-HASH";
621 struct GNUNET_CRYPTO_AuthKey auth_key;
623 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
627 GNUNET_CRYPTO_hmac (&auth_key,
635 * Derive a symmetric encryption key from an HMAC-HASH.
637 * @param key Key to use for the HMAC.
638 * @param[out] out Key to generate.
639 * @param source Source key material (data to HMAC).
640 * @param len Length of @a source.
643 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
644 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
648 static const char ctx[] = "axolotl derive key";
649 struct GNUNET_HashCode h;
655 GNUNET_CRYPTO_kdf (out, sizeof (*out),
663 * Encrypt data with the axolotl tunnel key.
665 * @param ax key material to use.
666 * @param dst Destination with @a size bytes for the encrypted data.
667 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
668 * @param size Size of the buffers at @a src and @a dst
671 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
676 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
677 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
680 ax->ratchet_counter++;
681 if ( (GNUNET_YES == ax->ratchet_allowed) &&
682 ( (ratchet_messages <= ax->ratchet_counter) ||
683 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
685 ax->ratchet_flag = GNUNET_YES;
687 if (GNUNET_YES == ax->ratchet_flag)
689 /* Advance ratchet */
690 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
691 struct GNUNET_HashCode dh;
692 struct GNUNET_HashCode hmac;
693 static const char ctx[] = "axolotl ratchet";
698 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
699 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
702 t_ax_hmac_hash (&ax->RK,
706 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
708 &hmac, sizeof (hmac),
716 ax->ratchet_flag = GNUNET_NO;
717 ax->ratchet_allowed = GNUNET_NO;
718 ax->ratchet_counter = 0;
719 ax->ratchet_expiration
720 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
724 t_hmac_derive_key (&ax->CKs,
728 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
733 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
738 GNUNET_assert (size == out_size);
739 t_hmac_derive_key (&ax->CKs,
747 * Decrypt data with the axolotl tunnel key.
749 * @param ax key material to use.
750 * @param dst Destination for the decrypted data, must contain @a size bytes.
751 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
752 * @param size Size of the @a src and @a dst buffers
755 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
760 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
761 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
764 t_hmac_derive_key (&ax->CKr,
768 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
772 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
773 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
778 GNUNET_assert (out_size == size);
779 t_hmac_derive_key (&ax->CKr,
787 * Encrypt header with the axolotl header key.
789 * @param ax key material to use.
790 * @param msg Message whose header to encrypt.
793 t_h_encrypt (struct CadetTunnelAxolotl *ax,
794 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
796 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
799 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
803 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header.Ns,
804 sizeof (struct GNUNET_CADET_AxHeader),
808 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
813 * Decrypt header with the current axolotl header key.
815 * @param ax key material to use.
816 * @param src Message whose header to decrypt.
817 * @param dst Where to decrypt header to.
820 t_h_decrypt (struct CadetTunnelAxolotl *ax,
821 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
822 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
824 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
827 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
831 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
832 sizeof (struct GNUNET_CADET_AxHeader),
836 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
841 * Delete a key from the list of skipped keys.
843 * @param ax key material to delete @a key from.
844 * @param key Key to delete.
847 delete_skipped_key (struct CadetTunnelAxolotl *ax,
848 struct CadetTunnelSkippedKey *key)
850 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
859 * Decrypt and verify data with the appropriate tunnel key and verify that the
860 * data has not been altered since it was sent by the remote peer.
862 * @param ax key material to use.
863 * @param dst Destination for the plaintext.
864 * @param src Source of the message. Can overlap with @c dst.
865 * @param size Size of the message.
866 * @return Size of the decrypted data, -1 if an error was encountered.
869 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
871 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
874 struct CadetTunnelSkippedKey *key;
875 struct GNUNET_ShortHashCode *hmac;
876 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
877 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
878 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
884 LOG (GNUNET_ERROR_TYPE_DEBUG,
885 "Trying skipped keys\n");
886 hmac = &plaintext_header.hmac;
887 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
889 /* Find a correct Header Key */
891 for (key = ax->skipped_head; NULL != key; key = key->next)
893 t_hmac (&src->ax_header,
894 sizeof (struct GNUNET_CADET_AxHeader) + esize,
898 if (0 == memcmp (hmac,
909 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
910 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
911 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
912 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
915 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
919 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
920 sizeof (struct GNUNET_CADET_AxHeader),
923 &plaintext_header.ax_header.Ns);
924 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
926 /* Find the correct message key */
927 N = ntohl (plaintext_header.ax_header.Ns);
928 while ( (NULL != key) &&
931 if ( (NULL == key) ||
932 (0 != memcmp (&key->HK,
934 sizeof (*valid_HK))) )
937 /* Decrypt payload */
938 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
943 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
948 delete_skipped_key (ax,
955 * Delete a key from the list of skipped keys.
957 * @param ax key material to delete from.
958 * @param HKr Header Key to use.
961 store_skipped_key (struct CadetTunnelAxolotl *ax,
962 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
964 struct CadetTunnelSkippedKey *key;
966 key = GNUNET_new (struct CadetTunnelSkippedKey);
967 key->timestamp = GNUNET_TIME_absolute_get ();
970 t_hmac_derive_key (&ax->CKr,
974 t_hmac_derive_key (&ax->CKr,
978 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
987 * Stage skipped AX keys and calculate the message key.
988 * Stores each HK and MK for skipped messages.
990 * @param ax key material to use
991 * @param HKr Header key.
992 * @param Np Received meesage number.
993 * @return #GNUNET_OK if keys were stored.
994 * #GNUNET_SYSERR if an error ocurred (Np not expected).
997 store_ax_keys (struct CadetTunnelAxolotl *ax,
998 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1004 LOG (GNUNET_ERROR_TYPE_DEBUG,
1005 "Storing skipped keys [%u, %u)\n",
1008 if (MAX_KEY_GAP < gap)
1010 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1011 /* TODO: start new key exchange on return */
1012 GNUNET_break_op (0);
1013 LOG (GNUNET_ERROR_TYPE_WARNING,
1014 "Got message %u, expected %u+\n",
1017 return GNUNET_SYSERR;
1021 /* Delayed message: don't store keys, flag to try old keys. */
1022 return GNUNET_SYSERR;
1026 store_skipped_key (ax,
1029 while (ax->skipped > MAX_SKIPPED_KEYS)
1030 delete_skipped_key (ax,
1037 * Decrypt and verify data with the appropriate tunnel key and verify that the
1038 * data has not been altered since it was sent by the remote peer.
1040 * @param ax key material to use
1041 * @param dst Destination for the plaintext.
1042 * @param src Source of the message. Can overlap with @c dst.
1043 * @param size Size of the message.
1044 * @return Size of the decrypted data, -1 if an error was encountered.
1047 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1049 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1052 struct GNUNET_ShortHashCode msg_hmac;
1053 struct GNUNET_HashCode hmac;
1054 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1057 size_t esize; /* Size of encryped payload */
1059 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1061 /* Try current HK */
1062 t_hmac (&src->ax_header,
1063 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1066 if (0 != memcmp (&msg_hmac,
1070 static const char ctx[] = "axolotl ratchet";
1071 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1072 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1073 struct GNUNET_HashCode dh;
1074 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1077 t_hmac (&src->ax_header,
1078 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1082 if (0 != memcmp (&msg_hmac,
1086 /* Try the skipped keys, if that fails, we're out of luck. */
1087 return try_old_ax_keys (ax,
1097 Np = ntohl (plaintext_header.ax_header.Ns);
1098 PNp = ntohl (plaintext_header.ax_header.PNs);
1099 DHRp = &plaintext_header.ax_header.DHRs;
1104 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1105 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1108 t_ax_hmac_hash (&ax->RK,
1111 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1113 &hmac, sizeof (hmac),
1116 /* Commit "purported" keys */
1122 ax->ratchet_allowed = GNUNET_YES;
1129 Np = ntohl (plaintext_header.ax_header.Ns);
1130 PNp = ntohl (plaintext_header.ax_header.PNs);
1132 if ( (Np != ax->Nr) &&
1133 (GNUNET_OK != store_ax_keys (ax,
1137 /* Try the skipped keys, if that fails, we're out of luck. */
1138 return try_old_ax_keys (ax,
1154 * Our tunnel became ready for the first time, notify channels
1155 * that have been waiting.
1157 * @param cls our tunnel, not used
1158 * @param key unique ID of the channel, not used
1159 * @param value the `struct CadetChannel` to notify
1160 * @return #GNUNET_OK (continue to iterate)
1163 notify_tunnel_up_cb (void *cls,
1167 struct CadetChannel *ch = value;
1169 GCCH_tunnel_up (ch);
1175 * Change the tunnel encryption state.
1176 * If the encryption state changes to OK, stop the rekey task.
1178 * @param t Tunnel whose encryption state to change, or NULL.
1179 * @param state New encryption state.
1182 GCT_change_estate (struct CadetTunnel *t,
1183 enum CadetTunnelEState state)
1185 enum CadetTunnelEState old = t->estate;
1188 LOG (GNUNET_ERROR_TYPE_DEBUG,
1189 "Tunnel %s estate changed from %d to %d\n",
1194 if ( (CADET_TUNNEL_KEY_OK != old) &&
1195 (CADET_TUNNEL_KEY_OK == t->estate) )
1197 if (NULL != t->kx_task)
1199 GNUNET_SCHEDULER_cancel (t->kx_task);
1202 if (CADET_TUNNEL_KEY_REKEY != old)
1204 /* notify all channels that have been waiting */
1205 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1206 ¬ify_tunnel_up_cb,
1210 /* FIXME: schedule rekey task! */
1216 * Send a KX message.
1218 * FIXME: does not take care of sender-authentication yet!
1220 * @param t Tunnel on which to send it.
1221 * @param force_reply Force the other peer to reply with a KX message.
1224 send_kx (struct CadetTunnel *t,
1227 struct CadetTunnelAxolotl *ax = &t->ax;
1228 struct CadetTConnection *ct;
1229 struct CadetConnection *cc;
1230 struct GNUNET_MQ_Envelope *env;
1231 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1232 enum GNUNET_CADET_KX_Flags flags;
1234 ct = get_ready_connection (t);
1237 LOG (GNUNET_ERROR_TYPE_DEBUG,
1238 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1243 LOG (GNUNET_ERROR_TYPE_DEBUG,
1244 "Sending KX on tunnel %s using connection %s\n",
1248 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1249 env = GNUNET_MQ_msg (msg,
1250 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1251 flags = GNUNET_CADET_KX_FLAG_NONE;
1252 if (GNUNET_YES == force_reply)
1253 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1254 msg->flags = htonl (flags);
1255 msg->cid = *GCC_get_id (cc);
1256 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1257 &msg->ephemeral_key);
1258 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1260 ct->is_ready = GNUNET_NO;
1263 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1264 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1265 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1266 GCT_change_estate (t,
1267 CADET_TUNNEL_KEY_SENT);
1272 * Handle KX message.
1274 * FIXME: sender-authentication in KX is missing!
1276 * @param ct connection/tunnel combo that received encrypted message
1277 * @param msg the key exchange message
1280 GCT_handle_kx (struct CadetTConnection *ct,
1281 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1283 struct CadetTunnel *t = ct->t;
1284 struct CadetTunnelAxolotl *ax = &t->ax;
1285 struct GNUNET_HashCode key_material[3];
1286 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1287 const char salt[] = "CADET Axolotl salt";
1288 const struct GNUNET_PeerIdentity *pid;
1291 pid = GCP_get_id (t->destination);
1292 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1294 am_I_alice = GNUNET_YES;
1295 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1297 am_I_alice = GNUNET_NO;
1300 GNUNET_break_op (0);
1304 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1306 if (NULL != t->kx_task)
1308 GNUNET_SCHEDULER_cancel (t->kx_task);
1315 if (0 == memcmp (&ax->DHRr,
1317 sizeof (msg->ratchet_key)))
1319 LOG (GNUNET_ERROR_TYPE_DEBUG,
1320 " known ratchet key, exit\n");
1324 ax->DHRr = msg->ratchet_key;
1327 if (GNUNET_YES == am_I_alice)
1329 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1330 &msg->ephemeral_key, /* B0 */
1335 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1336 &pid->public_key, /* A */
1341 if (GNUNET_YES == am_I_alice)
1343 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1344 &pid->public_key, /* B */
1349 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1350 &msg->ephemeral_key, /* B0 */
1357 /* (This is the triple-DH, we could probably safely skip this,
1358 as A0/B0 are already in the key material.) */
1359 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1360 &msg->ephemeral_key, /* B0 or A0 */
1364 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1365 salt, sizeof (salt),
1366 &key_material, sizeof (key_material),
1369 if (0 == memcmp (&ax->RK,
1373 LOG (GNUNET_ERROR_TYPE_INFO,
1374 " known handshake key, exit\n");
1377 LOG (GNUNET_ERROR_TYPE_DEBUG,
1378 "Handling KX message for tunnel %s\n",
1382 if (GNUNET_YES == am_I_alice)
1388 ax->ratchet_flag = GNUNET_YES;
1396 ax->ratchet_flag = GNUNET_NO;
1397 ax->ratchet_allowed = GNUNET_NO;
1398 ax->ratchet_counter = 0;
1399 ax->ratchet_expiration
1400 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1409 case CADET_TUNNEL_KEY_UNINITIALIZED:
1410 GCT_change_estate (t,
1411 CADET_TUNNEL_KEY_PING);
1413 case CADET_TUNNEL_KEY_SENT:
1414 /* Got a response to us sending our key; now
1415 we can start transmitting! */
1416 GCT_change_estate (t,
1417 CADET_TUNNEL_KEY_OK);
1418 if (NULL != t->send_task)
1419 GNUNET_SCHEDULER_cancel (t->send_task);
1420 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1423 case CADET_TUNNEL_KEY_PING:
1424 /* Got a key yet again; need encrypted payload to advance */
1426 case CADET_TUNNEL_KEY_OK:
1427 /* Did not expect a key, but so what. */
1429 case CADET_TUNNEL_KEY_REKEY:
1430 /* Got a key yet again; need encrypted payload to advance */
1436 /* ************************************** end core crypto ***************************** */
1440 * Compute the next free channel tunnel number for this tunnel.
1442 * @param t the tunnel
1443 * @return unused number that can uniquely identify a channel in the tunnel
1445 static struct GNUNET_CADET_ChannelTunnelNumber
1446 get_next_free_ctn (struct CadetTunnel *t)
1448 #define HIGH_BIT 0x8000000
1449 struct GNUNET_CADET_ChannelTunnelNumber ret;
1454 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1455 GCP_get_id (GCT_get_destination (t)));
1461 GNUNET_assert (0); // loopback must never go here!
1462 ctn = ntohl (t->next_ctn.cn);
1464 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1467 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1469 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1470 ret.cn = ntohl (ctn);
1476 * Add a channel to a tunnel, and notify channel that we are ready
1477 * for transmission if we are already up. Otherwise that notification
1478 * will be done later in #notify_tunnel_up_cb().
1482 * @return unique number identifying @a ch within @a t
1484 struct GNUNET_CADET_ChannelTunnelNumber
1485 GCT_add_channel (struct CadetTunnel *t,
1486 struct CadetChannel *ch)
1488 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1490 ctn = get_next_free_ctn (t);
1491 GNUNET_assert (GNUNET_YES ==
1492 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1495 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1496 LOG (GNUNET_ERROR_TYPE_DEBUG,
1497 "Adding channel %s to tunnel %s\n",
1500 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1501 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1502 GCCH_tunnel_up (ch);
1508 * We lost a connection, remove it from our list and clean up
1509 * the connection object itself.
1511 * @param ct binding of connection to tunnel of the connection that was lost.
1514 GCT_connection_lost (struct CadetTConnection *ct)
1516 struct CadetTunnel *t = ct->t;
1518 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1526 * This tunnel is no longer used, destroy it.
1528 * @param cls the idle tunnel
1531 destroy_tunnel (void *cls)
1533 struct CadetTunnel *t = cls;
1534 struct CadetTConnection *ct;
1535 struct CadetTunnelQueueEntry *tq;
1537 t->destroy_task = NULL;
1538 LOG (GNUNET_ERROR_TYPE_DEBUG,
1539 "Destroying idle tunnel %s\n",
1541 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1542 while (NULL != (ct = t->connection_head))
1544 struct CadetConnection *cc;
1546 GNUNET_assert (ct->t == t);
1548 GCT_connection_lost (ct);
1549 GCC_destroy_without_tunnel (cc);
1551 while (NULL != (tq = t->tq_head))
1553 if (NULL != tq->cont)
1554 tq->cont (tq->cont_cls);
1555 GCT_send_cancel (tq);
1557 GCP_drop_tunnel (t->destination,
1559 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1560 if (NULL != t->maintain_connections_task)
1562 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1563 t->maintain_connections_task = NULL;
1565 if (NULL != t->send_task)
1567 GNUNET_SCHEDULER_cancel (t->send_task);
1568 t->send_task = NULL;
1570 if (NULL != t->kx_task)
1572 GNUNET_SCHEDULER_cancel (t->kx_task);
1575 GNUNET_MST_destroy (t->mst);
1576 GNUNET_MQ_destroy (t->mq);
1577 while (NULL != t->ax.skipped_head)
1578 delete_skipped_key (&t->ax,
1579 t->ax.skipped_head);
1580 GNUNET_assert (0 == t->ax.skipped);
1581 GNUNET_free_non_null (t->ax.kx_0);
1582 GNUNET_free_non_null (t->ax.DHRs);
1588 * Remove a channel from a tunnel.
1592 * @param ctn unique number identifying @a ch within @a t
1595 GCT_remove_channel (struct CadetTunnel *t,
1596 struct CadetChannel *ch,
1597 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1599 LOG (GNUNET_ERROR_TYPE_DEBUG,
1600 "Removing channel %s from tunnel %s\n",
1603 GNUNET_assert (GNUNET_YES ==
1604 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1608 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1610 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1618 * Destroy remaining channels during shutdown.
1620 * @param cls the `struct CadetTunnel` of the channel
1621 * @param key key of the channel
1622 * @param value the `struct CadetChannel`
1623 * @return #GNUNET_OK (continue to iterate)
1626 destroy_remaining_channels (void *cls,
1630 struct CadetChannel *ch = value;
1632 GCCH_handle_remote_destroy (ch);
1638 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1640 * @param t tunnel to destroy
1643 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1645 GNUNET_assert (GNUNET_YES == shutting_down);
1646 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1647 &destroy_remaining_channels,
1650 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1651 if (NULL != t->destroy_task)
1653 GNUNET_SCHEDULER_cancel (t->destroy_task);
1654 t->destroy_task = NULL;
1661 * It's been a while, we should try to redo the KX, if we can.
1663 * @param cls the `struct CadetTunnel` to do KX for.
1666 retry_kx (void *cls)
1668 struct CadetTunnel *t = cls;
1672 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1673 (CADET_TUNNEL_KEY_SENT == t->estate) )
1680 * Send normal payload from queue in @a t via connection @a ct.
1681 * Does nothing if our payload queue is empty.
1683 * @param t tunnel to send data from
1684 * @param ct connection to use for transmission (is ready)
1687 try_send_normal_payload (struct CadetTunnel *t,
1688 struct CadetTConnection *ct)
1690 struct CadetTunnelQueueEntry *tq;
1692 GNUNET_assert (GNUNET_YES == ct->is_ready);
1696 /* no messages pending right now */
1697 LOG (GNUNET_ERROR_TYPE_DEBUG,
1698 "Not sending payload of %s on ready %s (nothing pending)\n",
1703 /* ready to send message 'tq' on tunnel 'ct' */
1704 GNUNET_assert (t == tq->t);
1705 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1708 if (NULL != tq->cid)
1709 *tq->cid = *GCC_get_id (ct->cc);
1710 ct->is_ready = GNUNET_NO;
1711 LOG (GNUNET_ERROR_TYPE_DEBUG,
1712 "Sending payload of %s on %s\n",
1715 GCC_transmit (ct->cc,
1717 if (NULL != tq->cont)
1718 tq->cont (tq->cont_cls);
1724 * A connection is @a is_ready for transmission. Looks at our message
1725 * queue and if there is a message, sends it out via the connection.
1727 * @param cls the `struct CadetTConnection` that is @a is_ready
1728 * @param is_ready #GNUNET_YES if connection are now ready,
1729 * #GNUNET_NO if connection are no longer ready
1732 connection_ready_cb (void *cls,
1735 struct CadetTConnection *ct = cls;
1736 struct CadetTunnel *t = ct->t;
1738 if (GNUNET_NO == is_ready)
1740 LOG (GNUNET_ERROR_TYPE_DEBUG,
1741 "Connection %s no longer ready for tunnel %s\n",
1744 ct->is_ready = GNUNET_NO;
1747 ct->is_ready = GNUNET_YES;
1748 LOG (GNUNET_ERROR_TYPE_DEBUG,
1749 "Connection %s now ready for tunnel %s in state %s\n",
1752 estate2s (t->estate));
1755 case CADET_TUNNEL_KEY_UNINITIALIZED:
1759 case CADET_TUNNEL_KEY_SENT:
1760 case CADET_TUNNEL_KEY_PING:
1761 /* opportunity to #retry_kx() starts now, schedule job */
1762 if (NULL == t->kx_task)
1765 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1770 case CADET_TUNNEL_KEY_OK:
1771 try_send_normal_payload (t,
1774 case CADET_TUNNEL_KEY_REKEY:
1777 t->estate = CADET_TUNNEL_KEY_OK;
1784 * Called when either we have a new connection, or a new message in the
1785 * queue, or some existing connection has transmission capacity. Looks
1786 * at our message queue and if there is a message, picks a connection
1789 * @param cls the `struct CadetTunnel` to process messages on
1792 trigger_transmissions (void *cls)
1794 struct CadetTunnel *t = cls;
1795 struct CadetTConnection *ct;
1797 t->send_task = NULL;
1798 if (NULL == t->tq_head)
1799 return; /* no messages pending right now */
1800 ct = get_ready_connection (t);
1802 return; /* no connections ready */
1803 try_send_normal_payload (t,
1809 * Consider using the path @a p for the tunnel @a t.
1810 * The tunnel destination is at offset @a off in path @a p.
1812 * @param cls our tunnel
1813 * @param path a path to our destination
1814 * @param off offset of the destination on path @a path
1815 * @return #GNUNET_YES (should keep iterating)
1818 consider_path_cb (void *cls,
1819 struct CadetPeerPath *path,
1822 struct CadetTunnel *t = cls;
1823 unsigned int min_length = UINT_MAX;
1824 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1825 struct CadetTConnection *ct;
1827 /* Check if we care about the new path. */
1828 for (ct = t->connection_head;
1832 struct CadetPeerPath *ps;
1834 ps = GCC_get_path (ct->cc);
1837 LOG (GNUNET_ERROR_TYPE_DEBUG,
1838 "Ignoring duplicate path %s for tunnel %s.\n",
1841 return GNUNET_YES; /* duplicate */
1843 min_length = GNUNET_MIN (min_length,
1844 GCPP_get_length (ps));
1845 max_desire = GNUNET_MAX (max_desire,
1846 GCPP_get_desirability (ps));
1849 /* FIXME: not sure we should really just count
1850 'num_connections' here, as they may all have
1851 consistently failed to connect. */
1853 /* We iterate by increasing path length; if we have enough paths and
1854 this one is more than twice as long than what we are currently
1855 using, then ignore all of these super-long ones! */
1856 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1857 (min_length * 2 < off) )
1859 LOG (GNUNET_ERROR_TYPE_DEBUG,
1860 "Ignoring paths of length %u, they are way too long.\n",
1864 /* If we have enough paths and this one looks no better, ignore it. */
1865 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1866 (min_length < GCPP_get_length (path)) &&
1867 (max_desire > GCPP_get_desirability (path)) )
1869 LOG (GNUNET_ERROR_TYPE_DEBUG,
1870 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1871 GCPP_get_length (path),
1872 (unsigned long long) GCPP_get_desirability (path),
1873 GCP_2s (t->destination));
1877 /* Path is interesting (better by some metric, or we don't have
1878 enough paths yet). */
1879 ct = GNUNET_new (struct CadetTConnection);
1880 ct->created = GNUNET_TIME_absolute_get ();
1882 ct->cc = GCC_create (t->destination,
1885 &connection_ready_cb,
1887 /* FIXME: schedule job to kill connection (and path?) if it takes
1888 too long to get ready! (And track performance data on how long
1889 other connections took with the tunnel!)
1890 => Note: to be done within 'connection'-logic! */
1891 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1894 t->num_connections++;
1895 LOG (GNUNET_ERROR_TYPE_DEBUG,
1896 "Found interesting path %s for tunnel %s, created connection %s\n",
1905 * Function called to maintain the connections underlying our tunnel.
1906 * Tries to maintain (incl. tear down) connections for the tunnel, and
1907 * if there is a significant change, may trigger transmissions.
1909 * Basically, needs to check if there are connections that perform
1910 * badly, and if so eventually kill them and trigger a replacement.
1911 * The strategy is to open one more connection than
1912 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1913 * least-performing one, and then inquire for new ones.
1915 * @param cls the `struct CadetTunnel`
1918 maintain_connections_cb (void *cls)
1920 struct CadetTunnel *t = cls;
1922 t->maintain_connections_task = NULL;
1923 LOG (GNUNET_ERROR_TYPE_DEBUG,
1924 "Performing connection maintenance for tunnel %s.\n",
1927 (void) GCP_iterate_paths (t->destination,
1931 GNUNET_break (0); // FIXME: implement!
1936 * Consider using the path @a p for the tunnel @a t.
1937 * The tunnel destination is at offset @a off in path @a p.
1939 * @param cls our tunnel
1940 * @param path a path to our destination
1941 * @param off offset of the destination on path @a path
1944 GCT_consider_path (struct CadetTunnel *t,
1945 struct CadetPeerPath *p,
1948 (void) consider_path_cb (t,
1955 * We got a keepalive. Track in statistics.
1957 * @param cls the `struct CadetTunnel` for which we decrypted the message
1958 * @param msg the message we received on the tunnel
1961 handle_plaintext_keepalive (void *cls,
1962 const struct GNUNET_MessageHeader *msg)
1964 struct CadetTunnel *t = cls;
1966 LOG (GNUNET_ERROR_TYPE_DEBUG,
1967 "Received KEEPALIVE on tunnel %s\n",
1969 GNUNET_STATISTICS_update (stats,
1970 "# keepalives received",
1977 * Check that @a msg is well-formed.
1979 * @param cls the `struct CadetTunnel` for which we decrypted the message
1980 * @param msg the message we received on the tunnel
1981 * @return #GNUNET_OK (any variable-size payload goes)
1984 check_plaintext_data (void *cls,
1985 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1992 * We received payload data for a channel. Locate the channel
1993 * and process the data, or return an error if the channel is unknown.
1995 * @param cls the `struct CadetTunnel` for which we decrypted the message
1996 * @param msg the message we received on the tunnel
1999 handle_plaintext_data (void *cls,
2000 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2002 struct CadetTunnel *t = cls;
2003 struct CadetChannel *ch;
2005 ch = lookup_channel (t,
2009 /* We don't know about such a channel, might have been destroyed on our
2010 end in the meantime, or never existed. Send back a DESTROY. */
2011 LOG (GNUNET_ERROR_TYPE_DEBUG,
2012 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2013 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2014 ntohl (msg->ctn.cn));
2015 GCT_send_channel_destroy (t,
2019 GCCH_handle_channel_plaintext_data (ch,
2025 * We received an acknowledgement for data we sent on a channel.
2026 * Locate the channel and process it, or return an error if the
2027 * channel is unknown.
2029 * @param cls the `struct CadetTunnel` for which we decrypted the message
2030 * @param ack the message we received on the tunnel
2033 handle_plaintext_data_ack (void *cls,
2034 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2036 struct CadetTunnel *t = cls;
2037 struct CadetChannel *ch;
2039 ch = lookup_channel (t,
2043 /* We don't know about such a channel, might have been destroyed on our
2044 end in the meantime, or never existed. Send back a DESTROY. */
2045 LOG (GNUNET_ERROR_TYPE_DEBUG,
2046 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2047 ntohl (ack->ctn.cn));
2048 GCT_send_channel_destroy (t,
2052 GCCH_handle_channel_plaintext_data_ack (ch,
2058 * We have received a request to open a channel to a port from
2059 * another peer. Creates the incoming channel.
2061 * @param cls the `struct CadetTunnel` for which we decrypted the message
2062 * @param copen the message we received on the tunnel
2065 handle_plaintext_channel_open (void *cls,
2066 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2068 struct CadetTunnel *t = cls;
2069 struct CadetChannel *ch;
2071 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2072 ntohl (copen->ctn.cn));
2075 LOG (GNUNET_ERROR_TYPE_DEBUG,
2076 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2077 GNUNET_h2s (&copen->port),
2080 GCCH_handle_duplicate_open (ch);
2083 LOG (GNUNET_ERROR_TYPE_DEBUG,
2084 "Receicved channel OPEN on port %s from %s\n",
2085 GNUNET_h2s (&copen->port),
2087 ch = GCCH_channel_incoming_new (t,
2090 ntohl (copen->opt));
2091 GNUNET_assert (GNUNET_OK ==
2092 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2093 ntohl (copen->ctn.cn),
2095 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2100 * Send a DESTROY message via the tunnel.
2102 * @param t the tunnel to transmit over
2103 * @param ctn ID of the channel to destroy
2106 GCT_send_channel_destroy (struct CadetTunnel *t,
2107 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2109 struct GNUNET_CADET_ChannelManageMessage msg;
2111 LOG (GNUNET_ERROR_TYPE_DEBUG,
2112 "Sending DESTORY message for channel ID %u\n",
2114 msg.header.size = htons (sizeof (msg));
2115 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2116 msg.reserved = htonl (0);
2126 * We have received confirmation from the target peer that the
2127 * given channel could be established (the port is open).
2130 * @param cls the `struct CadetTunnel` for which we decrypted the message
2131 * @param cm the message we received on the tunnel
2134 handle_plaintext_channel_open_ack (void *cls,
2135 const struct GNUNET_CADET_ChannelManageMessage *cm)
2137 struct CadetTunnel *t = cls;
2138 struct CadetChannel *ch;
2140 ch = lookup_channel (t,
2144 /* We don't know about such a channel, might have been destroyed on our
2145 end in the meantime, or never existed. Send back a DESTROY. */
2146 LOG (GNUNET_ERROR_TYPE_DEBUG,
2147 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2148 ntohl (cm->ctn.cn));
2149 GCT_send_channel_destroy (t,
2153 LOG (GNUNET_ERROR_TYPE_DEBUG,
2154 "Received channel OPEN_ACK on channel %s from %s\n",
2157 GCCH_handle_channel_open_ack (ch);
2162 * We received a message saying that a channel should be destroyed.
2163 * Pass it on to the correct channel.
2165 * @param cls the `struct CadetTunnel` for which we decrypted the message
2166 * @param cm the message we received on the tunnel
2169 handle_plaintext_channel_destroy (void *cls,
2170 const struct GNUNET_CADET_ChannelManageMessage *cm)
2172 struct CadetTunnel *t = cls;
2173 struct CadetChannel *ch;
2175 ch = lookup_channel (t,
2179 /* We don't know about such a channel, might have been destroyed on our
2180 end in the meantime, or never existed. */
2181 LOG (GNUNET_ERROR_TYPE_DEBUG,
2182 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2183 ntohl (cm->ctn.cn));
2186 LOG (GNUNET_ERROR_TYPE_DEBUG,
2187 "Receicved channel DESTROY on %s from %s\n",
2190 GCCH_handle_remote_destroy (ch);
2195 * Handles a message we decrypted, by injecting it into
2196 * our message queue (which will do the dispatching).
2198 * @param cls the `struct CadetTunnel` that got the message
2199 * @param msg the message
2200 * @return #GNUNET_OK (continue to process)
2203 handle_decrypted (void *cls,
2204 const struct GNUNET_MessageHeader *msg)
2206 struct CadetTunnel *t = cls;
2208 GNUNET_MQ_inject_message (t->mq,
2215 * Function called if we had an error processing
2216 * an incoming decrypted message.
2218 * @param cls the `struct CadetTunnel`
2219 * @param error error code
2222 decrypted_error_cb (void *cls,
2223 enum GNUNET_MQ_Error error)
2225 GNUNET_break_op (0);
2230 * Create a tunnel to @a destionation. Must only be called
2231 * from within #GCP_get_tunnel().
2233 * @param destination where to create the tunnel to
2234 * @return new tunnel to @a destination
2236 struct CadetTunnel *
2237 GCT_create_tunnel (struct CadetPeer *destination)
2239 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2240 struct GNUNET_MQ_MessageHandler handlers[] = {
2241 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2242 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2243 struct GNUNET_MessageHeader,
2245 GNUNET_MQ_hd_var_size (plaintext_data,
2246 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2247 struct GNUNET_CADET_ChannelAppDataMessage,
2249 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2250 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2251 struct GNUNET_CADET_ChannelDataAckMessage,
2253 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2254 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2255 struct GNUNET_CADET_ChannelOpenMessage,
2257 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2258 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2259 struct GNUNET_CADET_ChannelManageMessage,
2261 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2262 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2263 struct GNUNET_CADET_ChannelManageMessage,
2265 GNUNET_MQ_handler_end ()
2268 new_ephemeral (&t->ax);
2269 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2270 t->destination = destination;
2271 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2272 t->maintain_connections_task
2273 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2275 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2280 &decrypted_error_cb,
2282 t->mst = GNUNET_MST_create (&handle_decrypted,
2289 * Add a @a connection to the @a tunnel.
2292 * @param cid connection identifer to use for the connection
2293 * @param path path to use for the connection
2294 * @return #GNUNET_OK on success,
2295 * #GNUNET_SYSERR on failure (duplicate connection)
2298 GCT_add_inbound_connection (struct CadetTunnel *t,
2299 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2300 struct CadetPeerPath *path)
2302 struct CadetTConnection *ct;
2304 ct = GNUNET_new (struct CadetTConnection);
2305 ct->created = GNUNET_TIME_absolute_get ();
2307 ct->cc = GCC_create_inbound (t->destination,
2311 &connection_ready_cb,
2315 LOG (GNUNET_ERROR_TYPE_DEBUG,
2316 "Tunnel %s refused inbound connection %s (duplicate)\n",
2320 return GNUNET_SYSERR;
2322 /* FIXME: schedule job to kill connection (and path?) if it takes
2323 too long to get ready! (And track performance data on how long
2324 other connections took with the tunnel!)
2325 => Note: to be done within 'connection'-logic! */
2326 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2329 t->num_connections++;
2330 LOG (GNUNET_ERROR_TYPE_DEBUG,
2331 "Tunnel %s has new connection %s\n",
2339 * Handle encrypted message.
2341 * @param ct connection/tunnel combo that received encrypted message
2342 * @param msg the encrypted message to decrypt
2345 GCT_handle_encrypted (struct CadetTConnection *ct,
2346 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2348 struct CadetTunnel *t = ct->t;
2349 uint16_t size = ntohs (msg->header.size);
2350 char cbuf [size] GNUNET_ALIGN;
2351 ssize_t decrypted_size;
2353 LOG (GNUNET_ERROR_TYPE_DEBUG,
2354 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2356 (unsigned int) size,
2361 case CADET_TUNNEL_KEY_UNINITIALIZED:
2362 /* We did not even SEND our KX, how can the other peer
2363 send us encrypted data? */
2364 GNUNET_break_op (0);
2366 case CADET_TUNNEL_KEY_SENT:
2367 /* We did not get the KX of the other peer, but that
2368 might have been lost. Ask for KX again. */
2369 GNUNET_STATISTICS_update (stats,
2370 "# received encrypted without KX",
2373 if (NULL != t->kx_task)
2374 GNUNET_SCHEDULER_cancel (t->kx_task);
2375 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2378 case CADET_TUNNEL_KEY_PING:
2379 /* Great, first payload, we might graduate to OK */
2380 case CADET_TUNNEL_KEY_OK:
2381 case CADET_TUNNEL_KEY_REKEY:
2385 GNUNET_STATISTICS_update (stats,
2386 "# received encrypted",
2389 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2394 if (-1 == decrypted_size)
2396 GNUNET_break_op (0);
2397 LOG (GNUNET_ERROR_TYPE_WARNING,
2398 "Tunnel %s failed to decrypt and validate encrypted data\n",
2400 GNUNET_STATISTICS_update (stats,
2401 "# unable to decrypt",
2406 if (CADET_TUNNEL_KEY_PING == t->estate)
2408 GCT_change_estate (t,
2409 CADET_TUNNEL_KEY_OK);
2410 if (NULL != t->send_task)
2411 GNUNET_SCHEDULER_cancel (t->send_task);
2412 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2415 /* The MST will ultimately call #handle_decrypted() on each message. */
2416 GNUNET_break_op (GNUNET_OK ==
2417 GNUNET_MST_from_buffer (t->mst,
2426 * Sends an already built message on a tunnel, encrypting it and
2427 * choosing the best connection if not provided.
2429 * @param message Message to send. Function modifies it.
2430 * @param t Tunnel on which this message is transmitted.
2431 * @param cont Continuation to call once message is really sent.
2432 * @param cont_cls Closure for @c cont.
2433 * @return Handle to cancel message. NULL if @c cont is NULL.
2435 struct CadetTunnelQueueEntry *
2436 GCT_send (struct CadetTunnel *t,
2437 const struct GNUNET_MessageHeader *message,
2438 GNUNET_SCHEDULER_TaskCallback cont,
2441 struct CadetTunnelQueueEntry *tq;
2442 uint16_t payload_size;
2443 struct GNUNET_MQ_Envelope *env;
2444 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2446 payload_size = ntohs (message->size);
2447 LOG (GNUNET_ERROR_TYPE_DEBUG,
2448 "Encrypting %u bytes for tunnel %s\n",
2449 (unsigned int) payload_size,
2451 env = GNUNET_MQ_msg_extra (ax_msg,
2453 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2454 t_ax_encrypt (&t->ax,
2458 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2459 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2460 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2461 &ax_msg->ax_header.DHRs);
2462 t_h_encrypt (&t->ax,
2464 t_hmac (&ax_msg->ax_header,
2465 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2470 tq = GNUNET_malloc (sizeof (*tq));
2473 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2475 tq->cont_cls = cont_cls;
2476 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2479 if (NULL != t->send_task)
2480 GNUNET_SCHEDULER_cancel (t->send_task);
2482 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2489 * Cancel a previously sent message while it's in the queue.
2491 * ONLY can be called before the continuation given to the send
2492 * function is called. Once the continuation is called, the message is
2493 * no longer in the queue!
2495 * @param tq Handle to the queue entry to cancel.
2498 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2500 struct CadetTunnel *t = tq->t;
2502 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2505 GNUNET_MQ_discard (tq->env);
2511 * Iterate over all connections of a tunnel.
2513 * @param t Tunnel whose connections to iterate.
2514 * @param iter Iterator.
2515 * @param iter_cls Closure for @c iter.
2518 GCT_iterate_connections (struct CadetTunnel *t,
2519 GCT_ConnectionIterator iter,
2522 for (struct CadetTConnection *ct = t->connection_head;
2531 * Closure for #iterate_channels_cb.
2538 GCT_ChannelIterator iter;
2541 * Closure for @e iter.
2548 * Helper function for #GCT_iterate_channels.
2550 * @param cls the `struct ChanIterCls`
2552 * @param value a `struct CadetChannel`
2553 * @return #GNUNET_OK
2556 iterate_channels_cb (void *cls,
2560 struct ChanIterCls *ctx = cls;
2561 struct CadetChannel *ch = value;
2563 ctx->iter (ctx->iter_cls,
2570 * Iterate over all channels of a tunnel.
2572 * @param t Tunnel whose channels to iterate.
2573 * @param iter Iterator.
2574 * @param iter_cls Closure for @c iter.
2577 GCT_iterate_channels (struct CadetTunnel *t,
2578 GCT_ChannelIterator iter,
2581 struct ChanIterCls ctx;
2584 ctx.iter_cls = iter_cls;
2585 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2586 &iterate_channels_cb,
2593 * Call #GCCH_debug() on a channel.
2595 * @param cls points to the log level to use
2597 * @param value the `struct CadetChannel` to dump
2598 * @return #GNUNET_OK (continue iteration)
2601 debug_channel (void *cls,
2605 const enum GNUNET_ErrorType *level = cls;
2606 struct CadetChannel *ch = value;
2608 GCCH_debug (ch, *level);
2613 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2617 * Log all possible info about the tunnel state.
2619 * @param t Tunnel to debug.
2620 * @param level Debug level to use.
2623 GCT_debug (const struct CadetTunnel *t,
2624 enum GNUNET_ErrorType level)
2626 struct CadetTConnection *iter_c;
2629 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2631 __FILE__, __FUNCTION__, __LINE__);
2636 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2638 estate2s (t->estate),
2640 t->num_connections);
2641 #if DUMP_KEYS_TO_STDERR
2642 ax_debug (t->ax, level);
2646 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2650 "TTT connections:\n");
2651 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2652 GCC_debug (iter_c->cc,
2656 "TTT TUNNEL END\n");
2660 /* end of gnunet-service-cadet-new_tunnels.c */