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__)
53 * How often do we try to decrypt payload with unverified key
54 * material? Used to limit CPU increase upon receiving bogus
57 #define MAX_UNVERIFIED_ATTEMPTS 16
60 * How long do we wait until tearing down an idle tunnel?
62 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
65 * Maximum number of skipped keys we keep in memory per tunnel.
67 #define MAX_SKIPPED_KEYS 64
70 * Maximum number of keys (and thus ratchet steps) we are willing to
71 * skip before we decide this is either a bogus packet or a DoS-attempt.
73 #define MAX_KEY_GAP 256
77 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
79 struct CadetTunnelSkippedKey
84 struct CadetTunnelSkippedKey *next;
89 struct CadetTunnelSkippedKey *prev;
92 * When was this key stored (for timeout).
94 struct GNUNET_TIME_Absolute timestamp;
99 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
104 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
107 * Key number for a given HK.
114 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
116 struct CadetTunnelAxolotl
119 * A (double linked) list of stored message keys and associated header keys
120 * for "skipped" messages, i.e. messages that have not been
121 * received despite the reception of more recent messages, (head).
123 struct CadetTunnelSkippedKey *skipped_head;
126 * Skipped messages' keys DLL, tail.
128 struct CadetTunnelSkippedKey *skipped_tail;
131 * 32-byte root key which gets updated by DH ratchet.
133 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
136 * 32-byte header key (currently used for sending).
138 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141 * 32-byte header key (currently used for receiving)
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146 * 32-byte next header key (for sending), used once the
147 * ratchet advances. We are sure that the sender has this
148 * key as well only after @e ratchet_allowed is #GNUNET_YES.
150 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
153 * 32-byte next header key (for receiving). To be tried
154 * when decrypting with @e HKr fails and thus the sender
155 * may have advanced the ratchet.
157 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
160 * 32-byte chain keys (used for forward-secrecy) for
161 * sending messages. Updated for every message.
163 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
166 * 32-byte chain keys (used for forward-secrecy) for
167 * receiving messages. Updated for every message. If
168 * messages are skipped, the respective derived MKs
169 * (and the current @HKr) are kept in the @e skipped_head DLL.
171 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
174 * ECDH for key exchange (A0 / B0).
176 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
179 * ECDH Ratchet key (our private key in the current DH).
181 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
184 * ECDH Ratchet key (other peer's public key in the current DH).
186 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
189 * Time when the current ratchet expires and a new one is triggered
190 * (if @e ratchet_allowed is #GNUNET_YES).
192 struct GNUNET_TIME_Absolute ratchet_expiration;
195 * Number of elements in @a skipped_head <-> @a skipped_tail.
197 unsigned int skipped;
200 * Message number (reset to 0 with each new ratchet, next message to send).
205 * Message number (reset to 0 with each new ratchet, next message to recv).
210 * Previous message numbers (# of msgs sent under prev ratchet)
215 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
220 * True (#GNUNET_YES) if we have received a message from the
221 * other peer that uses the keys from our last ratchet step.
222 * This implies that we are again allowed to advance the ratchet,
223 * otherwise we have to wait until the other peer sees our current
224 * ephemeral key and advances first.
226 * #GNUNET_NO if we have advanced the ratched but lack any evidence
227 * that the other peer has noticed this.
232 * Number of messages recieved since our last ratchet advance.
234 * If this counter = 0, we cannot send a new ratchet key in the next
237 * If this counter > 0, we could (but don't have to) send a new key.
239 * Once the @e ratchet_counter is larger than
240 * #ratchet_messages (or @e ratchet_expiration time has past), and
241 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
243 unsigned int ratchet_counter;
249 * Struct used to save messages in a non-ready tunnel to send once connected.
251 struct CadetTunnelQueueEntry
254 * We are entries in a DLL
256 struct CadetTunnelQueueEntry *next;
259 * We are entries in a DLL
261 struct CadetTunnelQueueEntry *prev;
264 * Tunnel these messages belong in.
266 struct CadetTunnel *t;
269 * Continuation to call once sent (on the channel layer).
271 GNUNET_SCHEDULER_TaskCallback cont;
274 * Closure for @c cont.
279 * Envelope of message to send follows.
281 struct GNUNET_MQ_Envelope *env;
284 * Where to put the connection identifier into the payload
285 * of the message in @e env once we have it?
287 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
292 * Struct containing all information regarding a tunnel to a peer.
297 * Destination of the tunnel.
299 struct CadetPeer *destination;
302 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
303 * ephemeral key changes.
305 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
308 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
310 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
313 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
315 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
320 struct CadetTunnelAxolotl ax;
323 * Unverified Axolotl info, used only if we got a fresh KX (not a
324 * KX_AUTH) while our end of the tunnel was still up. In this case,
325 * we keep the fresh KX around but do not put it into action until
326 * we got encrypted payload that assures us of the authenticity of
329 struct CadetTunnelAxolotl *unverified_ax;
332 * Task scheduled if there are no more channels using the tunnel.
334 struct GNUNET_SCHEDULER_Task *destroy_task;
337 * Task to trim connections if too many are present.
339 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
342 * Task to send messages from queue (if possible).
344 struct GNUNET_SCHEDULER_Task *send_task;
347 * Task to trigger KX.
349 struct GNUNET_SCHEDULER_Task *kx_task;
352 * Tokenizer for decrypted messages.
354 struct GNUNET_MessageStreamTokenizer *mst;
357 * Dispatcher for decrypted messages only (do NOT use for sending!).
359 struct GNUNET_MQ_Handle *mq;
362 * DLL of connections that are actively used to reach the destination peer.
364 struct CadetTConnection *connection_head;
367 * DLL of connections that are actively used to reach the destination peer.
369 struct CadetTConnection *connection_tail;
372 * Channels inside this tunnel. Maps
373 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
375 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
378 * Channel ID for the next created channel in this tunnel.
380 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
383 * Queued messages, to transmit once tunnel gets connected.
385 struct CadetTunnelQueueEntry *tq_head;
388 * Queued messages, to transmit once tunnel gets connected.
390 struct CadetTunnelQueueEntry *tq_tail;
393 * How long do we wait until we retry the KX?
395 struct GNUNET_TIME_Relative kx_retry_delay;
398 * When do we try the next KX?
400 struct GNUNET_TIME_Absolute next_kx_attempt;
403 * Number of connections in the @e connection_head DLL.
405 unsigned int num_connections;
408 * How often have we tried and failed to decrypt a message using
409 * the unverified KX material from @e unverified_ax? Used to
410 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
412 unsigned int unverified_attempts;
415 * Number of entries in the @e tq_head DLL.
420 * State of the tunnel encryption.
422 enum CadetTunnelEState estate;
428 * Get the static string for the peer this tunnel is directed.
432 * @return Static string the destination peer's ID.
435 GCT_2s (const struct CadetTunnel *t)
440 return "Tunnel(NULL)";
441 GNUNET_snprintf (buf,
444 GNUNET_i2s (GCP_get_id (t->destination)));
450 * Get string description for tunnel encryption state.
452 * @param es Tunnel state.
454 * @return String representation.
457 estate2s (enum CadetTunnelEState es)
463 case CADET_TUNNEL_KEY_UNINITIALIZED:
464 return "CADET_TUNNEL_KEY_UNINITIALIZED";
465 case CADET_TUNNEL_KEY_SENT:
466 return "CADET_TUNNEL_KEY_SENT";
467 case CADET_TUNNEL_KEY_PING:
468 return "CADET_TUNNEL_KEY_PING";
469 case CADET_TUNNEL_KEY_OK:
470 return "CADET_TUNNEL_KEY_OK";
471 case CADET_TUNNEL_KEY_REKEY:
472 return "CADET_TUNNEL_KEY_REKEY";
474 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
481 * Return the peer to which this tunnel goes.
484 * @return the destination of the tunnel
487 GCT_get_destination (struct CadetTunnel *t)
489 return t->destination;
494 * Count channels of a tunnel.
496 * @param t Tunnel on which to count.
498 * @return Number of channels.
501 GCT_count_channels (struct CadetTunnel *t)
503 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
508 * Lookup a channel by its @a ctn.
510 * @param t tunnel to look in
511 * @param ctn number of channel to find
512 * @return NULL if channel does not exist
514 struct CadetChannel *
515 lookup_channel (struct CadetTunnel *t,
516 struct GNUNET_CADET_ChannelTunnelNumber ctn)
518 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
524 * Count all created connections of a tunnel. Not necessarily ready connections!
526 * @param t Tunnel on which to count.
528 * @return Number of connections created, either being established or ready.
531 GCT_count_any_connections (struct CadetTunnel *t)
533 return t->num_connections;
538 * Find first connection that is ready in the list of
539 * our connections. Picks ready connections round-robin.
541 * @param t tunnel to search
542 * @return NULL if we have no connection that is ready
544 static struct CadetTConnection *
545 get_ready_connection (struct CadetTunnel *t)
547 for (struct CadetTConnection *pos = t->connection_head;
550 if (GNUNET_YES == pos->is_ready)
552 if (pos != t->connection_tail)
554 /* move 'pos' to the end, so we try other ready connections
555 first next time (round-robin, modulo availability) */
556 GNUNET_CONTAINER_DLL_remove (t->connection_head,
559 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
570 * Get the encryption state of a tunnel.
574 * @return Tunnel's encryption state.
576 enum CadetTunnelEState
577 GCT_get_estate (struct CadetTunnel *t)
584 * Called when either we have a new connection, or a new message in the
585 * queue, or some existing connection has transmission capacity. Looks
586 * at our message queue and if there is a message, picks a connection
589 * @param cls the `struct CadetTunnel` to process messages on
592 trigger_transmissions (void *cls);
595 /* ************************************** start core crypto ***************************** */
599 * Create a new Axolotl ephemeral (ratchet) key.
601 * @param ax key material to update
604 new_ephemeral (struct CadetTunnelAxolotl *ax)
606 GNUNET_free_non_null (ax->DHRs);
607 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
614 * @param plaintext Content to HMAC.
615 * @param size Size of @c plaintext.
616 * @param iv Initialization vector for the message.
617 * @param key Key to use.
618 * @param hmac[out] Destination to store the HMAC.
621 t_hmac (const void *plaintext,
624 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
625 struct GNUNET_ShortHashCode *hmac)
627 static const char ctx[] = "cadet authentication key";
628 struct GNUNET_CRYPTO_AuthKey auth_key;
629 struct GNUNET_HashCode hash;
631 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
637 /* Two step: GNUNET_ShortHash is only 256 bits,
638 GNUNET_HashCode is 512, so we truncate. */
639 GNUNET_CRYPTO_hmac (&auth_key,
652 * @param key Key to use.
653 * @param[out] hash Resulting HMAC.
654 * @param source Source key material (data to HMAC).
655 * @param len Length of @a source.
658 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
659 struct GNUNET_HashCode *hash,
663 static const char ctx[] = "axolotl HMAC-HASH";
664 struct GNUNET_CRYPTO_AuthKey auth_key;
666 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
670 GNUNET_CRYPTO_hmac (&auth_key,
678 * Derive a symmetric encryption key from an HMAC-HASH.
680 * @param key Key to use for the HMAC.
681 * @param[out] out Key to generate.
682 * @param source Source key material (data to HMAC).
683 * @param len Length of @a source.
686 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
687 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
691 static const char ctx[] = "axolotl derive key";
692 struct GNUNET_HashCode h;
698 GNUNET_CRYPTO_kdf (out, sizeof (*out),
706 * Encrypt data with the axolotl tunnel key.
708 * @param ax key material to use.
709 * @param dst Destination with @a size bytes for the encrypted data.
710 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
711 * @param size Size of the buffers at @a src and @a dst
714 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
719 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
720 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
723 ax->ratchet_counter++;
724 if ( (GNUNET_YES == ax->ratchet_allowed) &&
725 ( (ratchet_messages <= ax->ratchet_counter) ||
726 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
728 ax->ratchet_flag = GNUNET_YES;
730 if (GNUNET_YES == ax->ratchet_flag)
732 /* Advance ratchet */
733 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
734 struct GNUNET_HashCode dh;
735 struct GNUNET_HashCode hmac;
736 static const char ctx[] = "axolotl ratchet";
741 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
742 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
745 t_ax_hmac_hash (&ax->RK,
749 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
751 &hmac, sizeof (hmac),
759 ax->ratchet_flag = GNUNET_NO;
760 ax->ratchet_allowed = GNUNET_NO;
761 ax->ratchet_counter = 0;
762 ax->ratchet_expiration
763 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
767 t_hmac_derive_key (&ax->CKs,
771 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
776 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
781 GNUNET_assert (size == out_size);
782 t_hmac_derive_key (&ax->CKs,
790 * Decrypt data with the axolotl tunnel key.
792 * @param ax key material to use.
793 * @param dst Destination for the decrypted data, must contain @a size bytes.
794 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
795 * @param size Size of the @a src and @a dst buffers
798 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
803 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
804 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
807 t_hmac_derive_key (&ax->CKr,
811 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
815 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
816 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
821 GNUNET_assert (out_size == size);
822 t_hmac_derive_key (&ax->CKr,
830 * Encrypt header with the axolotl header key.
832 * @param ax key material to use.
833 * @param[in|out] msg Message whose header to encrypt.
836 t_h_encrypt (struct CadetTunnelAxolotl *ax,
837 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
839 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
842 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
846 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
847 sizeof (struct GNUNET_CADET_AxHeader),
851 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
856 * Decrypt header with the current axolotl header key.
858 * @param ax key material to use.
859 * @param src Message whose header to decrypt.
860 * @param dst Where to decrypt header to.
863 t_h_decrypt (struct CadetTunnelAxolotl *ax,
864 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
865 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
867 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
870 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
874 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
875 sizeof (struct GNUNET_CADET_AxHeader),
879 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
884 * Delete a key from the list of skipped keys.
886 * @param ax key material to delete @a key from.
887 * @param key Key to delete.
890 delete_skipped_key (struct CadetTunnelAxolotl *ax,
891 struct CadetTunnelSkippedKey *key)
893 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
902 * Decrypt and verify data with the appropriate tunnel key and verify that the
903 * data has not been altered since it was sent by the remote peer.
905 * @param ax key material to use.
906 * @param dst Destination for the plaintext.
907 * @param src Source of the message. Can overlap with @c dst.
908 * @param size Size of the message.
909 * @return Size of the decrypted data, -1 if an error was encountered.
912 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
914 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
917 struct CadetTunnelSkippedKey *key;
918 struct GNUNET_ShortHashCode *hmac;
919 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
920 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
921 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
927 LOG (GNUNET_ERROR_TYPE_DEBUG,
928 "Trying skipped keys\n");
929 hmac = &plaintext_header.hmac;
930 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
932 /* Find a correct Header Key */
934 for (key = ax->skipped_head; NULL != key; key = key->next)
936 t_hmac (&src->ax_header,
937 sizeof (struct GNUNET_CADET_AxHeader) + esize,
941 if (0 == memcmp (hmac,
952 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
953 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
954 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
955 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
958 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
962 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
963 sizeof (struct GNUNET_CADET_AxHeader),
966 &plaintext_header.ax_header.Ns);
967 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
969 /* Find the correct message key */
970 N = ntohl (plaintext_header.ax_header.Ns);
971 while ( (NULL != key) &&
974 if ( (NULL == key) ||
975 (0 != memcmp (&key->HK,
977 sizeof (*valid_HK))) )
980 /* Decrypt payload */
981 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
986 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
991 delete_skipped_key (ax,
998 * Delete a key from the list of skipped keys.
1000 * @param ax key material to delete from.
1001 * @param HKr Header Key to use.
1004 store_skipped_key (struct CadetTunnelAxolotl *ax,
1005 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1007 struct CadetTunnelSkippedKey *key;
1009 key = GNUNET_new (struct CadetTunnelSkippedKey);
1010 key->timestamp = GNUNET_TIME_absolute_get ();
1013 t_hmac_derive_key (&ax->CKr,
1017 t_hmac_derive_key (&ax->CKr,
1021 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1030 * Stage skipped AX keys and calculate the message key.
1031 * Stores each HK and MK for skipped messages.
1033 * @param ax key material to use
1034 * @param HKr Header key.
1035 * @param Np Received meesage number.
1036 * @return #GNUNET_OK if keys were stored.
1037 * #GNUNET_SYSERR if an error ocurred (Np not expected).
1040 store_ax_keys (struct CadetTunnelAxolotl *ax,
1041 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1047 LOG (GNUNET_ERROR_TYPE_DEBUG,
1048 "Storing skipped keys [%u, %u)\n",
1051 if (MAX_KEY_GAP < gap)
1053 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1054 /* TODO: start new key exchange on return */
1055 GNUNET_break_op (0);
1056 LOG (GNUNET_ERROR_TYPE_WARNING,
1057 "Got message %u, expected %u+\n",
1060 return GNUNET_SYSERR;
1064 /* Delayed message: don't store keys, flag to try old keys. */
1065 return GNUNET_SYSERR;
1069 store_skipped_key (ax,
1072 while (ax->skipped > MAX_SKIPPED_KEYS)
1073 delete_skipped_key (ax,
1080 * Decrypt and verify data with the appropriate tunnel key and verify that the
1081 * data has not been altered since it was sent by the remote peer.
1083 * @param ax key material to use
1084 * @param dst Destination for the plaintext.
1085 * @param src Source of the message. Can overlap with @c dst.
1086 * @param size Size of the message.
1087 * @return Size of the decrypted data, -1 if an error was encountered.
1090 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1092 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1095 struct GNUNET_ShortHashCode msg_hmac;
1096 struct GNUNET_HashCode hmac;
1097 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1100 size_t esize; /* Size of encryped payload */
1102 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1104 /* Try current HK */
1105 t_hmac (&src->ax_header,
1106 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1109 if (0 != memcmp (&msg_hmac,
1113 static const char ctx[] = "axolotl ratchet";
1114 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1115 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1116 struct GNUNET_HashCode dh;
1117 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1120 t_hmac (&src->ax_header,
1121 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1125 if (0 != memcmp (&msg_hmac,
1129 /* Try the skipped keys, if that fails, we're out of luck. */
1130 return try_old_ax_keys (ax,
1140 Np = ntohl (plaintext_header.ax_header.Ns);
1141 PNp = ntohl (plaintext_header.ax_header.PNs);
1142 DHRp = &plaintext_header.ax_header.DHRs;
1147 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1148 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1151 t_ax_hmac_hash (&ax->RK,
1154 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1156 &hmac, sizeof (hmac),
1159 /* Commit "purported" keys */
1165 ax->ratchet_allowed = GNUNET_YES;
1172 Np = ntohl (plaintext_header.ax_header.Ns);
1173 PNp = ntohl (plaintext_header.ax_header.PNs);
1175 if ( (Np != ax->Nr) &&
1176 (GNUNET_OK != store_ax_keys (ax,
1180 /* Try the skipped keys, if that fails, we're out of luck. */
1181 return try_old_ax_keys (ax,
1197 * Our tunnel became ready for the first time, notify channels
1198 * that have been waiting.
1200 * @param cls our tunnel, not used
1201 * @param key unique ID of the channel, not used
1202 * @param value the `struct CadetChannel` to notify
1203 * @return #GNUNET_OK (continue to iterate)
1206 notify_tunnel_up_cb (void *cls,
1210 struct CadetChannel *ch = value;
1212 GCCH_tunnel_up (ch);
1218 * Change the tunnel encryption state.
1219 * If the encryption state changes to OK, stop the rekey task.
1221 * @param t Tunnel whose encryption state to change, or NULL.
1222 * @param state New encryption state.
1225 GCT_change_estate (struct CadetTunnel *t,
1226 enum CadetTunnelEState state)
1228 enum CadetTunnelEState old = t->estate;
1231 LOG (GNUNET_ERROR_TYPE_DEBUG,
1232 "Tunnel %s estate changed from %d to %d\n",
1237 if ( (CADET_TUNNEL_KEY_OK != old) &&
1238 (CADET_TUNNEL_KEY_OK == t->estate) )
1240 if (NULL != t->kx_task)
1242 GNUNET_SCHEDULER_cancel (t->kx_task);
1245 if (CADET_TUNNEL_KEY_REKEY != old)
1247 /* notify all channels that have been waiting */
1248 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1249 ¬ify_tunnel_up_cb,
1253 /* FIXME: schedule rekey task! */
1259 * Send a KX message.
1261 * FIXME: does not take care of sender-authentication yet!
1263 * @param t Tunnel on which to send it.
1264 * @param ax axolotl key context to use
1265 * @param force_reply Force the other peer to reply with a KX message.
1268 send_kx (struct CadetTunnel *t,
1269 struct CadetTunnelAxolotl *ax,
1272 struct CadetTConnection *ct;
1273 struct CadetConnection *cc;
1274 struct GNUNET_MQ_Envelope *env;
1275 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1276 enum GNUNET_CADET_KX_Flags flags;
1278 ct = get_ready_connection (t);
1281 LOG (GNUNET_ERROR_TYPE_DEBUG,
1282 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1287 LOG (GNUNET_ERROR_TYPE_DEBUG,
1288 "Sending KX on tunnel %s using connection %s\n",
1292 // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1293 env = GNUNET_MQ_msg (msg,
1294 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1295 flags = GNUNET_CADET_KX_FLAG_NONE;
1296 if (GNUNET_YES == force_reply)
1297 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1298 msg->flags = htonl (flags);
1299 msg->cid = *GCC_get_id (cc);
1300 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1301 &msg->ephemeral_key);
1302 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1304 ct->is_ready = GNUNET_NO;
1307 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1308 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1309 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1310 GCT_change_estate (t,
1311 CADET_TUNNEL_KEY_SENT);
1316 * Cleanup state used by @a ax.
1318 * @param ax state to free, but not memory of @a ax itself
1321 cleanup_ax (struct CadetTunnelAxolotl *ax)
1323 while (NULL != ax->skipped_head)
1324 delete_skipped_key (ax,
1326 GNUNET_assert (0 == ax->skipped);
1327 GNUNET_free_non_null (ax->kx_0);
1328 GNUNET_free_non_null (ax->DHRs);
1333 * Handle KX message that lacks authentication (and which will thus
1334 * only be considered authenticated after we respond with our own
1335 * KX_AUTH and finally successfully decrypt payload).
1337 * @param ct connection/tunnel combo that received encrypted message
1338 * @param msg the key exchange message
1341 GCT_handle_kx (struct CadetTConnection *ct,
1342 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1344 struct CadetTunnel *t = ct->t;
1345 struct CadetTunnelAxolotl *ax;
1346 struct GNUNET_HashCode key_material[3];
1347 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1348 const char salt[] = "CADET Axolotl salt";
1349 const struct GNUNET_PeerIdentity *pid;
1352 /* We only keep ONE unverified KX around, so if there is an existing one,
1354 if (NULL != t->unverified_ax)
1356 LOG (GNUNET_ERROR_TYPE_DEBUG,
1357 "Dropping old unverified KX state, got a fresh one.\n",
1358 t->unverified_attempts);
1359 cleanup_ax (t->unverified_ax);
1360 memset (t->unverified_ax,
1362 sizeof (struct CadetTunnelAxolotl));
1363 new_ephemeral (t->unverified_ax);
1364 t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1368 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1369 new_ephemeral (t->unverified_ax);
1370 t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1372 t->unverified_attempts = 0;
1373 ax = t->unverified_ax;
1375 pid = GCP_get_id (t->destination);
1376 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1378 am_I_alice = GNUNET_YES;
1379 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1381 am_I_alice = GNUNET_NO;
1384 GNUNET_break_op (0);
1388 if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1390 if (NULL != t->kx_task)
1392 GNUNET_SCHEDULER_cancel (t->kx_task);
1400 if (0 == memcmp (&ax->DHRr,
1402 sizeof (msg->ratchet_key)))
1404 LOG (GNUNET_ERROR_TYPE_DEBUG,
1405 " known ratchet key, exit\n");
1409 ax->DHRr = msg->ratchet_key;
1412 if (GNUNET_YES == am_I_alice)
1414 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1415 &msg->ephemeral_key, /* B0 */
1420 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1421 &pid->public_key, /* A */
1426 if (GNUNET_YES == am_I_alice)
1428 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1429 &pid->public_key, /* B */
1434 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1435 &msg->ephemeral_key, /* B0 */
1442 /* (This is the triple-DH, we could probably safely skip this,
1443 as A0/B0 are already in the key material.) */
1444 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1445 &msg->ephemeral_key, /* B0 or A0 */
1449 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1450 salt, sizeof (salt),
1451 &key_material, sizeof (key_material),
1454 if (0 == memcmp (&ax->RK,
1458 LOG (GNUNET_ERROR_TYPE_INFO,
1459 " known handshake key, exit\n");
1462 LOG (GNUNET_ERROR_TYPE_DEBUG,
1463 "Handling KX message for tunnel %s\n",
1467 if (GNUNET_YES == am_I_alice)
1473 ax->ratchet_flag = GNUNET_YES;
1481 ax->ratchet_flag = GNUNET_NO;
1482 ax->ratchet_allowed = GNUNET_NO;
1483 ax->ratchet_counter = 0;
1484 ax->ratchet_expiration
1485 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1494 case CADET_TUNNEL_KEY_UNINITIALIZED:
1495 GCT_change_estate (t,
1496 CADET_TUNNEL_KEY_PING);
1498 case CADET_TUNNEL_KEY_SENT:
1499 /* Got a response to us sending our key; now
1500 we can start transmitting! */
1501 GCT_change_estate (t,
1502 CADET_TUNNEL_KEY_OK);
1503 if (NULL != t->send_task)
1504 GNUNET_SCHEDULER_cancel (t->send_task);
1505 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1508 case CADET_TUNNEL_KEY_PING:
1509 /* Got a key yet again; need encrypted payload to advance */
1511 case CADET_TUNNEL_KEY_OK:
1512 /* Did not expect a key, but so what. */
1514 case CADET_TUNNEL_KEY_REKEY:
1515 /* Got a key yet again; need encrypted payload to advance */
1521 /* ************************************** end core crypto ***************************** */
1525 * Compute the next free channel tunnel number for this tunnel.
1527 * @param t the tunnel
1528 * @return unused number that can uniquely identify a channel in the tunnel
1530 static struct GNUNET_CADET_ChannelTunnelNumber
1531 get_next_free_ctn (struct CadetTunnel *t)
1533 #define HIGH_BIT 0x8000000
1534 struct GNUNET_CADET_ChannelTunnelNumber ret;
1539 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1540 GCP_get_id (GCT_get_destination (t)));
1546 GNUNET_assert (0); // loopback must never go here!
1547 ctn = ntohl (t->next_ctn.cn);
1549 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1552 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1554 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1555 ret.cn = ntohl (ctn);
1561 * Add a channel to a tunnel, and notify channel that we are ready
1562 * for transmission if we are already up. Otherwise that notification
1563 * will be done later in #notify_tunnel_up_cb().
1567 * @return unique number identifying @a ch within @a t
1569 struct GNUNET_CADET_ChannelTunnelNumber
1570 GCT_add_channel (struct CadetTunnel *t,
1571 struct CadetChannel *ch)
1573 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1575 ctn = get_next_free_ctn (t);
1576 GNUNET_assert (GNUNET_YES ==
1577 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1580 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1581 LOG (GNUNET_ERROR_TYPE_DEBUG,
1582 "Adding channel %s to tunnel %s\n",
1585 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1586 (CADET_TUNNEL_KEY_REKEY == t->estate) )
1587 GCCH_tunnel_up (ch);
1593 * We lost a connection, remove it from our list and clean up
1594 * the connection object itself.
1596 * @param ct binding of connection to tunnel of the connection that was lost.
1599 GCT_connection_lost (struct CadetTConnection *ct)
1601 struct CadetTunnel *t = ct->t;
1603 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1611 * This tunnel is no longer used, destroy it.
1613 * @param cls the idle tunnel
1616 destroy_tunnel (void *cls)
1618 struct CadetTunnel *t = cls;
1619 struct CadetTConnection *ct;
1620 struct CadetTunnelQueueEntry *tq;
1622 t->destroy_task = NULL;
1623 LOG (GNUNET_ERROR_TYPE_DEBUG,
1624 "Destroying idle tunnel %s\n",
1626 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1627 while (NULL != (ct = t->connection_head))
1629 struct CadetConnection *cc;
1631 GNUNET_assert (ct->t == t);
1633 GCT_connection_lost (ct);
1634 GCC_destroy_without_tunnel (cc);
1636 while (NULL != (tq = t->tq_head))
1638 if (NULL != tq->cont)
1639 tq->cont (tq->cont_cls);
1640 GCT_send_cancel (tq);
1642 GCP_drop_tunnel (t->destination,
1644 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1645 if (NULL != t->maintain_connections_task)
1647 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1648 t->maintain_connections_task = NULL;
1650 if (NULL != t->send_task)
1652 GNUNET_SCHEDULER_cancel (t->send_task);
1653 t->send_task = NULL;
1655 if (NULL != t->kx_task)
1657 GNUNET_SCHEDULER_cancel (t->kx_task);
1660 GNUNET_MST_destroy (t->mst);
1661 GNUNET_MQ_destroy (t->mq);
1662 cleanup_ax (&t->ax);
1663 if (NULL != t->unverified_ax)
1665 cleanup_ax (t->unverified_ax);
1666 GNUNET_free (t->unverified_ax);
1673 * Remove a channel from a tunnel.
1677 * @param ctn unique number identifying @a ch within @a t
1680 GCT_remove_channel (struct CadetTunnel *t,
1681 struct CadetChannel *ch,
1682 struct GNUNET_CADET_ChannelTunnelNumber ctn)
1684 LOG (GNUNET_ERROR_TYPE_DEBUG,
1685 "Removing channel %s from tunnel %s\n",
1688 GNUNET_assert (GNUNET_YES ==
1689 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1693 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1695 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1703 * Destroy remaining channels during shutdown.
1705 * @param cls the `struct CadetTunnel` of the channel
1706 * @param key key of the channel
1707 * @param value the `struct CadetChannel`
1708 * @return #GNUNET_OK (continue to iterate)
1711 destroy_remaining_channels (void *cls,
1715 struct CadetChannel *ch = value;
1717 GCCH_handle_remote_destroy (ch);
1723 * Destroys the tunnel @a t now, without delay. Used during shutdown.
1725 * @param t tunnel to destroy
1728 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1730 GNUNET_assert (GNUNET_YES == shutting_down);
1731 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1732 &destroy_remaining_channels,
1735 GNUNET_CONTAINER_multihashmap32_size (t->channels));
1736 if (NULL != t->destroy_task)
1738 GNUNET_SCHEDULER_cancel (t->destroy_task);
1739 t->destroy_task = NULL;
1746 * It's been a while, we should try to redo the KX, if we can.
1748 * @param cls the `struct CadetTunnel` to do KX for.
1751 retry_kx (void *cls)
1753 struct CadetTunnel *t = cls;
1758 ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1759 (CADET_TUNNEL_KEY_SENT == t->estate) )
1766 * Send normal payload from queue in @a t via connection @a ct.
1767 * Does nothing if our payload queue is empty.
1769 * @param t tunnel to send data from
1770 * @param ct connection to use for transmission (is ready)
1773 try_send_normal_payload (struct CadetTunnel *t,
1774 struct CadetTConnection *ct)
1776 struct CadetTunnelQueueEntry *tq;
1778 GNUNET_assert (GNUNET_YES == ct->is_ready);
1782 /* no messages pending right now */
1783 LOG (GNUNET_ERROR_TYPE_DEBUG,
1784 "Not sending payload of %s on ready %s (nothing pending)\n",
1789 /* ready to send message 'tq' on tunnel 'ct' */
1790 GNUNET_assert (t == tq->t);
1791 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1794 if (NULL != tq->cid)
1795 *tq->cid = *GCC_get_id (ct->cc);
1796 ct->is_ready = GNUNET_NO;
1797 LOG (GNUNET_ERROR_TYPE_DEBUG,
1798 "Sending payload of %s on %s\n",
1801 GCC_transmit (ct->cc,
1803 if (NULL != tq->cont)
1804 tq->cont (tq->cont_cls);
1810 * A connection is @a is_ready for transmission. Looks at our message
1811 * queue and if there is a message, sends it out via the connection.
1813 * @param cls the `struct CadetTConnection` that is @a is_ready
1814 * @param is_ready #GNUNET_YES if connection are now ready,
1815 * #GNUNET_NO if connection are no longer ready
1818 connection_ready_cb (void *cls,
1821 struct CadetTConnection *ct = cls;
1822 struct CadetTunnel *t = ct->t;
1824 if (GNUNET_NO == is_ready)
1826 LOG (GNUNET_ERROR_TYPE_DEBUG,
1827 "Connection %s no longer ready for tunnel %s\n",
1830 ct->is_ready = GNUNET_NO;
1833 ct->is_ready = GNUNET_YES;
1834 LOG (GNUNET_ERROR_TYPE_DEBUG,
1835 "Connection %s now ready for tunnel %s in state %s\n",
1838 estate2s (t->estate));
1841 case CADET_TUNNEL_KEY_UNINITIALIZED:
1846 case CADET_TUNNEL_KEY_SENT:
1847 case CADET_TUNNEL_KEY_PING:
1848 /* opportunity to #retry_kx() starts now, schedule job */
1849 if (NULL == t->kx_task)
1852 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1857 case CADET_TUNNEL_KEY_OK:
1858 try_send_normal_payload (t,
1861 case CADET_TUNNEL_KEY_REKEY:
1865 t->estate = CADET_TUNNEL_KEY_OK;
1872 * Called when either we have a new connection, or a new message in the
1873 * queue, or some existing connection has transmission capacity. Looks
1874 * at our message queue and if there is a message, picks a connection
1877 * @param cls the `struct CadetTunnel` to process messages on
1880 trigger_transmissions (void *cls)
1882 struct CadetTunnel *t = cls;
1883 struct CadetTConnection *ct;
1885 t->send_task = NULL;
1886 if (NULL == t->tq_head)
1887 return; /* no messages pending right now */
1888 ct = get_ready_connection (t);
1890 return; /* no connections ready */
1891 try_send_normal_payload (t,
1897 * Consider using the path @a p for the tunnel @a t.
1898 * The tunnel destination is at offset @a off in path @a p.
1900 * @param cls our tunnel
1901 * @param path a path to our destination
1902 * @param off offset of the destination on path @a path
1903 * @return #GNUNET_YES (should keep iterating)
1906 consider_path_cb (void *cls,
1907 struct CadetPeerPath *path,
1910 struct CadetTunnel *t = cls;
1911 unsigned int min_length = UINT_MAX;
1912 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1913 struct CadetTConnection *ct;
1915 /* Check if we care about the new path. */
1916 for (ct = t->connection_head;
1920 struct CadetPeerPath *ps;
1922 ps = GCC_get_path (ct->cc);
1925 LOG (GNUNET_ERROR_TYPE_DEBUG,
1926 "Ignoring duplicate path %s for tunnel %s.\n",
1929 return GNUNET_YES; /* duplicate */
1931 min_length = GNUNET_MIN (min_length,
1932 GCPP_get_length (ps));
1933 max_desire = GNUNET_MAX (max_desire,
1934 GCPP_get_desirability (ps));
1937 /* FIXME: not sure we should really just count
1938 'num_connections' here, as they may all have
1939 consistently failed to connect. */
1941 /* We iterate by increasing path length; if we have enough paths and
1942 this one is more than twice as long than what we are currently
1943 using, then ignore all of these super-long ones! */
1944 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1945 (min_length * 2 < off) )
1947 LOG (GNUNET_ERROR_TYPE_DEBUG,
1948 "Ignoring paths of length %u, they are way too long.\n",
1952 /* If we have enough paths and this one looks no better, ignore it. */
1953 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1954 (min_length < GCPP_get_length (path)) &&
1955 (max_desire > GCPP_get_desirability (path)) )
1957 LOG (GNUNET_ERROR_TYPE_DEBUG,
1958 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1959 GCPP_get_length (path),
1960 (unsigned long long) GCPP_get_desirability (path),
1961 GCP_2s (t->destination));
1965 /* Path is interesting (better by some metric, or we don't have
1966 enough paths yet). */
1967 ct = GNUNET_new (struct CadetTConnection);
1968 ct->created = GNUNET_TIME_absolute_get ();
1970 ct->cc = GCC_create (t->destination,
1973 &connection_ready_cb,
1975 /* FIXME: schedule job to kill connection (and path?) if it takes
1976 too long to get ready! (And track performance data on how long
1977 other connections took with the tunnel!)
1978 => Note: to be done within 'connection'-logic! */
1979 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1982 t->num_connections++;
1983 LOG (GNUNET_ERROR_TYPE_DEBUG,
1984 "Found interesting path %s for tunnel %s, created connection %s\n",
1993 * Function called to maintain the connections underlying our tunnel.
1994 * Tries to maintain (incl. tear down) connections for the tunnel, and
1995 * if there is a significant change, may trigger transmissions.
1997 * Basically, needs to check if there are connections that perform
1998 * badly, and if so eventually kill them and trigger a replacement.
1999 * The strategy is to open one more connection than
2000 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2001 * least-performing one, and then inquire for new ones.
2003 * @param cls the `struct CadetTunnel`
2006 maintain_connections_cb (void *cls)
2008 struct CadetTunnel *t = cls;
2010 t->maintain_connections_task = NULL;
2011 LOG (GNUNET_ERROR_TYPE_DEBUG,
2012 "Performing connection maintenance for tunnel %s.\n",
2015 (void) GCP_iterate_paths (t->destination,
2019 GNUNET_break (0); // FIXME: implement!
2024 * Consider using the path @a p for the tunnel @a t.
2025 * The tunnel destination is at offset @a off in path @a p.
2027 * @param cls our tunnel
2028 * @param path a path to our destination
2029 * @param off offset of the destination on path @a path
2032 GCT_consider_path (struct CadetTunnel *t,
2033 struct CadetPeerPath *p,
2036 (void) consider_path_cb (t,
2043 * We got a keepalive. Track in statistics.
2045 * @param cls the `struct CadetTunnel` for which we decrypted the message
2046 * @param msg the message we received on the tunnel
2049 handle_plaintext_keepalive (void *cls,
2050 const struct GNUNET_MessageHeader *msg)
2052 struct CadetTunnel *t = cls;
2054 LOG (GNUNET_ERROR_TYPE_DEBUG,
2055 "Received KEEPALIVE on tunnel %s\n",
2057 GNUNET_STATISTICS_update (stats,
2058 "# keepalives received",
2065 * Check that @a msg is well-formed.
2067 * @param cls the `struct CadetTunnel` for which we decrypted the message
2068 * @param msg the message we received on the tunnel
2069 * @return #GNUNET_OK (any variable-size payload goes)
2072 check_plaintext_data (void *cls,
2073 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2080 * We received payload data for a channel. Locate the channel
2081 * and process the data, or return an error if the channel is unknown.
2083 * @param cls the `struct CadetTunnel` for which we decrypted the message
2084 * @param msg the message we received on the tunnel
2087 handle_plaintext_data (void *cls,
2088 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2090 struct CadetTunnel *t = cls;
2091 struct CadetChannel *ch;
2093 ch = lookup_channel (t,
2097 /* We don't know about such a channel, might have been destroyed on our
2098 end in the meantime, or never existed. Send back a DESTROY. */
2099 LOG (GNUNET_ERROR_TYPE_DEBUG,
2100 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2101 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2102 ntohl (msg->ctn.cn));
2103 GCT_send_channel_destroy (t,
2107 GCCH_handle_channel_plaintext_data (ch,
2113 * We received an acknowledgement for data we sent on a channel.
2114 * Locate the channel and process it, or return an error if the
2115 * channel is unknown.
2117 * @param cls the `struct CadetTunnel` for which we decrypted the message
2118 * @param ack the message we received on the tunnel
2121 handle_plaintext_data_ack (void *cls,
2122 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2124 struct CadetTunnel *t = cls;
2125 struct CadetChannel *ch;
2127 ch = lookup_channel (t,
2131 /* We don't know about such a channel, might have been destroyed on our
2132 end in the meantime, or never existed. Send back a DESTROY. */
2133 LOG (GNUNET_ERROR_TYPE_DEBUG,
2134 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2135 ntohl (ack->ctn.cn));
2136 GCT_send_channel_destroy (t,
2140 GCCH_handle_channel_plaintext_data_ack (ch,
2146 * We have received a request to open a channel to a port from
2147 * another peer. Creates the incoming channel.
2149 * @param cls the `struct CadetTunnel` for which we decrypted the message
2150 * @param copen the message we received on the tunnel
2153 handle_plaintext_channel_open (void *cls,
2154 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2156 struct CadetTunnel *t = cls;
2157 struct CadetChannel *ch;
2159 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2160 ntohl (copen->ctn.cn));
2163 LOG (GNUNET_ERROR_TYPE_DEBUG,
2164 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2165 GNUNET_h2s (&copen->port),
2168 GCCH_handle_duplicate_open (ch);
2171 LOG (GNUNET_ERROR_TYPE_DEBUG,
2172 "Receicved channel OPEN on port %s from %s\n",
2173 GNUNET_h2s (&copen->port),
2175 ch = GCCH_channel_incoming_new (t,
2178 ntohl (copen->opt));
2179 GNUNET_assert (GNUNET_OK ==
2180 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2181 ntohl (copen->ctn.cn),
2183 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2188 * Send a DESTROY message via the tunnel.
2190 * @param t the tunnel to transmit over
2191 * @param ctn ID of the channel to destroy
2194 GCT_send_channel_destroy (struct CadetTunnel *t,
2195 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2197 struct GNUNET_CADET_ChannelManageMessage msg;
2199 LOG (GNUNET_ERROR_TYPE_DEBUG,
2200 "Sending DESTORY message for channel ID %u\n",
2202 msg.header.size = htons (sizeof (msg));
2203 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2204 msg.reserved = htonl (0);
2214 * We have received confirmation from the target peer that the
2215 * given channel could be established (the port is open).
2218 * @param cls the `struct CadetTunnel` for which we decrypted the message
2219 * @param cm the message we received on the tunnel
2222 handle_plaintext_channel_open_ack (void *cls,
2223 const struct GNUNET_CADET_ChannelManageMessage *cm)
2225 struct CadetTunnel *t = cls;
2226 struct CadetChannel *ch;
2228 ch = lookup_channel (t,
2232 /* We don't know about such a channel, might have been destroyed on our
2233 end in the meantime, or never existed. Send back a DESTROY. */
2234 LOG (GNUNET_ERROR_TYPE_DEBUG,
2235 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2236 ntohl (cm->ctn.cn));
2237 GCT_send_channel_destroy (t,
2241 LOG (GNUNET_ERROR_TYPE_DEBUG,
2242 "Received channel OPEN_ACK on channel %s from %s\n",
2245 GCCH_handle_channel_open_ack (ch);
2250 * We received a message saying that a channel should be destroyed.
2251 * Pass it on to the correct channel.
2253 * @param cls the `struct CadetTunnel` for which we decrypted the message
2254 * @param cm the message we received on the tunnel
2257 handle_plaintext_channel_destroy (void *cls,
2258 const struct GNUNET_CADET_ChannelManageMessage *cm)
2260 struct CadetTunnel *t = cls;
2261 struct CadetChannel *ch;
2263 ch = lookup_channel (t,
2267 /* We don't know about such a channel, might have been destroyed on our
2268 end in the meantime, or never existed. */
2269 LOG (GNUNET_ERROR_TYPE_DEBUG,
2270 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2271 ntohl (cm->ctn.cn));
2274 LOG (GNUNET_ERROR_TYPE_DEBUG,
2275 "Receicved channel DESTROY on %s from %s\n",
2278 GCCH_handle_remote_destroy (ch);
2283 * Handles a message we decrypted, by injecting it into
2284 * our message queue (which will do the dispatching).
2286 * @param cls the `struct CadetTunnel` that got the message
2287 * @param msg the message
2288 * @return #GNUNET_OK (continue to process)
2291 handle_decrypted (void *cls,
2292 const struct GNUNET_MessageHeader *msg)
2294 struct CadetTunnel *t = cls;
2296 GNUNET_MQ_inject_message (t->mq,
2303 * Function called if we had an error processing
2304 * an incoming decrypted message.
2306 * @param cls the `struct CadetTunnel`
2307 * @param error error code
2310 decrypted_error_cb (void *cls,
2311 enum GNUNET_MQ_Error error)
2313 GNUNET_break_op (0);
2318 * Create a tunnel to @a destionation. Must only be called
2319 * from within #GCP_get_tunnel().
2321 * @param destination where to create the tunnel to
2322 * @return new tunnel to @a destination
2324 struct CadetTunnel *
2325 GCT_create_tunnel (struct CadetPeer *destination)
2327 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2328 struct GNUNET_MQ_MessageHandler handlers[] = {
2329 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2330 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2331 struct GNUNET_MessageHeader,
2333 GNUNET_MQ_hd_var_size (plaintext_data,
2334 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2335 struct GNUNET_CADET_ChannelAppDataMessage,
2337 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2338 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2339 struct GNUNET_CADET_ChannelDataAckMessage,
2341 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2342 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2343 struct GNUNET_CADET_ChannelOpenMessage,
2345 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2346 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2347 struct GNUNET_CADET_ChannelManageMessage,
2349 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2350 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2351 struct GNUNET_CADET_ChannelManageMessage,
2353 GNUNET_MQ_handler_end ()
2356 new_ephemeral (&t->ax);
2357 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2358 t->destination = destination;
2359 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2360 t->maintain_connections_task
2361 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2363 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2368 &decrypted_error_cb,
2370 t->mst = GNUNET_MST_create (&handle_decrypted,
2377 * Add a @a connection to the @a tunnel.
2380 * @param cid connection identifer to use for the connection
2381 * @param path path to use for the connection
2382 * @return #GNUNET_OK on success,
2383 * #GNUNET_SYSERR on failure (duplicate connection)
2386 GCT_add_inbound_connection (struct CadetTunnel *t,
2387 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2388 struct CadetPeerPath *path)
2390 struct CadetTConnection *ct;
2392 ct = GNUNET_new (struct CadetTConnection);
2393 ct->created = GNUNET_TIME_absolute_get ();
2395 ct->cc = GCC_create_inbound (t->destination,
2399 &connection_ready_cb,
2403 LOG (GNUNET_ERROR_TYPE_DEBUG,
2404 "Tunnel %s refused inbound connection %s (duplicate)\n",
2408 return GNUNET_SYSERR;
2410 /* FIXME: schedule job to kill connection (and path?) if it takes
2411 too long to get ready! (And track performance data on how long
2412 other connections took with the tunnel!)
2413 => Note: to be done within 'connection'-logic! */
2414 GNUNET_CONTAINER_DLL_insert (t->connection_head,
2417 t->num_connections++;
2418 LOG (GNUNET_ERROR_TYPE_DEBUG,
2419 "Tunnel %s has new connection %s\n",
2427 * Handle encrypted message.
2429 * @param ct connection/tunnel combo that received encrypted message
2430 * @param msg the encrypted message to decrypt
2433 GCT_handle_encrypted (struct CadetTConnection *ct,
2434 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2436 struct CadetTunnel *t = ct->t;
2437 uint16_t size = ntohs (msg->header.size);
2438 char cbuf [size] GNUNET_ALIGN;
2439 ssize_t decrypted_size;
2441 LOG (GNUNET_ERROR_TYPE_DEBUG,
2442 "Tunnel %s received %u bytes of encrypted data in state %d\n",
2444 (unsigned int) size,
2449 case CADET_TUNNEL_KEY_UNINITIALIZED:
2450 /* We did not even SEND our KX, how can the other peer
2451 send us encrypted data? */
2452 GNUNET_break_op (0);
2454 case CADET_TUNNEL_KEY_SENT:
2455 /* We did not get the KX of the other peer, but that
2456 might have been lost. Ask for KX again. */
2457 GNUNET_STATISTICS_update (stats,
2458 "# received encrypted without KX",
2461 if (NULL != t->kx_task)
2462 GNUNET_SCHEDULER_cancel (t->kx_task);
2463 t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2466 case CADET_TUNNEL_KEY_PING:
2467 /* Great, first payload, we might graduate to OK */
2468 case CADET_TUNNEL_KEY_OK:
2469 case CADET_TUNNEL_KEY_REKEY:
2473 GNUNET_STATISTICS_update (stats,
2474 "# received encrypted",
2477 decrypted_size = -1;
2478 if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
2479 (CADET_TUNNEL_KEY_REKEY == t->estate) )
2481 /* We have well-established key material available,
2482 try that. (This is the common case.) */
2483 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2489 if ( (-1 == decrypted_size) &&
2490 (NULL != t->unverified_ax) )
2492 /* We have un-authenticated KX material available. We should try
2493 this as a back-up option, in case the sender crashed and
2495 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2499 if (-1 != decrypted_size)
2501 /* It worked! Treat this as authentication of the AX data! */
2502 cleanup_ax (&t->ax);
2503 t->ax = *t->unverified_ax;
2504 GNUNET_free (t->unverified_ax);
2505 t->unverified_ax = NULL;
2507 if (CADET_TUNNEL_KEY_PING == t->estate)
2509 /* First time it worked, move tunnel into production! */
2510 GCT_change_estate (t,
2511 CADET_TUNNEL_KEY_OK);
2512 if (NULL != t->send_task)
2513 GNUNET_SCHEDULER_cancel (t->send_task);
2514 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2518 if (NULL != t->unverified_ax)
2520 /* We had unverified KX material that was useless; so increment
2521 counter and eventually move to ignore it. Note that we even do
2522 this increment if we successfully decrypted with the old KX
2523 material and thus didn't even both with the new one. This is
2524 the ideal case, as a malicious injection of bogus KX data
2525 basically only causes us to increment a counter a few times. */
2526 t->unverified_attempts++;
2527 LOG (GNUNET_ERROR_TYPE_DEBUG,
2528 "Failed to decrypt message with unverified KX data %u times\n",
2529 t->unverified_attempts);
2530 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2532 cleanup_ax (t->unverified_ax);
2533 GNUNET_free (t->unverified_ax);
2534 t->unverified_ax = NULL;
2538 if (-1 == decrypted_size)
2540 /* Decryption failed for good, complain. */
2541 GNUNET_break_op (0);
2542 LOG (GNUNET_ERROR_TYPE_WARNING,
2543 "Tunnel %s failed to decrypt and validate encrypted data\n",
2545 GNUNET_STATISTICS_update (stats,
2546 "# unable to decrypt",
2552 /* The MST will ultimately call #handle_decrypted() on each message. */
2553 GNUNET_break_op (GNUNET_OK ==
2554 GNUNET_MST_from_buffer (t->mst,
2563 * Sends an already built message on a tunnel, encrypting it and
2564 * choosing the best connection if not provided.
2566 * @param message Message to send. Function modifies it.
2567 * @param t Tunnel on which this message is transmitted.
2568 * @param cont Continuation to call once message is really sent.
2569 * @param cont_cls Closure for @c cont.
2570 * @return Handle to cancel message
2572 struct CadetTunnelQueueEntry *
2573 GCT_send (struct CadetTunnel *t,
2574 const struct GNUNET_MessageHeader *message,
2575 GNUNET_SCHEDULER_TaskCallback cont,
2578 struct CadetTunnelQueueEntry *tq;
2579 uint16_t payload_size;
2580 struct GNUNET_MQ_Envelope *env;
2581 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2583 if ( (CADET_TUNNEL_KEY_OK != t->estate) &&
2584 (CADET_TUNNEL_KEY_REKEY != t->estate) )
2589 payload_size = ntohs (message->size);
2590 LOG (GNUNET_ERROR_TYPE_DEBUG,
2591 "Encrypting %u bytes for tunnel %s\n",
2592 (unsigned int) payload_size,
2594 env = GNUNET_MQ_msg_extra (ax_msg,
2596 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2597 t_ax_encrypt (&t->ax,
2601 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2602 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2603 /* FIXME: we should do this once, not once per message;
2604 this is a point multiplication, and DHRs does not
2605 change all the time. */
2606 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2607 &ax_msg->ax_header.DHRs);
2608 t_h_encrypt (&t->ax,
2610 t_hmac (&ax_msg->ax_header,
2611 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2616 tq = GNUNET_malloc (sizeof (*tq));
2619 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2621 tq->cont_cls = cont_cls;
2622 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2625 if (NULL != t->send_task)
2626 GNUNET_SCHEDULER_cancel (t->send_task);
2628 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2635 * Cancel a previously sent message while it's in the queue.
2637 * ONLY can be called before the continuation given to the send
2638 * function is called. Once the continuation is called, the message is
2639 * no longer in the queue!
2641 * @param tq Handle to the queue entry to cancel.
2644 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2646 struct CadetTunnel *t = tq->t;
2648 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2651 GNUNET_MQ_discard (tq->env);
2657 * Iterate over all connections of a tunnel.
2659 * @param t Tunnel whose connections to iterate.
2660 * @param iter Iterator.
2661 * @param iter_cls Closure for @c iter.
2664 GCT_iterate_connections (struct CadetTunnel *t,
2665 GCT_ConnectionIterator iter,
2668 for (struct CadetTConnection *ct = t->connection_head;
2677 * Closure for #iterate_channels_cb.
2684 GCT_ChannelIterator iter;
2687 * Closure for @e iter.
2694 * Helper function for #GCT_iterate_channels.
2696 * @param cls the `struct ChanIterCls`
2698 * @param value a `struct CadetChannel`
2699 * @return #GNUNET_OK
2702 iterate_channels_cb (void *cls,
2706 struct ChanIterCls *ctx = cls;
2707 struct CadetChannel *ch = value;
2709 ctx->iter (ctx->iter_cls,
2716 * Iterate over all channels of a tunnel.
2718 * @param t Tunnel whose channels to iterate.
2719 * @param iter Iterator.
2720 * @param iter_cls Closure for @c iter.
2723 GCT_iterate_channels (struct CadetTunnel *t,
2724 GCT_ChannelIterator iter,
2727 struct ChanIterCls ctx;
2730 ctx.iter_cls = iter_cls;
2731 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2732 &iterate_channels_cb,
2739 * Call #GCCH_debug() on a channel.
2741 * @param cls points to the log level to use
2743 * @param value the `struct CadetChannel` to dump
2744 * @return #GNUNET_OK (continue iteration)
2747 debug_channel (void *cls,
2751 const enum GNUNET_ErrorType *level = cls;
2752 struct CadetChannel *ch = value;
2754 GCCH_debug (ch, *level);
2759 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2763 * Log all possible info about the tunnel state.
2765 * @param t Tunnel to debug.
2766 * @param level Debug level to use.
2769 GCT_debug (const struct CadetTunnel *t,
2770 enum GNUNET_ErrorType level)
2772 struct CadetTConnection *iter_c;
2775 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2777 __FILE__, __FUNCTION__, __LINE__);
2782 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2784 estate2s (t->estate),
2786 t->num_connections);
2789 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2793 "TTT connections:\n");
2794 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2795 GCC_debug (iter_c->cc,
2799 "TTT TUNNEL END\n");
2803 /* end of gnunet-service-cadet-new_tunnels.c */