2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017, 2018 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_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
27 * - proper connection evaluation during connection management:
28 * + consider quality (or quality spread?) of current connection set
29 * when deciding how often to do maintenance
30 * + interact with PEER to drive DHT GET/PUT operations based
31 * on how much we like our connections
34 #include "gnunet_util_lib.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_signatures.h"
37 #include "cadet_protocol.h"
38 #include "gnunet-service-cadet_channel.h"
39 #include "gnunet-service-cadet_connection.h"
40 #include "gnunet-service-cadet_tunnels.h"
41 #include "gnunet-service-cadet_peer.h"
42 #include "gnunet-service-cadet_paths.h"
45 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
48 * How often do we try to decrypt payload with unverified key
49 * material? Used to limit CPU increase upon receiving bogus
52 #define MAX_UNVERIFIED_ATTEMPTS 16
55 * How long do we wait until tearing down an idle tunnel?
57 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
60 * How long do we wait initially before retransmitting the KX?
61 * TODO: replace by 2 RTT if/once we have connection-level RTT data!
63 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
66 * Maximum number of skipped keys we keep in memory per tunnel.
68 #define MAX_SKIPPED_KEYS 64
71 * Maximum number of keys (and thus ratchet steps) we are willing to
72 * skip before we decide this is either a bogus packet or a DoS-attempt.
74 #define MAX_KEY_GAP 256
78 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
80 struct CadetTunnelSkippedKey
85 struct CadetTunnelSkippedKey *next;
90 struct CadetTunnelSkippedKey *prev;
93 * When was this key stored (for timeout).
95 struct GNUNET_TIME_Absolute timestamp;
100 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
105 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
108 * Key number for a given HK.
115 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
117 struct CadetTunnelAxolotl
120 * A (double linked) list of stored message keys and associated header keys
121 * for "skipped" messages, i.e. messages that have not been
122 * received despite the reception of more recent messages, (head).
124 struct CadetTunnelSkippedKey *skipped_head;
127 * Skipped messages' keys DLL, tail.
129 struct CadetTunnelSkippedKey *skipped_tail;
132 * 32-byte root key which gets updated by DH ratchet.
134 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
137 * 32-byte header key (currently used for sending).
139 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
142 * 32-byte header key (currently used for receiving)
144 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
147 * 32-byte next header key (for sending), used once the
148 * ratchet advances. We are sure that the sender has this
149 * key as well only after @e ratchet_allowed is #GNUNET_YES.
151 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
154 * 32-byte next header key (for receiving). To be tried
155 * when decrypting with @e HKr fails and thus the sender
156 * may have advanced the ratchet.
158 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
161 * 32-byte chain keys (used for forward-secrecy) for
162 * sending messages. Updated for every message.
164 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
167 * 32-byte chain keys (used for forward-secrecy) for
168 * receiving messages. Updated for every message. If
169 * messages are skipped, the respective derived MKs
170 * (and the current @HKr) are kept in the @e skipped_head DLL.
172 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
175 * ECDH for key exchange (A0 / B0).
177 struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
180 * ECDH Ratchet key (our private key in the current DH).
182 struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
185 * ECDH Ratchet key (other peer's public key in the current DH).
187 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
190 * Last ephemeral public key received from the other peer,
191 * for duplicate detection.
193 struct GNUNET_CRYPTO_EcdhePublicKey last_ephemeral;
196 * Time when the current ratchet expires and a new one is triggered
197 * (if @e ratchet_allowed is #GNUNET_YES).
199 struct GNUNET_TIME_Absolute ratchet_expiration;
202 * Number of elements in @a skipped_head <-> @a skipped_tail.
204 unsigned int skipped;
207 * Message number (reset to 0 with each new ratchet, next message to send).
212 * Message number (reset to 0 with each new ratchet, next message to recv).
217 * Previous message numbers (# of msgs sent under prev ratchet)
222 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
227 * True (#GNUNET_YES) if we have received a message from the
228 * other peer that uses the keys from our last ratchet step.
229 * This implies that we are again allowed to advance the ratchet,
230 * otherwise we have to wait until the other peer sees our current
231 * ephemeral key and advances first.
233 * #GNUNET_NO if we have advanced the ratched but lack any evidence
234 * that the other peer has noticed this.
239 * Number of messages recieved since our last ratchet advance.
241 * If this counter = 0, we cannot send a new ratchet key in the next
244 * If this counter > 0, we could (but don't have to) send a new key.
246 * Once the @e ratchet_counter is larger than
247 * #ratchet_messages (or @e ratchet_expiration time has past), and
248 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
250 unsigned int ratchet_counter;
256 * Struct used to save messages in a non-ready tunnel to send once connected.
258 struct CadetTunnelQueueEntry
261 * We are entries in a DLL
263 struct CadetTunnelQueueEntry *next;
266 * We are entries in a DLL
268 struct CadetTunnelQueueEntry *prev;
271 * Tunnel these messages belong in.
273 struct CadetTunnel *t;
276 * Continuation to call once sent (on the channel layer).
278 GCT_SendContinuation cont;
281 * Closure for @c cont.
286 * Envelope of message to send follows.
288 struct GNUNET_MQ_Envelope *env;
291 * Where to put the connection identifier into the payload
292 * of the message in @e env once we have it?
294 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
299 * Struct containing all information regarding a tunnel to a peer.
304 * Destination of the tunnel.
306 struct CadetPeer *destination;
309 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
310 * ephemeral key changes.
312 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
315 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
317 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
320 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
322 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
327 struct CadetTunnelAxolotl ax;
330 * Unverified Axolotl info, used only if we got a fresh KX (not a
331 * KX_AUTH) while our end of the tunnel was still up. In this case,
332 * we keep the fresh KX around but do not put it into action until
333 * we got encrypted payload that assures us of the authenticity of
336 struct CadetTunnelAxolotl *unverified_ax;
339 * Task scheduled if there are no more channels using the tunnel.
341 struct GNUNET_SCHEDULER_Task *destroy_task;
344 * Task to trim connections if too many are present.
346 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
349 * Task to send messages from queue (if possible).
351 struct GNUNET_SCHEDULER_Task *send_task;
354 * Task to trigger KX.
356 struct GNUNET_SCHEDULER_Task *kx_task;
359 * Tokenizer for decrypted messages.
361 struct GNUNET_MessageStreamTokenizer *mst;
364 * Dispatcher for decrypted messages only (do NOT use for sending!).
366 struct GNUNET_MQ_Handle *mq;
369 * DLL of ready connections that are actively used to reach the destination peer.
371 struct CadetTConnection *connection_ready_head;
374 * DLL of ready connections that are actively used to reach the destination peer.
376 struct CadetTConnection *connection_ready_tail;
379 * DLL of connections that we maintain that might be used to reach the destination peer.
381 struct CadetTConnection *connection_busy_head;
384 * DLL of connections that we maintain that might be used to reach the destination peer.
386 struct CadetTConnection *connection_busy_tail;
389 * Channels inside this tunnel. Maps
390 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
392 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
395 * Channel ID for the next created channel in this tunnel.
397 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
400 * Queued messages, to transmit once tunnel gets connected.
402 struct CadetTunnelQueueEntry *tq_head;
405 * Queued messages, to transmit once tunnel gets connected.
407 struct CadetTunnelQueueEntry *tq_tail;
410 * Identification of the connection from which we are currently processing
411 * a message. Only valid (non-NULL) during #handle_decrypted() and the
412 * handle-*()-functions called from our @e mq during that function.
414 struct CadetTConnection *current_ct;
417 * How long do we wait until we retry the KX?
419 struct GNUNET_TIME_Relative kx_retry_delay;
422 * When do we try the next KX?
424 struct GNUNET_TIME_Absolute next_kx_attempt;
427 * Number of connections in the @e connection_ready_head DLL.
429 unsigned int num_ready_connections;
432 * Number of connections in the @e connection_busy_head DLL.
434 unsigned int num_busy_connections;
437 * How often have we tried and failed to decrypt a message using
438 * the unverified KX material from @e unverified_ax? Used to
439 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
441 unsigned int unverified_attempts;
444 * Number of entries in the @e tq_head DLL.
449 * State of the tunnel encryption.
451 enum CadetTunnelEState estate;
454 * Force triggering KX_AUTH independent of @e estate.
456 int kx_auth_requested;
462 * Am I Alice or Bob, or talking to myself?
464 * @param other the other peer
465 * @return #GNUNET_YES for Alice, #GNUNET_NO for Bob, #GNUNET_SYSERR if talking to myself
468 alice_or_bob (const struct GNUNET_PeerIdentity *other)
470 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
473 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
479 return GNUNET_SYSERR;
485 * Connection @a ct is now unready, clear it's ready flag
486 * and move it from the ready DLL to the busy DLL.
488 * @param ct connection to move to unready status
491 mark_connection_unready (struct CadetTConnection *ct)
493 struct CadetTunnel *t = ct->t;
495 GNUNET_assert (GNUNET_YES == ct->is_ready);
496 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
497 t->connection_ready_tail,
499 GNUNET_assert (0 < t->num_ready_connections);
500 t->num_ready_connections--;
501 ct->is_ready = GNUNET_NO;
502 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
503 t->connection_busy_tail,
505 t->num_busy_connections++;
510 * Get the static string for the peer this tunnel is directed.
514 * @return Static string the destination peer's ID.
517 GCT_2s (const struct CadetTunnel *t)
522 return "Tunnel(NULL)";
523 GNUNET_snprintf (buf,
526 GNUNET_i2s (GCP_get_id (t->destination)));
532 * Get string description for tunnel encryption state.
534 * @param es Tunnel state.
536 * @return String representation.
539 estate2s (enum CadetTunnelEState es)
545 case CADET_TUNNEL_KEY_UNINITIALIZED:
546 return "CADET_TUNNEL_KEY_UNINITIALIZED";
547 case CADET_TUNNEL_KEY_AX_RECV:
548 return "CADET_TUNNEL_KEY_AX_RECV";
549 case CADET_TUNNEL_KEY_AX_SENT:
550 return "CADET_TUNNEL_KEY_AX_SENT";
551 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
552 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
553 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
554 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
555 case CADET_TUNNEL_KEY_OK:
556 return "CADET_TUNNEL_KEY_OK";
558 GNUNET_snprintf (buf,
560 "%u (UNKNOWN STATE)",
568 * Return the peer to which this tunnel goes.
571 * @return the destination of the tunnel
574 GCT_get_destination (struct CadetTunnel *t)
576 return t->destination;
581 * Count channels of a tunnel.
583 * @param t Tunnel on which to count.
585 * @return Number of channels.
588 GCT_count_channels (struct CadetTunnel *t)
590 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
595 * Lookup a channel by its @a ctn.
597 * @param t tunnel to look in
598 * @param ctn number of channel to find
599 * @return NULL if channel does not exist
601 struct CadetChannel *
602 lookup_channel (struct CadetTunnel *t,
603 struct GNUNET_CADET_ChannelTunnelNumber ctn)
605 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
611 * Count all created connections of a tunnel. Not necessarily ready connections!
613 * @param t Tunnel on which to count.
615 * @return Number of connections created, either being established or ready.
618 GCT_count_any_connections (const struct CadetTunnel *t)
620 return t->num_ready_connections + t->num_busy_connections;
625 * Find first connection that is ready in the list of
626 * our connections. Picks ready connections round-robin.
628 * @param t tunnel to search
629 * @return NULL if we have no connection that is ready
631 static struct CadetTConnection *
632 get_ready_connection (struct CadetTunnel *t)
634 struct CadetTConnection *hd = t->connection_ready_head;
636 GNUNET_assert ( (NULL == hd) ||
637 (GNUNET_YES == hd->is_ready) );
643 * Get the encryption state of a tunnel.
647 * @return Tunnel's encryption state.
649 enum CadetTunnelEState
650 GCT_get_estate (struct CadetTunnel *t)
657 * Called when either we have a new connection, or a new message in the
658 * queue, or some existing connection has transmission capacity. Looks
659 * at our message queue and if there is a message, picks a connection
662 * @param cls the `struct CadetTunnel` to process messages on
665 trigger_transmissions (void *cls);
668 /* ************************************** start core crypto ***************************** */
672 * Create a new Axolotl ephemeral (ratchet) key.
674 * @param ax key material to update
677 new_ephemeral (struct CadetTunnelAxolotl *ax)
679 LOG (GNUNET_ERROR_TYPE_DEBUG,
680 "Creating new ephemeral ratchet key (DHRs)\n");
681 GNUNET_assert (GNUNET_OK ==
682 GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
689 * @param plaintext Content to HMAC.
690 * @param size Size of @c plaintext.
691 * @param iv Initialization vector for the message.
692 * @param key Key to use.
693 * @param hmac[out] Destination to store the HMAC.
696 t_hmac (const void *plaintext,
699 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
700 struct GNUNET_ShortHashCode *hmac)
702 static const char ctx[] = "cadet authentication key";
703 struct GNUNET_CRYPTO_AuthKey auth_key;
704 struct GNUNET_HashCode hash;
706 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
712 /* Two step: GNUNET_ShortHash is only 256 bits,
713 GNUNET_HashCode is 512, so we truncate. */
714 GNUNET_CRYPTO_hmac (&auth_key,
727 * @param key Key to use.
728 * @param[out] hash Resulting HMAC.
729 * @param source Source key material (data to HMAC).
730 * @param len Length of @a source.
733 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
734 struct GNUNET_HashCode *hash,
738 static const char ctx[] = "axolotl HMAC-HASH";
739 struct GNUNET_CRYPTO_AuthKey auth_key;
741 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
745 GNUNET_CRYPTO_hmac (&auth_key,
753 * Derive a symmetric encryption key from an HMAC-HASH.
755 * @param key Key to use for the HMAC.
756 * @param[out] out Key to generate.
757 * @param source Source key material (data to HMAC).
758 * @param len Length of @a source.
761 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
762 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
766 static const char ctx[] = "axolotl derive key";
767 struct GNUNET_HashCode h;
773 GNUNET_CRYPTO_kdf (out, sizeof (*out),
781 * Encrypt data with the axolotl tunnel key.
783 * @param ax key material to use.
784 * @param dst Destination with @a size bytes for the encrypted data.
785 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
786 * @param size Size of the buffers at @a src and @a dst
789 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
794 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
795 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
798 ax->ratchet_counter++;
799 if ( (GNUNET_YES == ax->ratchet_allowed) &&
800 ( (ratchet_messages <= ax->ratchet_counter) ||
801 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
803 ax->ratchet_flag = GNUNET_YES;
805 if (GNUNET_YES == ax->ratchet_flag)
807 /* Advance ratchet */
808 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
809 struct GNUNET_HashCode dh;
810 struct GNUNET_HashCode hmac;
811 static const char ctx[] = "axolotl ratchet";
816 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
817 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
820 t_ax_hmac_hash (&ax->RK,
824 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
826 &hmac, sizeof (hmac),
834 ax->ratchet_flag = GNUNET_NO;
835 ax->ratchet_allowed = GNUNET_NO;
836 ax->ratchet_counter = 0;
837 ax->ratchet_expiration
838 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
842 t_hmac_derive_key (&ax->CKs,
846 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
851 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
856 GNUNET_assert (size == out_size);
857 t_hmac_derive_key (&ax->CKs,
865 * Decrypt data with the axolotl tunnel key.
867 * @param ax key material to use.
868 * @param dst Destination for the decrypted data, must contain @a size bytes.
869 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
870 * @param size Size of the @a src and @a dst buffers
873 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
878 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
879 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
882 t_hmac_derive_key (&ax->CKr,
886 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
890 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
891 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
896 GNUNET_assert (out_size == size);
897 t_hmac_derive_key (&ax->CKr,
905 * Encrypt header with the axolotl header key.
907 * @param ax key material to use.
908 * @param[in|out] msg Message whose header to encrypt.
911 t_h_encrypt (struct CadetTunnelAxolotl *ax,
912 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
914 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
917 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
921 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
922 sizeof (struct GNUNET_CADET_AxHeader),
926 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
931 * Decrypt header with the current axolotl header key.
933 * @param ax key material to use.
934 * @param src Message whose header to decrypt.
935 * @param dst Where to decrypt header to.
938 t_h_decrypt (struct CadetTunnelAxolotl *ax,
939 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
940 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
942 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
945 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
949 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
950 sizeof (struct GNUNET_CADET_AxHeader),
954 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
959 * Delete a key from the list of skipped keys.
961 * @param ax key material to delete @a key from.
962 * @param key Key to delete.
965 delete_skipped_key (struct CadetTunnelAxolotl *ax,
966 struct CadetTunnelSkippedKey *key)
968 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
977 * Decrypt and verify data with the appropriate tunnel key and verify that the
978 * data has not been altered since it was sent by the remote peer.
980 * @param ax key material to use.
981 * @param dst Destination for the plaintext.
982 * @param src Source of the message. Can overlap with @c dst.
983 * @param size Size of the message.
984 * @return Size of the decrypted data, -1 if an error was encountered.
987 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
989 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
992 struct CadetTunnelSkippedKey *key;
993 struct GNUNET_ShortHashCode *hmac;
994 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
995 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
996 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
1002 LOG (GNUNET_ERROR_TYPE_DEBUG,
1003 "Trying skipped keys\n");
1004 hmac = &plaintext_header.hmac;
1005 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1007 /* Find a correct Header Key */
1009 for (key = ax->skipped_head; NULL != key; key = key->next)
1011 t_hmac (&src->ax_header,
1012 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1016 if (0 == memcmp (hmac,
1020 valid_HK = &key->HK;
1027 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
1028 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
1029 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1030 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1032 /* Decrypt header */
1033 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1037 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1038 sizeof (struct GNUNET_CADET_AxHeader),
1041 &plaintext_header.ax_header.Ns);
1042 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1044 /* Find the correct message key */
1045 N = ntohl (plaintext_header.ax_header.Ns);
1046 while ( (NULL != key) &&
1049 if ( (NULL == key) ||
1050 (0 != memcmp (&key->HK,
1052 sizeof (*valid_HK))) )
1055 /* Decrypt payload */
1056 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1061 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1066 delete_skipped_key (ax,
1073 * Delete a key from the list of skipped keys.
1075 * @param ax key material to delete from.
1076 * @param HKr Header Key to use.
1079 store_skipped_key (struct CadetTunnelAxolotl *ax,
1080 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1082 struct CadetTunnelSkippedKey *key;
1084 key = GNUNET_new (struct CadetTunnelSkippedKey);
1085 key->timestamp = GNUNET_TIME_absolute_get ();
1088 t_hmac_derive_key (&ax->CKr,
1092 t_hmac_derive_key (&ax->CKr,
1096 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1105 * Stage skipped AX keys and calculate the message key.
1106 * Stores each HK and MK for skipped messages.
1108 * @param ax key material to use
1109 * @param HKr Header key.
1110 * @param Np Received meesage number.
1111 * @return #GNUNET_OK if keys were stored.
1112 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1115 store_ax_keys (struct CadetTunnelAxolotl *ax,
1116 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1122 LOG (GNUNET_ERROR_TYPE_DEBUG,
1123 "Storing skipped keys [%u, %u)\n",
1126 if (MAX_KEY_GAP < gap)
1128 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1129 /* TODO: start new key exchange on return */
1130 GNUNET_break_op (0);
1131 LOG (GNUNET_ERROR_TYPE_WARNING,
1132 "Got message %u, expected %u+\n",
1135 return GNUNET_SYSERR;
1139 /* Delayed message: don't store keys, flag to try old keys. */
1140 return GNUNET_SYSERR;
1144 store_skipped_key (ax,
1147 while (ax->skipped > MAX_SKIPPED_KEYS)
1148 delete_skipped_key (ax,
1155 * Decrypt and verify data with the appropriate tunnel key and verify that the
1156 * data has not been altered since it was sent by the remote peer.
1158 * @param ax key material to use
1159 * @param dst Destination for the plaintext.
1160 * @param src Source of the message. Can overlap with @c dst.
1161 * @param size Size of the message.
1162 * @return Size of the decrypted data, -1 if an error was encountered.
1165 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1167 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1170 struct GNUNET_ShortHashCode msg_hmac;
1171 struct GNUNET_HashCode hmac;
1172 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1175 size_t esize; /* Size of encryped payload */
1177 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1179 /* Try current HK */
1180 t_hmac (&src->ax_header,
1181 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1184 if (0 != memcmp (&msg_hmac,
1188 static const char ctx[] = "axolotl ratchet";
1189 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1190 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1191 struct GNUNET_HashCode dh;
1192 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1195 t_hmac (&src->ax_header,
1196 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1200 if (0 != memcmp (&msg_hmac,
1204 /* Try the skipped keys, if that fails, we're out of luck. */
1205 return try_old_ax_keys (ax,
1215 Np = ntohl (plaintext_header.ax_header.Ns);
1216 PNp = ntohl (plaintext_header.ax_header.PNs);
1217 DHRp = &plaintext_header.ax_header.DHRs;
1222 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1223 GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1226 t_ax_hmac_hash (&ax->RK,
1229 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1231 &hmac, sizeof (hmac),
1234 /* Commit "purported" keys */
1240 ax->ratchet_allowed = GNUNET_YES;
1247 Np = ntohl (plaintext_header.ax_header.Ns);
1248 PNp = ntohl (plaintext_header.ax_header.PNs);
1250 if ( (Np != ax->Nr) &&
1251 (GNUNET_OK != store_ax_keys (ax,
1255 /* Try the skipped keys, if that fails, we're out of luck. */
1256 return try_old_ax_keys (ax,
1272 * Our tunnel became ready for the first time, notify channels
1273 * that have been waiting.
1275 * @param cls our tunnel, not used
1276 * @param key unique ID of the channel, not used
1277 * @param value the `struct CadetChannel` to notify
1278 * @return #GNUNET_OK (continue to iterate)
1281 notify_tunnel_up_cb (void *cls,
1285 struct CadetChannel *ch = value;
1287 GCCH_tunnel_up (ch);
1293 * Change the tunnel encryption state.
1294 * If the encryption state changes to OK, stop the rekey task.
1296 * @param t Tunnel whose encryption state to change, or NULL.
1297 * @param state New encryption state.
1300 GCT_change_estate (struct CadetTunnel *t,
1301 enum CadetTunnelEState state)
1303 enum CadetTunnelEState old = t->estate;
1306 LOG (GNUNET_ERROR_TYPE_DEBUG,
1307 "%s estate changed from %s to %s\n",
1312 if ( (CADET_TUNNEL_KEY_OK != old) &&
1313 (CADET_TUNNEL_KEY_OK == t->estate) )
1315 if (NULL != t->kx_task)
1317 GNUNET_SCHEDULER_cancel (t->kx_task);
1320 /* notify all channels that have been waiting */
1321 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1322 ¬ify_tunnel_up_cb,
1324 if (NULL != t->send_task)
1325 GNUNET_SCHEDULER_cancel (t->send_task);
1326 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1333 * Send a KX message.
1335 * @param t tunnel on which to send the KX_AUTH
1336 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1337 * we are to find one that is ready.
1338 * @param ax axolotl key context to use
1341 send_kx (struct CadetTunnel *t,
1342 struct CadetTConnection *ct,
1343 struct CadetTunnelAxolotl *ax)
1345 struct CadetConnection *cc;
1346 struct GNUNET_MQ_Envelope *env;
1347 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1348 enum GNUNET_CADET_KX_Flags flags;
1350 if (GNUNET_YES != alice_or_bob (GCP_get_id (t->destination)))
1351 return; /* only Alice may send KX */
1352 if ( (NULL == ct) ||
1353 (GNUNET_NO == ct->is_ready) )
1354 ct = get_ready_connection (t);
1357 LOG (GNUNET_ERROR_TYPE_DEBUG,
1358 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1360 estate2s (t->estate));
1361 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1365 env = GNUNET_MQ_msg (msg,
1366 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1367 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1368 msg->flags = htonl (flags);
1369 msg->cid = *GCC_get_id (cc);
1370 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1371 &msg->ephemeral_key);
1372 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1374 mark_connection_unready (ct);
1375 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1376 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1377 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1378 GCT_change_estate (t,
1379 CADET_TUNNEL_KEY_AX_SENT);
1380 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1381 GCT_change_estate (t,
1382 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1385 GNUNET_STATISTICS_update (stats,
1393 * Send a KX_AUTH message.
1395 * @param t tunnel on which to send the KX_AUTH
1396 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1397 * we are to find one that is ready.
1398 * @param ax axolotl key context to use
1399 * @param force_reply Force the other peer to reply with a KX_AUTH message
1400 * (set if we would like to transmit right now, but cannot)
1403 send_kx_auth (struct CadetTunnel *t,
1404 struct CadetTConnection *ct,
1405 struct CadetTunnelAxolotl *ax,
1408 struct CadetConnection *cc;
1409 struct GNUNET_MQ_Envelope *env;
1410 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1411 enum GNUNET_CADET_KX_Flags flags;
1413 if ( (NULL == ct) ||
1414 (GNUNET_NO == ct->is_ready) )
1415 ct = get_ready_connection (t);
1418 LOG (GNUNET_ERROR_TYPE_DEBUG,
1419 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1421 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1422 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1425 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1427 env = GNUNET_MQ_msg (msg,
1428 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1429 flags = GNUNET_CADET_KX_FLAG_NONE;
1430 if (GNUNET_YES == force_reply)
1431 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1432 msg->kx.flags = htonl (flags);
1433 msg->kx.cid = *GCC_get_id (cc);
1434 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1435 &msg->kx.ephemeral_key);
1436 GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1437 &msg->kx.ratchet_key);
1438 /* Compute authenticator (this is the main difference to #send_kx()) */
1439 GNUNET_CRYPTO_hash (&ax->RK,
1442 /* Compute when to be triggered again; actual job will
1443 be scheduled via #connection_ready_cb() */
1445 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1447 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1449 /* Send via cc, mark it as unready */
1450 mark_connection_unready (ct);
1452 /* Update state machine, unless we are already OK */
1453 if (CADET_TUNNEL_KEY_OK != t->estate)
1454 GCT_change_estate (t,
1455 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1458 GNUNET_STATISTICS_update (stats,
1459 "# KX_AUTH transmitted",
1466 * Cleanup state used by @a ax.
1468 * @param ax state to free, but not memory of @a ax itself
1471 cleanup_ax (struct CadetTunnelAxolotl *ax)
1473 while (NULL != ax->skipped_head)
1474 delete_skipped_key (ax,
1476 GNUNET_assert (0 == ax->skipped);
1477 GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1478 GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1483 * Update our Axolotl key state based on the KX data we received.
1484 * Computes the new chain keys, and root keys, etc, and also checks
1485 * wether this is a replay of the current chain.
1487 * @param[in|out] axolotl chain key state to recompute
1488 * @param pid peer identity of the other peer
1489 * @param ephemeral_key ephemeral public key of the other peer
1490 * @param ratchet_key senders next ephemeral public key
1491 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1492 * root key is already in @a ax and thus the KX is useless;
1493 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1496 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1497 const struct GNUNET_PeerIdentity *pid,
1498 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1499 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1501 struct GNUNET_HashCode key_material[3];
1502 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1503 const char salt[] = "CADET Axolotl salt";
1506 if (GNUNET_SYSERR == (am_I_alice = alice_or_bob (pid)))
1508 GNUNET_break_op (0);
1509 return GNUNET_SYSERR;
1511 if (0 == memcmp (&ax->DHRr,
1513 sizeof (*ratchet_key)))
1515 GNUNET_STATISTICS_update (stats,
1516 "# Ratchet key already known",
1519 LOG (GNUNET_ERROR_TYPE_DEBUG,
1520 "Ratchet key already known. Ignoring KX.\n");
1524 ax->DHRr = *ratchet_key;
1525 ax->last_ephemeral = *ephemeral_key;
1527 if (GNUNET_YES == am_I_alice)
1529 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* a */
1530 ephemeral_key, /* B0 */
1535 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* b0 */
1536 &pid->public_key, /* A */
1540 if (GNUNET_YES == am_I_alice)
1542 GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* a0 */
1543 &pid->public_key, /* B */
1548 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* b */
1549 ephemeral_key, /* A0 */
1554 GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0, /* a0 or b0 */
1555 ephemeral_key, /* B0 or A0 */
1558 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1559 salt, sizeof (salt),
1560 &key_material, sizeof (key_material),
1563 if (0 == memcmp (&ax->RK,
1567 LOG (GNUNET_ERROR_TYPE_DEBUG,
1568 "Root key already known. Ignoring KX.\n");
1569 GNUNET_STATISTICS_update (stats,
1570 "# Root key already known",
1577 if (GNUNET_YES == am_I_alice)
1583 ax->ratchet_flag = GNUNET_YES;
1591 ax->ratchet_flag = GNUNET_NO;
1592 ax->ratchet_expiration
1593 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1601 * Try to redo the KX or KX_AUTH handshake, if we can.
1603 * @param cls the `struct CadetTunnel` to do KX for.
1606 retry_kx (void *cls)
1608 struct CadetTunnel *t = cls;
1609 struct CadetTunnelAxolotl *ax;
1612 LOG (GNUNET_ERROR_TYPE_DEBUG,
1613 "Trying to make KX progress on %s in state %s\n",
1615 estate2s (t->estate));
1618 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1619 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1624 case CADET_TUNNEL_KEY_AX_RECV:
1625 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1626 /* We are responding, so only require reply
1627 if WE have a channel waiting. */
1628 if (NULL != t->unverified_ax)
1630 /* Send AX_AUTH so we might get this one verified */
1631 ax = t->unverified_ax;
1635 /* How can this be? */
1642 (0 == GCT_count_channels (t))
1646 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1647 /* We are responding, so only require reply
1648 if WE have a channel waiting. */
1649 if (NULL != t->unverified_ax)
1651 /* Send AX_AUTH so we might get this one verified */
1652 ax = t->unverified_ax;
1656 /* How can this be? */
1663 (0 == GCT_count_channels (t))
1667 case CADET_TUNNEL_KEY_OK:
1668 /* Must have been the *other* peer asking us to
1669 respond with a KX_AUTH. */
1670 if (NULL != t->unverified_ax)
1672 /* Sending AX_AUTH in response to AX so we might get this one verified */
1673 ax = t->unverified_ax;
1677 /* Sending AX_AUTH in response to AX_AUTH */
1690 * Handle KX message that lacks authentication (and which will thus
1691 * only be considered authenticated after we respond with our own
1692 * KX_AUTH and finally successfully decrypt payload).
1694 * @param ct connection/tunnel combo that received encrypted message
1695 * @param msg the key exchange message
1698 GCT_handle_kx (struct CadetTConnection *ct,
1699 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1701 struct CadetTunnel *t = ct->t;
1704 GNUNET_STATISTICS_update (stats,
1708 if (GNUNET_YES == alice_or_bob (GCP_get_id (t->destination)))
1710 /* Bob is not allowed to send KX! */
1711 GNUNET_break_op (0);
1716 memcmp (&t->ax.DHRr,
1718 sizeof (msg->ratchet_key))) &&
1720 memcmp (&t->ax.last_ephemeral,
1721 &msg->ephemeral_key,
1722 sizeof (msg->ephemeral_key))) )
1725 GNUNET_STATISTICS_update (stats,
1726 "# Duplicate KX received",
1736 /* We only keep ONE unverified KX around, so if there is an existing one,
1738 if (NULL != t->unverified_ax)
1741 memcmp (&t->unverified_ax->DHRr,
1743 sizeof (msg->ratchet_key))) &&
1745 memcmp (&t->unverified_ax->last_ephemeral,
1746 &msg->ephemeral_key,
1747 sizeof (msg->ephemeral_key))) )
1749 GNUNET_STATISTICS_update (stats,
1750 "# Duplicate unverified KX received",
1761 LOG (GNUNET_ERROR_TYPE_DEBUG,
1762 "Dropping old unverified KX state.\n");
1763 GNUNET_STATISTICS_update (stats,
1764 "# Unverified KX dropped for fresh KX",
1767 GNUNET_break (NULL == t->unverified_ax->skipped_head);
1768 memset (t->unverified_ax,
1770 sizeof (struct CadetTunnelAxolotl));
1774 LOG (GNUNET_ERROR_TYPE_DEBUG,
1775 "Creating fresh unverified KX for %s\n",
1777 GNUNET_STATISTICS_update (stats,
1781 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1783 /* Set as the 'current' RK/DHRr the one we are currently using,
1784 so that the duplicate-detection logic of
1785 #update_ax_by_kx can work. */
1786 t->unverified_ax->RK = t->ax.RK;
1787 t->unverified_ax->DHRr = t->ax.DHRr;
1788 t->unverified_ax->DHRs = t->ax.DHRs;
1789 t->unverified_ax->kx_0 = t->ax.kx_0;
1790 t->unverified_attempts = 0;
1792 /* Update 'ax' by the new key material */
1793 ret = update_ax_by_kx (t->unverified_ax,
1794 GCP_get_id (t->destination),
1795 &msg->ephemeral_key,
1797 GNUNET_break (GNUNET_SYSERR != ret);
1798 if (GNUNET_OK != ret)
1800 GNUNET_STATISTICS_update (stats,
1804 return; /* duplicate KX, nothing to do */
1806 /* move ahead in our state machine */
1807 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1808 GCT_change_estate (t,
1809 CADET_TUNNEL_KEY_AX_RECV);
1810 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1811 GCT_change_estate (t,
1812 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1814 /* KX is still not done, try again our end. */
1815 if (CADET_TUNNEL_KEY_OK != t->estate)
1817 if (NULL != t->kx_task)
1818 GNUNET_SCHEDULER_cancel (t->kx_task);
1820 = GNUNET_SCHEDULER_add_now (&retry_kx,
1827 * Handle KX_AUTH message.
1829 * @param ct connection/tunnel combo that received encrypted message
1830 * @param msg the key exchange message
1833 GCT_handle_kx_auth (struct CadetTConnection *ct,
1834 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1836 struct CadetTunnel *t = ct->t;
1837 struct CadetTunnelAxolotl ax_tmp;
1838 struct GNUNET_HashCode kx_auth;
1841 GNUNET_STATISTICS_update (stats,
1842 "# KX_AUTH received",
1845 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1846 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1848 /* Confusing, we got a KX_AUTH before we even send our own
1849 KX. This should not happen. We'll send our own KX ASAP anyway,
1850 so let's ignore this here. */
1851 GNUNET_break_op (0);
1854 LOG (GNUNET_ERROR_TYPE_DEBUG,
1855 "Handling KX_AUTH message for %s\n",
1857 /* We do everything in ax_tmp until we've checked the authentication
1858 so we don't clobber anything we care about by accident. */
1861 /* Update 'ax' by the new key material */
1862 ret = update_ax_by_kx (&ax_tmp,
1863 GCP_get_id (t->destination),
1864 &msg->kx.ephemeral_key,
1865 &msg->kx.ratchet_key);
1866 if (GNUNET_OK != ret)
1868 if (GNUNET_NO == ret)
1869 GNUNET_STATISTICS_update (stats,
1870 "# redundant KX_AUTH received",
1874 GNUNET_break (0); /* connect to self!? */
1877 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1880 if (0 != memcmp (&kx_auth,
1884 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1885 we transmitted to the sender, refuse it, try KX again. */
1886 GNUNET_STATISTICS_update (stats,
1887 "# KX_AUTH not using our last KX received (auth failure)",
1890 LOG (GNUNET_ERROR_TYPE_WARNING,
1891 "KX AUTH missmatch!\n");
1892 if (NULL == t->kx_task)
1894 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1899 /* Yep, we're good. */
1901 if (NULL != t->unverified_ax)
1903 /* We got some "stale" KX before, drop that. */
1904 cleanup_ax (t->unverified_ax);
1905 GNUNET_free (t->unverified_ax);
1906 t->unverified_ax = NULL;
1909 /* move ahead in our state machine */
1912 case CADET_TUNNEL_KEY_UNINITIALIZED:
1913 case CADET_TUNNEL_KEY_AX_RECV:
1914 /* Checked above, this is impossible. */
1917 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1918 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1919 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1920 GCT_change_estate (t,
1921 CADET_TUNNEL_KEY_OK);
1923 case CADET_TUNNEL_KEY_OK:
1924 /* Did not expect another KX_AUTH, but so what, still acceptable.
1925 Nothing to do here. */
1932 /* ************************************** end core crypto ***************************** */
1936 * Compute the next free channel tunnel number for this tunnel.
1938 * @param t the tunnel
1939 * @return unused number that can uniquely identify a channel in the tunnel
1941 static struct GNUNET_CADET_ChannelTunnelNumber
1942 get_next_free_ctn (struct CadetTunnel *t)
1944 #define HIGH_BIT 0x8000000
1945 struct GNUNET_CADET_ChannelTunnelNumber ret;
1950 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1951 GCP_get_id (GCT_get_destination (t)));
1957 GNUNET_assert (0); // loopback must never go here!
1958 ctn = ntohl (t->next_ctn.cn);
1960 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1963 ctn = ((ctn + 1) & (~ HIGH_BIT));
1965 t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
1966 ret.cn = htonl (ctn | highbit);
1972 * Add a channel to a tunnel, and notify channel that we are ready
1973 * for transmission if we are already up. Otherwise that notification
1974 * will be done later in #notify_tunnel_up_cb().
1978 * @return unique number identifying @a ch within @a t
1980 struct GNUNET_CADET_ChannelTunnelNumber
1981 GCT_add_channel (struct CadetTunnel *t,
1982 struct CadetChannel *ch)
1984 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1986 ctn = get_next_free_ctn (t);
1987 if (NULL != t->destroy_task)
1989 GNUNET_SCHEDULER_cancel (t->destroy_task);
1990 t->destroy_task = NULL;
1992 GNUNET_assert (GNUNET_YES ==
1993 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1996 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1997 LOG (GNUNET_ERROR_TYPE_DEBUG,
1998 "Adding %s to %s\n",
2003 case CADET_TUNNEL_KEY_UNINITIALIZED:
2004 /* waiting for connection to start KX */
2006 case CADET_TUNNEL_KEY_AX_RECV:
2007 case CADET_TUNNEL_KEY_AX_SENT:
2008 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2009 /* we're currently waiting for KX to complete */
2011 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2012 /* waiting for OTHER peer to send us data,
2013 we might need to prompt more aggressively! */
2014 if (NULL == t->kx_task)
2016 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2020 case CADET_TUNNEL_KEY_OK:
2021 /* We are ready. Tell the new channel that we are up. */
2022 GCCH_tunnel_up (ch);
2030 * We lost a connection, remove it from our list and clean up
2031 * the connection object itself.
2033 * @param ct binding of connection to tunnel of the connection that was lost.
2036 GCT_connection_lost (struct CadetTConnection *ct)
2038 struct CadetTunnel *t = ct->t;
2040 if (GNUNET_YES == ct->is_ready)
2042 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
2043 t->connection_ready_tail,
2045 t->num_ready_connections--;
2049 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2050 t->connection_busy_tail,
2052 t->num_busy_connections--;
2059 * Clean up connection @a ct of a tunnel.
2061 * @param cls the `struct CadetTunnel`
2062 * @param ct connection to clean up
2065 destroy_t_connection (void *cls,
2066 struct CadetTConnection *ct)
2068 struct CadetTunnel *t = cls;
2069 struct CadetConnection *cc = ct->cc;
2071 GNUNET_assert (ct->t == t);
2072 GCT_connection_lost (ct);
2073 GCC_destroy_without_tunnel (cc);
2078 * This tunnel is no longer used, destroy it.
2080 * @param cls the idle tunnel
2083 destroy_tunnel (void *cls)
2085 struct CadetTunnel *t = cls;
2086 struct CadetTunnelQueueEntry *tq;
2088 t->destroy_task = NULL;
2089 LOG (GNUNET_ERROR_TYPE_DEBUG,
2090 "Destroying idle %s\n",
2092 GNUNET_assert (0 == GCT_count_channels (t));
2093 GCT_iterate_connections (t,
2094 &destroy_t_connection,
2096 GNUNET_assert (NULL == t->connection_ready_head);
2097 GNUNET_assert (NULL == t->connection_busy_head);
2098 while (NULL != (tq = t->tq_head))
2100 if (NULL != tq->cont)
2101 tq->cont (tq->cont_cls,
2103 GCT_send_cancel (tq);
2105 GCP_drop_tunnel (t->destination,
2107 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2108 if (NULL != t->maintain_connections_task)
2110 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2111 t->maintain_connections_task = NULL;
2113 if (NULL != t->send_task)
2115 GNUNET_SCHEDULER_cancel (t->send_task);
2116 t->send_task = NULL;
2118 if (NULL != t->kx_task)
2120 GNUNET_SCHEDULER_cancel (t->kx_task);
2123 GNUNET_MST_destroy (t->mst);
2124 GNUNET_MQ_destroy (t->mq);
2125 if (NULL != t->unverified_ax)
2127 cleanup_ax (t->unverified_ax);
2128 GNUNET_free (t->unverified_ax);
2130 cleanup_ax (&t->ax);
2131 GNUNET_assert (NULL == t->destroy_task);
2137 * Remove a channel from a tunnel.
2141 * @param ctn unique number identifying @a ch within @a t
2144 GCT_remove_channel (struct CadetTunnel *t,
2145 struct CadetChannel *ch,
2146 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2148 LOG (GNUNET_ERROR_TYPE_DEBUG,
2149 "Removing %s from %s\n",
2152 GNUNET_assert (GNUNET_YES ==
2153 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2157 GCT_count_channels (t)) &&
2158 (NULL == t->destroy_task) )
2161 = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2169 * Destroy remaining channels during shutdown.
2171 * @param cls the `struct CadetTunnel` of the channel
2172 * @param key key of the channel
2173 * @param value the `struct CadetChannel`
2174 * @return #GNUNET_OK (continue to iterate)
2177 destroy_remaining_channels (void *cls,
2181 struct CadetChannel *ch = value;
2183 GCCH_handle_remote_destroy (ch,
2190 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2192 * @param t tunnel to destroy
2195 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2197 GNUNET_assert (GNUNET_YES == shutting_down);
2198 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2199 &destroy_remaining_channels,
2202 GCT_count_channels (t));
2203 if (NULL != t->destroy_task)
2205 GNUNET_SCHEDULER_cancel (t->destroy_task);
2206 t->destroy_task = NULL;
2213 * Send normal payload from queue in @a t via connection @a ct.
2214 * Does nothing if our payload queue is empty.
2216 * @param t tunnel to send data from
2217 * @param ct connection to use for transmission (is ready)
2220 try_send_normal_payload (struct CadetTunnel *t,
2221 struct CadetTConnection *ct)
2223 struct CadetTunnelQueueEntry *tq;
2225 GNUNET_assert (GNUNET_YES == ct->is_ready);
2229 /* no messages pending right now */
2230 LOG (GNUNET_ERROR_TYPE_DEBUG,
2231 "Not sending payload of %s on ready %s (nothing pending)\n",
2236 /* ready to send message 'tq' on tunnel 'ct' */
2237 GNUNET_assert (t == tq->t);
2238 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2241 if (NULL != tq->cid)
2242 *tq->cid = *GCC_get_id (ct->cc);
2243 mark_connection_unready (ct);
2244 LOG (GNUNET_ERROR_TYPE_DEBUG,
2245 "Sending payload of %s on %s\n",
2248 GCC_transmit (ct->cc,
2250 if (NULL != tq->cont)
2251 tq->cont (tq->cont_cls,
2252 GCC_get_id (ct->cc));
2258 * A connection is @a is_ready for transmission. Looks at our message
2259 * queue and if there is a message, sends it out via the connection.
2261 * @param cls the `struct CadetTConnection` that is @a is_ready
2262 * @param is_ready #GNUNET_YES if connection are now ready,
2263 * #GNUNET_NO if connection are no longer ready
2266 connection_ready_cb (void *cls,
2269 struct CadetTConnection *ct = cls;
2270 struct CadetTunnel *t = ct->t;
2272 if (GNUNET_NO == is_ready)
2274 LOG (GNUNET_ERROR_TYPE_DEBUG,
2275 "%s no longer ready for %s\n",
2278 mark_connection_unready (ct);
2281 GNUNET_assert (GNUNET_NO == ct->is_ready);
2282 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2283 t->connection_busy_tail,
2285 GNUNET_assert (0 < t->num_busy_connections);
2286 t->num_busy_connections--;
2287 ct->is_ready = GNUNET_YES;
2288 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2289 t->connection_ready_tail,
2291 t->num_ready_connections++;
2293 LOG (GNUNET_ERROR_TYPE_DEBUG,
2294 "%s now ready for %s in state %s\n",
2297 estate2s (t->estate));
2300 case CADET_TUNNEL_KEY_UNINITIALIZED:
2301 /* Do not begin KX if WE have no channels waiting! */
2302 if (0 == GCT_count_channels (t))
2304 /* We are uninitialized, just transmit immediately,
2305 without undue delay. */
2306 if (NULL != t->kx_task)
2308 GNUNET_SCHEDULER_cancel (t->kx_task);
2315 case CADET_TUNNEL_KEY_AX_RECV:
2316 case CADET_TUNNEL_KEY_AX_SENT:
2317 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2318 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2319 /* we're currently waiting for KX to complete, schedule job */
2320 if (NULL == t->kx_task)
2322 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2326 case CADET_TUNNEL_KEY_OK:
2327 if (GNUNET_YES == t->kx_auth_requested)
2329 if (NULL != t->kx_task)
2331 GNUNET_SCHEDULER_cancel (t->kx_task);
2340 try_send_normal_payload (t,
2348 * Called when either we have a new connection, or a new message in the
2349 * queue, or some existing connection has transmission capacity. Looks
2350 * at our message queue and if there is a message, picks a connection
2353 * @param cls the `struct CadetTunnel` to process messages on
2356 trigger_transmissions (void *cls)
2358 struct CadetTunnel *t = cls;
2359 struct CadetTConnection *ct;
2361 t->send_task = NULL;
2362 if (NULL == t->tq_head)
2363 return; /* no messages pending right now */
2364 ct = get_ready_connection (t);
2366 return; /* no connections ready */
2367 try_send_normal_payload (t,
2373 * Closure for #evaluate_connection. Used to assemble summary information
2374 * about the existing connections so we can evaluate a new path.
2376 struct EvaluationSummary
2380 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2382 unsigned int min_length;
2385 * Maximum length of any of our connections, 0 if we have none.
2387 unsigned int max_length;
2390 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2392 GNUNET_CONTAINER_HeapCostType min_desire;
2395 * Maximum desirability of any of our connections, 0 if we have none.
2397 GNUNET_CONTAINER_HeapCostType max_desire;
2400 * Path we are comparing against for #evaluate_connection, can be NULL.
2402 struct CadetPeerPath *path;
2405 * Connection deemed the "worst" so far encountered by #evaluate_connection,
2406 * NULL if we did not yet encounter any connections.
2408 struct CadetTConnection *worst;
2411 * Numeric score of @e worst, only set if @e worst is non-NULL.
2416 * Set to #GNUNET_YES if we have a connection over @e path already.
2424 * Evaluate a connection, updating our summary information in @a cls about
2425 * what kinds of connections we have.
2427 * @param cls the `struct EvaluationSummary *` to update
2428 * @param ct a connection to include in the summary
2431 evaluate_connection (void *cls,
2432 struct CadetTConnection *ct)
2434 struct EvaluationSummary *es = cls;
2435 struct CadetConnection *cc = ct->cc;
2436 struct CadetPeerPath *ps = GCC_get_path (cc);
2437 const struct CadetConnectionMetrics *metrics;
2438 GNUNET_CONTAINER_HeapCostType ct_desirability;
2439 struct GNUNET_TIME_Relative uptime;
2440 struct GNUNET_TIME_Relative last_use;
2443 double success_rate;
2447 LOG (GNUNET_ERROR_TYPE_DEBUG,
2448 "Ignoring duplicate path %s.\n",
2449 GCPP_2s (es->path));
2450 es->duplicate = GNUNET_YES;
2453 ct_desirability = GCPP_get_desirability (ps);
2454 ct_length = GCPP_get_length (ps);
2455 metrics = GCC_get_metrics (cc);
2456 uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2457 last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2458 /* We add 1.0 here to avoid division by zero. */
2459 success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2462 + 100.0 / (1.0 + ct_length) /* longer paths = better */
2463 + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2464 - last_use.rel_value_us / 1000L; /* longer idle = worse */
2465 score *= success_rate; /* weigh overall by success rate */
2467 if ( (NULL == es->worst) ||
2468 (score < es->worst_score) )
2471 es->worst_score = score;
2473 es->min_length = GNUNET_MIN (es->min_length,
2475 es->max_length = GNUNET_MAX (es->max_length,
2477 es->min_desire = GNUNET_MIN (es->min_desire,
2479 es->max_desire = GNUNET_MAX (es->max_desire,
2485 * Consider using the path @a p for the tunnel @a t.
2486 * The tunnel destination is at offset @a off in path @a p.
2488 * @param cls our tunnel
2489 * @param path a path to our destination
2490 * @param off offset of the destination on path @a path
2491 * @return #GNUNET_YES (should keep iterating)
2494 consider_path_cb (void *cls,
2495 struct CadetPeerPath *path,
2498 struct CadetTunnel *t = cls;
2499 struct EvaluationSummary es;
2500 struct CadetTConnection *ct;
2502 GNUNET_assert (off < GCPP_get_length (path));
2503 es.min_length = UINT_MAX;
2506 es.min_desire = UINT64_MAX;
2508 es.duplicate = GNUNET_NO;
2511 /* Compute evaluation summary over existing connections. */
2512 GCT_iterate_connections (t,
2513 &evaluate_connection,
2515 if (GNUNET_YES == es.duplicate)
2518 /* FIXME: not sure we should really just count
2519 'num_connections' here, as they may all have
2520 consistently failed to connect. */
2522 /* We iterate by increasing path length; if we have enough paths and
2523 this one is more than twice as long than what we are currently
2524 using, then ignore all of these super-long ones! */
2525 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2526 (es.min_length * 2 < off) &&
2527 (es.max_length < off) )
2529 LOG (GNUNET_ERROR_TYPE_DEBUG,
2530 "Ignoring paths of length %u, they are way too long.\n",
2534 /* If we have enough paths and this one looks no better, ignore it. */
2535 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2536 (es.min_length < GCPP_get_length (path)) &&
2537 (es.min_desire > GCPP_get_desirability (path)) &&
2538 (es.max_length < off) )
2540 LOG (GNUNET_ERROR_TYPE_DEBUG,
2541 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2542 GCPP_get_length (path),
2543 (unsigned long long) GCPP_get_desirability (path),
2544 GCP_2s (t->destination));
2548 /* Path is interesting (better by some metric, or we don't have
2549 enough paths yet). */
2550 ct = GNUNET_new (struct CadetTConnection);
2551 ct->created = GNUNET_TIME_absolute_get ();
2553 ct->cc = GCC_create (t->destination,
2556 GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2558 &connection_ready_cb,
2561 /* FIXME: schedule job to kill connection (and path?) if it takes
2562 too long to get ready! (And track performance data on how long
2563 other connections took with the tunnel!)
2564 => Note: to be done within 'connection'-logic! */
2565 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2566 t->connection_busy_tail,
2568 t->num_busy_connections++;
2569 LOG (GNUNET_ERROR_TYPE_DEBUG,
2570 "Found interesting path %s for %s, created %s\n",
2579 * Function called to maintain the connections underlying our tunnel.
2580 * Tries to maintain (incl. tear down) connections for the tunnel, and
2581 * if there is a significant change, may trigger transmissions.
2583 * Basically, needs to check if there are connections that perform
2584 * badly, and if so eventually kill them and trigger a replacement.
2585 * The strategy is to open one more connection than
2586 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2587 * least-performing one, and then inquire for new ones.
2589 * @param cls the `struct CadetTunnel`
2592 maintain_connections_cb (void *cls)
2594 struct CadetTunnel *t = cls;
2595 struct GNUNET_TIME_Relative delay;
2596 struct EvaluationSummary es;
2598 t->maintain_connections_task = NULL;
2599 LOG (GNUNET_ERROR_TYPE_DEBUG,
2600 "Performing connection maintenance for %s.\n",
2603 es.min_length = UINT_MAX;
2606 es.min_desire = UINT64_MAX;
2609 es.duplicate = GNUNET_NO;
2610 GCT_iterate_connections (t,
2611 &evaluate_connection,
2613 if ( (NULL != es.worst) &&
2614 (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2616 /* Clear out worst-performing connection 'es.worst'. */
2617 destroy_t_connection (t,
2621 /* Consider additional paths */
2622 (void) GCP_iterate_paths (t->destination,
2626 /* FIXME: calculate when to try again based on how well we are doing;
2627 in particular, if we have to few connections, we might be able
2628 to do without this (as PATHS should tell us whenever a new path
2629 is available instantly; however, need to make sure this job is
2630 restarted after that happens).
2631 Furthermore, if the paths we do know are in a reasonably narrow
2632 quality band and are plentyful, we might also consider us stabilized
2633 and then reduce the frequency accordingly. */
2634 delay = GNUNET_TIME_UNIT_MINUTES;
2635 t->maintain_connections_task
2636 = GNUNET_SCHEDULER_add_delayed (delay,
2637 &maintain_connections_cb,
2643 * Consider using the path @a p for the tunnel @a t.
2644 * The tunnel destination is at offset @a off in path @a p.
2646 * @param cls our tunnel
2647 * @param path a path to our destination
2648 * @param off offset of the destination on path @a path
2651 GCT_consider_path (struct CadetTunnel *t,
2652 struct CadetPeerPath *p,
2655 LOG (GNUNET_ERROR_TYPE_DEBUG,
2656 "Considering %s for %s\n",
2659 (void) consider_path_cb (t,
2666 * We got a keepalive. Track in statistics.
2668 * @param cls the `struct CadetTunnel` for which we decrypted the message
2669 * @param msg the message we received on the tunnel
2672 handle_plaintext_keepalive (void *cls,
2673 const struct GNUNET_MessageHeader *msg)
2675 struct CadetTunnel *t = cls;
2677 LOG (GNUNET_ERROR_TYPE_DEBUG,
2678 "Received KEEPALIVE on %s\n",
2680 GNUNET_STATISTICS_update (stats,
2681 "# keepalives received",
2688 * Check that @a msg is well-formed.
2690 * @param cls the `struct CadetTunnel` for which we decrypted the message
2691 * @param msg the message we received on the tunnel
2692 * @return #GNUNET_OK (any variable-size payload goes)
2695 check_plaintext_data (void *cls,
2696 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2703 * We received payload data for a channel. Locate the channel
2704 * and process the data, or return an error if the channel is unknown.
2706 * @param cls the `struct CadetTunnel` for which we decrypted the message
2707 * @param msg the message we received on the tunnel
2710 handle_plaintext_data (void *cls,
2711 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2713 struct CadetTunnel *t = cls;
2714 struct CadetChannel *ch;
2716 ch = lookup_channel (t,
2720 /* We don't know about such a channel, might have been destroyed on our
2721 end in the meantime, or never existed. Send back a DESTROY. */
2722 LOG (GNUNET_ERROR_TYPE_DEBUG,
2723 "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2724 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2725 ntohl (msg->ctn.cn));
2726 GCT_send_channel_destroy (t,
2730 GCCH_handle_channel_plaintext_data (ch,
2731 GCC_get_id (t->current_ct->cc),
2737 * We received an acknowledgement for data we sent on a channel.
2738 * Locate the channel and process it, or return an error if the
2739 * channel is unknown.
2741 * @param cls the `struct CadetTunnel` for which we decrypted the message
2742 * @param ack the message we received on the tunnel
2745 handle_plaintext_data_ack (void *cls,
2746 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2748 struct CadetTunnel *t = cls;
2749 struct CadetChannel *ch;
2751 ch = lookup_channel (t,
2755 /* We don't know about such a channel, might have been destroyed on our
2756 end in the meantime, or never existed. Send back a DESTROY. */
2757 LOG (GNUNET_ERROR_TYPE_DEBUG,
2758 "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2759 ntohl (ack->ctn.cn));
2760 GCT_send_channel_destroy (t,
2764 GCCH_handle_channel_plaintext_data_ack (ch,
2765 GCC_get_id (t->current_ct->cc),
2771 * We have received a request to open a channel to a port from
2772 * another peer. Creates the incoming channel.
2774 * @param cls the `struct CadetTunnel` for which we decrypted the message
2775 * @param copen the message we received on the tunnel
2778 handle_plaintext_channel_open (void *cls,
2779 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2781 struct CadetTunnel *t = cls;
2782 struct CadetChannel *ch;
2784 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2785 ntohl (copen->ctn.cn));
2788 LOG (GNUNET_ERROR_TYPE_DEBUG,
2789 "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n",
2790 GNUNET_h2s (&copen->h_port),
2793 GCCH_handle_duplicate_open (ch,
2794 GCC_get_id (t->current_ct->cc));
2797 LOG (GNUNET_ERROR_TYPE_DEBUG,
2798 "Received CHANNEL_OPEN on h_port %s from %s\n",
2799 GNUNET_h2s (&copen->h_port),
2801 ch = GCCH_channel_incoming_new (t,
2804 ntohl (copen->opt));
2805 if (NULL != t->destroy_task)
2807 GNUNET_SCHEDULER_cancel (t->destroy_task);
2808 t->destroy_task = NULL;
2810 GNUNET_assert (GNUNET_OK ==
2811 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2812 ntohl (copen->ctn.cn),
2814 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2819 * Send a DESTROY message via the tunnel.
2821 * @param t the tunnel to transmit over
2822 * @param ctn ID of the channel to destroy
2825 GCT_send_channel_destroy (struct CadetTunnel *t,
2826 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2828 struct GNUNET_CADET_ChannelDestroyMessage msg;
2830 LOG (GNUNET_ERROR_TYPE_DEBUG,
2831 "Sending DESTORY message for channel ID %u\n",
2833 msg.header.size = htons (sizeof (msg));
2834 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2835 msg.reserved = htonl (0);
2845 * We have received confirmation from the target peer that the
2846 * given channel could be established (the port is open).
2849 * @param cls the `struct CadetTunnel` for which we decrypted the message
2850 * @param cm the message we received on the tunnel
2853 handle_plaintext_channel_open_ack (void *cls,
2854 const struct GNUNET_CADET_ChannelOpenAckMessage *cm)
2856 struct CadetTunnel *t = cls;
2857 struct CadetChannel *ch;
2859 ch = lookup_channel (t,
2863 /* We don't know about such a channel, might have been destroyed on our
2864 end in the meantime, or never existed. Send back a DESTROY. */
2865 LOG (GNUNET_ERROR_TYPE_DEBUG,
2866 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2867 ntohl (cm->ctn.cn));
2868 GCT_send_channel_destroy (t,
2872 LOG (GNUNET_ERROR_TYPE_DEBUG,
2873 "Received channel OPEN_ACK on channel %s from %s\n",
2876 GCCH_handle_channel_open_ack (ch,
2877 GCC_get_id (t->current_ct->cc),
2883 * We received a message saying that a channel should be destroyed.
2884 * Pass it on to the correct channel.
2886 * @param cls the `struct CadetTunnel` for which we decrypted the message
2887 * @param cm the message we received on the tunnel
2890 handle_plaintext_channel_destroy (void *cls,
2891 const struct GNUNET_CADET_ChannelDestroyMessage *cm)
2893 struct CadetTunnel *t = cls;
2894 struct CadetChannel *ch;
2896 ch = lookup_channel (t,
2900 /* We don't know about such a channel, might have been destroyed on our
2901 end in the meantime, or never existed. */
2902 LOG (GNUNET_ERROR_TYPE_DEBUG,
2903 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2904 ntohl (cm->ctn.cn));
2907 LOG (GNUNET_ERROR_TYPE_DEBUG,
2908 "Received channel DESTROY on %s from %s\n",
2911 GCCH_handle_remote_destroy (ch,
2912 GCC_get_id (t->current_ct->cc));
2917 * Handles a message we decrypted, by injecting it into
2918 * our message queue (which will do the dispatching).
2920 * @param cls the `struct CadetTunnel` that got the message
2921 * @param msg the message
2922 * @return #GNUNET_OK on success (always)
2923 * #GNUNET_NO to stop further processing (no error)
2924 * #GNUNET_SYSERR to stop further processing with error
2927 handle_decrypted (void *cls,
2928 const struct GNUNET_MessageHeader *msg)
2930 struct CadetTunnel *t = cls;
2932 GNUNET_assert (NULL != t->current_ct);
2933 GNUNET_MQ_inject_message (t->mq,
2940 * Function called if we had an error processing
2941 * an incoming decrypted message.
2943 * @param cls the `struct CadetTunnel`
2944 * @param error error code
2947 decrypted_error_cb (void *cls,
2948 enum GNUNET_MQ_Error error)
2950 GNUNET_break_op (0);
2955 * Create a tunnel to @a destionation. Must only be called
2956 * from within #GCP_get_tunnel().
2958 * @param destination where to create the tunnel to
2959 * @return new tunnel to @a destination
2961 struct CadetTunnel *
2962 GCT_create_tunnel (struct CadetPeer *destination)
2964 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2965 struct GNUNET_MQ_MessageHandler handlers[] = {
2966 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2967 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2968 struct GNUNET_MessageHeader,
2970 GNUNET_MQ_hd_var_size (plaintext_data,
2971 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2972 struct GNUNET_CADET_ChannelAppDataMessage,
2974 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2975 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2976 struct GNUNET_CADET_ChannelDataAckMessage,
2978 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2979 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2980 struct GNUNET_CADET_ChannelOpenMessage,
2982 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2983 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2984 struct GNUNET_CADET_ChannelOpenAckMessage,
2986 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2987 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2988 struct GNUNET_CADET_ChannelDestroyMessage,
2990 GNUNET_MQ_handler_end ()
2993 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2994 new_ephemeral (&t->ax);
2995 GNUNET_assert (GNUNET_OK ==
2996 GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2997 t->destination = destination;
2998 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2999 t->maintain_connections_task
3000 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
3002 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
3007 &decrypted_error_cb,
3009 t->mst = GNUNET_MST_create (&handle_decrypted,
3016 * Add a @a connection to the @a tunnel.
3019 * @param cid connection identifer to use for the connection
3020 * @param options options for the connection
3021 * @param path path to use for the connection
3022 * @return #GNUNET_OK on success,
3023 * #GNUNET_SYSERR on failure (duplicate connection)
3026 GCT_add_inbound_connection (struct CadetTunnel *t,
3027 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
3028 enum GNUNET_CADET_ChannelOption options,
3029 struct CadetPeerPath *path)
3031 struct CadetTConnection *ct;
3033 ct = GNUNET_new (struct CadetTConnection);
3034 ct->created = GNUNET_TIME_absolute_get ();
3036 ct->cc = GCC_create_inbound (t->destination,
3041 &connection_ready_cb,
3045 LOG (GNUNET_ERROR_TYPE_DEBUG,
3046 "%s refused inbound %s (duplicate)\n",
3050 return GNUNET_SYSERR;
3052 /* FIXME: schedule job to kill connection (and path?) if it takes
3053 too long to get ready! (And track performance data on how long
3054 other connections took with the tunnel!)
3055 => Note: to be done within 'connection'-logic! */
3056 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
3057 t->connection_busy_tail,
3059 t->num_busy_connections++;
3060 LOG (GNUNET_ERROR_TYPE_DEBUG,
3069 * Handle encrypted message.
3071 * @param ct connection/tunnel combo that received encrypted message
3072 * @param msg the encrypted message to decrypt
3075 GCT_handle_encrypted (struct CadetTConnection *ct,
3076 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3078 struct CadetTunnel *t = ct->t;
3079 uint16_t size = ntohs (msg->header.size);
3080 char cbuf [size] GNUNET_ALIGN;
3081 ssize_t decrypted_size;
3083 LOG (GNUNET_ERROR_TYPE_DEBUG,
3084 "%s received %u bytes of encrypted data in state %d\n",
3086 (unsigned int) size,
3091 case CADET_TUNNEL_KEY_UNINITIALIZED:
3092 case CADET_TUNNEL_KEY_AX_RECV:
3093 /* We did not even SEND our KX, how can the other peer
3094 send us encrypted data? Must have been that we went
3095 down and the other peer still things we are up.
3096 Let's send it KX back. */
3097 GNUNET_STATISTICS_update (stats,
3098 "# received encrypted without any KX",
3101 if (NULL != t->kx_task)
3103 GNUNET_SCHEDULER_cancel (t->kx_task);
3110 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3111 /* We send KX, and other peer send KX to us at the same time.
3112 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3113 GNUNET_STATISTICS_update (stats,
3114 "# received encrypted without KX_AUTH",
3117 if (NULL != t->kx_task)
3119 GNUNET_SCHEDULER_cancel (t->kx_task);
3127 case CADET_TUNNEL_KEY_AX_SENT:
3128 /* We did not get the KX of the other peer, but that
3129 might have been lost. Send our KX again immediately. */
3130 GNUNET_STATISTICS_update (stats,
3131 "# received encrypted without KX",
3134 if (NULL != t->kx_task)
3136 GNUNET_SCHEDULER_cancel (t->kx_task);
3143 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3144 /* Great, first payload, we might graduate to OK! */
3145 case CADET_TUNNEL_KEY_OK:
3146 /* We are up and running, all good. */
3150 decrypted_size = -1;
3151 if (CADET_TUNNEL_KEY_OK == t->estate)
3153 /* We have well-established key material available,
3154 try that. (This is the common case.) */
3155 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3161 if ( (-1 == decrypted_size) &&
3162 (NULL != t->unverified_ax) )
3164 /* We have un-authenticated KX material available. We should try
3165 this as a back-up option, in case the sender crashed and
3167 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3171 if (-1 != decrypted_size)
3173 /* It worked! Treat this as authentication of the AX data! */
3174 cleanup_ax (&t->ax);
3175 t->ax = *t->unverified_ax;
3176 GNUNET_free (t->unverified_ax);
3177 t->unverified_ax = NULL;
3179 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3181 /* First time it worked, move tunnel into production! */
3182 GCT_change_estate (t,
3183 CADET_TUNNEL_KEY_OK);
3184 if (NULL != t->send_task)
3185 GNUNET_SCHEDULER_cancel (t->send_task);
3186 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3190 if (NULL != t->unverified_ax)
3192 /* We had unverified KX material that was useless; so increment
3193 counter and eventually move to ignore it. Note that we even do
3194 this increment if we successfully decrypted with the old KX
3195 material and thus didn't even both with the new one. This is
3196 the ideal case, as a malicious injection of bogus KX data
3197 basically only causes us to increment a counter a few times. */
3198 t->unverified_attempts++;
3199 LOG (GNUNET_ERROR_TYPE_DEBUG,
3200 "Failed to decrypt message with unverified KX data %u times\n",
3201 t->unverified_attempts);
3202 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3204 cleanup_ax (t->unverified_ax);
3205 GNUNET_free (t->unverified_ax);
3206 t->unverified_ax = NULL;
3210 if (-1 == decrypted_size)
3212 /* Decryption failed for good, complain. */
3213 LOG (GNUNET_ERROR_TYPE_WARNING,
3214 "%s failed to decrypt and validate encrypted data, retrying KX\n",
3216 GNUNET_STATISTICS_update (stats,
3217 "# unable to decrypt",
3220 if (NULL != t->kx_task)
3222 GNUNET_SCHEDULER_cancel (t->kx_task);
3230 GNUNET_STATISTICS_update (stats,
3231 "# decrypted bytes",
3235 /* The MST will ultimately call #handle_decrypted() on each message. */
3237 GNUNET_break_op (GNUNET_OK ==
3238 GNUNET_MST_from_buffer (t->mst,
3243 t->current_ct = NULL;
3248 * Sends an already built message on a tunnel, encrypting it and
3249 * choosing the best connection if not provided.
3251 * @param message Message to send. Function modifies it.
3252 * @param t Tunnel on which this message is transmitted.
3253 * @param cont Continuation to call once message is really sent.
3254 * @param cont_cls Closure for @c cont.
3255 * @return Handle to cancel message
3257 struct CadetTunnelQueueEntry *
3258 GCT_send (struct CadetTunnel *t,
3259 const struct GNUNET_MessageHeader *message,
3260 GCT_SendContinuation cont,
3263 struct CadetTunnelQueueEntry *tq;
3264 uint16_t payload_size;
3265 struct GNUNET_MQ_Envelope *env;
3266 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3268 if (CADET_TUNNEL_KEY_OK != t->estate)
3273 payload_size = ntohs (message->size);
3274 LOG (GNUNET_ERROR_TYPE_DEBUG,
3275 "Encrypting %u bytes for %s\n",
3276 (unsigned int) payload_size,
3278 env = GNUNET_MQ_msg_extra (ax_msg,
3280 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3281 t_ax_encrypt (&t->ax,
3285 GNUNET_STATISTICS_update (stats,
3286 "# encrypted bytes",
3289 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3290 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3291 /* FIXME: we should do this once, not once per message;
3292 this is a point multiplication, and DHRs does not
3293 change all the time. */
3294 GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3295 &ax_msg->ax_header.DHRs);
3296 t_h_encrypt (&t->ax,
3298 t_hmac (&ax_msg->ax_header,
3299 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3304 tq = GNUNET_malloc (sizeof (*tq));
3307 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3309 tq->cont_cls = cont_cls;
3310 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3313 if (NULL != t->send_task)
3314 GNUNET_SCHEDULER_cancel (t->send_task);
3316 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3323 * Cancel a previously sent message while it's in the queue.
3325 * ONLY can be called before the continuation given to the send
3326 * function is called. Once the continuation is called, the message is
3327 * no longer in the queue!
3329 * @param tq Handle to the queue entry to cancel.
3332 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3334 struct CadetTunnel *t = tq->t;
3336 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3339 GNUNET_MQ_discard (tq->env);
3345 * Iterate over all connections of a tunnel.
3347 * @param t Tunnel whose connections to iterate.
3348 * @param iter Iterator.
3349 * @param iter_cls Closure for @c iter.
3352 GCT_iterate_connections (struct CadetTunnel *t,
3353 GCT_ConnectionIterator iter,
3356 struct CadetTConnection *n;
3357 for (struct CadetTConnection *ct = t->connection_ready_head;
3365 for (struct CadetTConnection *ct = t->connection_busy_head;
3377 * Closure for #iterate_channels_cb.
3384 GCT_ChannelIterator iter;
3387 * Closure for @e iter.
3394 * Helper function for #GCT_iterate_channels.
3396 * @param cls the `struct ChanIterCls`
3398 * @param value a `struct CadetChannel`
3399 * @return #GNUNET_OK
3402 iterate_channels_cb (void *cls,
3406 struct ChanIterCls *ctx = cls;
3407 struct CadetChannel *ch = value;
3409 ctx->iter (ctx->iter_cls,
3416 * Iterate over all channels of a tunnel.
3418 * @param t Tunnel whose channels to iterate.
3419 * @param iter Iterator.
3420 * @param iter_cls Closure for @c iter.
3423 GCT_iterate_channels (struct CadetTunnel *t,
3424 GCT_ChannelIterator iter,
3427 struct ChanIterCls ctx;
3430 ctx.iter_cls = iter_cls;
3431 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3432 &iterate_channels_cb,
3439 * Call #GCCH_debug() on a channel.
3441 * @param cls points to the log level to use
3443 * @param value the `struct CadetChannel` to dump
3444 * @return #GNUNET_OK (continue iteration)
3447 debug_channel (void *cls,
3451 const enum GNUNET_ErrorType *level = cls;
3452 struct CadetChannel *ch = value;
3454 GCCH_debug (ch, *level);
3459 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3463 * Log all possible info about the tunnel state.
3465 * @param t Tunnel to debug.
3466 * @param level Debug level to use.
3469 GCT_debug (const struct CadetTunnel *t,
3470 enum GNUNET_ErrorType level)
3472 #if !defined(GNUNET_CULL_LOGGING)
3473 struct CadetTConnection *iter_c;
3476 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3478 __FILE__, __FUNCTION__, __LINE__);
3483 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3485 estate2s (t->estate),
3487 GCT_count_any_connections (t));
3490 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3494 "TTT connections:\n");
3495 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3496 GCC_debug (iter_c->cc,
3498 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3499 GCC_debug (iter_c->cc,
3503 "TTT TUNNEL END\n");
3508 /* end of gnunet-service-cadet_tunnels.c */