2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 #define MAX_SKIPPED_KEYS 64
47 #define MAX_KEY_GAP 256
48 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
49 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
52 /******************************************************************************/
53 /******************************** STRUCTS **********************************/
54 /******************************************************************************/
58 struct CadetTChannel *next;
59 struct CadetTChannel *prev;
60 struct CadetChannel *ch;
65 * Connection list and metadata.
67 struct CadetTConnection
72 struct CadetTConnection *next;
77 struct CadetTConnection *prev;
82 struct CadetConnection *c;
85 * Creation time, to keep oldest connection alive.
87 struct GNUNET_TIME_Absolute created;
90 * Connection throughput, to keep fastest connection alive.
96 * Structure used during a Key eXchange.
98 struct CadetTunnelKXCtx
101 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
102 * end before the key exchange is finished or times out.
104 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
107 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
108 * the other end before the key exchange started.
110 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
113 * Same as @c e_key_old, for the case of two simultaneous KX.
114 * This can happen if cadet decides to start a re-key while the peer has also
115 * started its re-key (due to network delay this is impossible to avoid).
116 * In this case, the key material generated with the peer's old ephemeral
117 * *might* (but doesn't have to) be incorrect.
118 * Since no more than two re-keys can happen simultaneously, this is enough.
120 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
123 * Same as @c d_key_old, for the case described in @c e_key_old2.
125 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
128 * Challenge to send and expect in the PONG.
133 * When the rekey started. One minute after this the new key will be used.
135 struct GNUNET_TIME_Absolute rekey_start_time;
138 * Task for delayed destruction of the Key eXchange context, to allow delayed
139 * messages with the old key to be decrypted successfully.
141 struct GNUNET_SCHEDULER_Task *finish_task;
145 * Encryption systems possible.
147 enum CadetTunnelEncryption
150 * Default Axolotl system.
155 * Fallback OTR-style encryption.
161 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
163 struct CadetTunnelSkippedKey
168 struct CadetTunnelSkippedKey *next;
173 struct CadetTunnelSkippedKey *prev;
176 * When was this key stored (for timeout).
178 struct GNUNET_TIME_Absolute timestamp;
183 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
188 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
193 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
195 struct CadetTunnelAxolotl
198 * A (double linked) list of stored message keys and associated header keys
199 * for "skipped" messages, i.e. messages that have not been
200 * received despite the reception of more recent messages, (head).
202 struct CadetTunnelSkippedKey *skipped_head;
205 * Skipped messages' keys DLL, tail.
207 struct CadetTunnelSkippedKey *skipped_tail;
210 * Elements in @a skipped_head <-> @a skipped_tail.
212 unsigned int skipped;
215 * 32-byte root key which gets updated by DH ratchet.
217 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
220 * 32-byte header key (send).
222 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
225 * 32-byte header key (recv)
227 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
230 * 32-byte next header key (send).
232 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
235 * 32-byte next header key (recv).
237 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
240 * 32-byte chain keys (used for forward-secrecy updating, send).
242 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
245 * 32-byte chain keys (used for forward-secrecy updating, recv).
247 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
250 * ECDH for key exchange (A0 / B0).
252 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
255 * ECDH Ratchet key (send).
257 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
260 * ECDH Ratchet key (recv).
262 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
265 * Message number (reset to 0 with each new ratchet, next message to send).
270 * Message number (reset to 0 with each new ratchet, next message to recv).
275 * Previous message numbers (# of msgs sent under prev ratchet)
280 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
285 * Number of messages recieved since our last ratchet advance.
286 * - If this counter = 0, we cannot send a new ratchet key in next msg.
287 * - If this counter > 0, we can (but don't yet have to) send a new key.
289 unsigned int ratchet_allowed;
292 * Number of messages recieved since our last ratchet advance.
293 * - If this counter = 0, we cannot send a new ratchet key in next msg.
294 * - If this counter > 0, we can (but don't yet have to) send a new key.
296 unsigned int ratchet_counter;
299 * When does this ratchet expire and a new one is triggered.
301 struct GNUNET_TIME_Absolute ratchet_expiration;
305 * Struct containing all information regarding a tunnel to a peer.
310 * Endpoint of the tunnel.
312 struct CadetPeer *peer;
315 * Type of encryption used in the tunnel.
317 enum CadetTunnelEncryption enc_type;
322 struct CadetTunnelAxolotl *ax;
325 * State of the tunnel connectivity.
327 enum CadetTunnelCState cstate;
330 * State of the tunnel encryption.
332 enum CadetTunnelEState estate;
335 * Key eXchange context.
337 struct CadetTunnelKXCtx *kx_ctx;
340 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
343 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
346 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
348 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
351 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
353 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
356 * Task to start the rekey process.
358 struct GNUNET_SCHEDULER_Task * rekey_task;
361 * Paths that are actively used to reach the destination peer.
363 struct CadetTConnection *connection_head;
364 struct CadetTConnection *connection_tail;
367 * Next connection number.
372 * Channels inside this tunnel.
374 struct CadetTChannel *channel_head;
375 struct CadetTChannel *channel_tail;
378 * Channel ID for the next created channel.
380 CADET_ChannelNumber next_chid;
383 * Destroy flag: if true, destroy on last message.
385 struct GNUNET_SCHEDULER_Task * destroy_task;
388 * Queued messages, to transmit once tunnel gets connected.
390 struct CadetTunnelDelayed *tq_head;
391 struct CadetTunnelDelayed *tq_tail;
394 * Task to trim connections if too many are present.
396 struct GNUNET_SCHEDULER_Task * trim_connections_task;
399 * Ephemeral message in the queue (to avoid queueing more than one).
401 struct CadetConnectionQueue *ephm_h;
404 * Pong message in the queue.
406 struct CadetConnectionQueue *pong_h;
411 * Struct used to save messages in a non-ready tunnel to send once connected.
413 struct CadetTunnelDelayed
418 struct CadetTunnelDelayed *next;
419 struct CadetTunnelDelayed *prev;
424 struct CadetTunnel *t;
427 * Tunnel queue given to the channel to cancel request. Update on send_queued.
429 struct CadetTunnelQueue *tq;
434 /* struct GNUNET_MessageHeader *msg; */
439 * Handle for messages queued but not yet sent.
441 struct CadetTunnelQueue
444 * Connection queue handle, to cancel if necessary.
446 struct CadetConnectionQueue *cq;
449 * Handle in case message hasn't been given to a connection yet.
451 struct CadetTunnelDelayed *tqd;
454 * Continuation to call once sent.
459 * Closure for @c cont.
465 /******************************************************************************/
466 /******************************* GLOBALS ***********************************/
467 /******************************************************************************/
470 * Global handle to the statistics service.
472 extern struct GNUNET_STATISTICS_Handle *stats;
475 * Local peer own ID (memory efficient handle).
477 extern GNUNET_PEER_Id myid;
480 * Local peer own ID (full value).
482 extern struct GNUNET_PeerIdentity my_full_id;
486 * Don't try to recover tunnels if shutting down.
488 extern int shutting_down;
492 * Set of all tunnels, in order to trigger a new exchange on rekey.
493 * Indexed by peer's ID.
495 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
498 * Default TTL for payload packets.
500 static unsigned long long default_ttl;
503 * Own Peer ID private key.
505 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
508 /******************************** AXOLOTL ************************************/
511 * How many messages are needed to trigger a ratchet advance.
513 static unsigned long long ratchet_messages;
516 * How long until we trigger a ratched advance.
518 static struct GNUNET_TIME_Relative ratchet_time;
521 /******************************** OTR ***********************************/
524 * Own global OTR ephemeral private key.
526 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
529 * Cached message used to perform a OTR key exchange.
531 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
534 * Task to generate a new OTR ephemeral key.
536 static struct GNUNET_SCHEDULER_Task *rekey_task;
541 static struct GNUNET_TIME_Relative rekey_period;
544 /******************************************************************************/
545 /******************************** STATIC ***********************************/
546 /******************************************************************************/
549 * Get string description for tunnel connectivity state.
551 * @param cs Tunnel state.
553 * @return String representation.
556 cstate2s (enum CadetTunnelCState cs)
562 case CADET_TUNNEL_NEW:
563 return "CADET_TUNNEL_NEW";
564 case CADET_TUNNEL_SEARCHING:
565 return "CADET_TUNNEL_SEARCHING";
566 case CADET_TUNNEL_WAITING:
567 return "CADET_TUNNEL_WAITING";
568 case CADET_TUNNEL_READY:
569 return "CADET_TUNNEL_READY";
570 case CADET_TUNNEL_SHUTDOWN:
571 return "CADET_TUNNEL_SHUTDOWN";
573 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
581 * Get string description for tunnel encryption state.
583 * @param es Tunnel state.
585 * @return String representation.
588 estate2s (enum CadetTunnelEState es)
594 case CADET_TUNNEL_KEY_UNINITIALIZED:
595 return "CADET_TUNNEL_KEY_UNINITIALIZED";
596 case CADET_TUNNEL_KEY_SENT:
597 return "CADET_TUNNEL_KEY_SENT";
598 case CADET_TUNNEL_KEY_PING:
599 return "CADET_TUNNEL_KEY_PING";
600 case CADET_TUNNEL_KEY_OK:
601 return "CADET_TUNNEL_KEY_OK";
602 case CADET_TUNNEL_KEY_REKEY:
603 return "CADET_TUNNEL_KEY_REKEY";
605 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
613 * @brief Check if tunnel is ready to send traffic.
615 * Tunnel must be connected and with encryption correctly set up.
617 * @param t Tunnel to check.
619 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
622 is_ready (struct CadetTunnel *t)
626 ready = CADET_TUNNEL_READY == t->cstate
627 && (CADET_TUNNEL_KEY_OK == t->estate
628 || CADET_TUNNEL_KEY_REKEY == t->estate);
629 ready = ready || GCT_is_loopback (t);
635 * Check if a key is invalid (NULL pointer or all 0)
637 * @param key Key to check.
639 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
642 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
644 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
649 memset (&null_key, 0, sizeof (null_key));
650 if (0 == memcmp (key, &null_key, sizeof (null_key)))
657 * Ephemeral key message purpose size.
659 * @return Size of the part of the ephemeral key message that must be signed.
662 ephemeral_purpose_size (void)
664 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
665 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
666 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
667 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
668 sizeof (struct GNUNET_PeerIdentity);
673 * Size of the encrypted part of a ping message.
675 * @return Size of the encrypted part of a ping message.
678 ping_encryption_size (void)
680 return sizeof (uint32_t);
685 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
687 * @param tch Tunnel's channel handle.
689 * @return Amount of messages the channel can still buffer towards the client.
692 get_channel_buffer (const struct CadetTChannel *tch)
696 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
697 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
699 return GCCH_get_buffer (tch->ch, fwd);
704 * Get the channel's allowance status.
706 * @param tch Tunnel's channel handle.
708 * @return #GNUNET_YES if we allowed the client to send data to us.
711 get_channel_allowed (const struct CadetTChannel *tch)
715 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
716 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
718 return GCCH_get_allowed (tch->ch, fwd);
723 * Get the connection's buffer.
725 * @param tc Tunnel's connection handle.
727 * @return Amount of messages the connection can still buffer.
730 get_connection_buffer (const struct CadetTConnection *tc)
734 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
735 fwd = GCC_is_origin (tc->c, GNUNET_YES);
737 return GCC_get_buffer (tc->c, fwd);
742 * Get the connection's allowance.
744 * @param tc Tunnel's connection handle.
746 * @return Amount of messages we have allowed the next peer to send us.
749 get_connection_allowed (const struct CadetTConnection *tc)
753 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
754 fwd = GCC_is_origin (tc->c, GNUNET_YES);
756 return GCC_get_allowed (tc->c, fwd);
761 * Check that a ephemeral key message s well formed and correctly signed.
763 * @param t Tunnel on which the message came.
764 * @param msg The ephemeral key message.
766 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
769 check_ephemeral (struct CadetTunnel *t,
770 const struct GNUNET_CADET_KX_Ephemeral *msg)
772 /* Check message size */
773 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
774 return GNUNET_SYSERR;
776 /* Check signature size */
777 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
778 return GNUNET_SYSERR;
781 if (0 != memcmp (&msg->origin_identity,
782 GCP_get_id (t->peer),
783 sizeof (struct GNUNET_PeerIdentity)))
784 return GNUNET_SYSERR;
786 /* Check signature */
788 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
791 &msg->origin_identity.public_key))
792 return GNUNET_SYSERR;
799 * Select the best key to use for encryption (send), based on KX status.
801 * Normally, return the current key. If there is a KX in progress and the old
802 * key is fresh enough, return the old key.
804 * @param t Tunnel to choose the key from.
806 * @return The optimal key to encrypt/hmac outgoing traffic.
808 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
809 select_key (const struct CadetTunnel *t)
811 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
813 if (NULL != t->kx_ctx
814 && NULL == t->kx_ctx->finish_task)
816 struct GNUNET_TIME_Relative age;
818 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
819 LOG (GNUNET_ERROR_TYPE_DEBUG,
820 " key exchange in progress, started %s ago\n",
821 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
822 // FIXME make duration of old keys configurable
823 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
825 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
826 key = &t->kx_ctx->e_key_old;
830 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
836 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
846 * @param plaintext Content to HMAC.
847 * @param size Size of @c plaintext.
848 * @param iv Initialization vector for the message.
849 * @param key Key to use.
850 * @param hmac[out] Destination to store the HMAC.
853 t_hmac (const void *plaintext, size_t size,
854 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
855 struct GNUNET_CADET_Hash *hmac)
857 static const char ctx[] = "cadet authentication key";
858 struct GNUNET_CRYPTO_AuthKey auth_key;
859 struct GNUNET_HashCode hash;
861 #if DUMP_KEYS_TO_STDERR
862 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
863 GNUNET_h2s ((struct GNUNET_HashCode *) key));
865 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
870 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
871 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
872 memcpy (hmac, &hash, sizeof (*hmac));
877 * Encrypt daforce_newest_keyta with the tunnel key.
879 * @param t Tunnel whose key to use.
880 * @param dst Destination for the encrypted data.
881 * @param src Source of the plaintext. Can overlap with @c dst.
882 * @param size Size of the plaintext.
883 * @param iv Initialization Vector to use.
884 * @param force_newest_key Force the use of the newest key, otherwise
885 * CADET will use the old key when allowed.
886 * This can happen in the case when a KX is going on
887 * and the old one hasn't expired.
890 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
891 size_t size, uint32_t iv, int force_newest_key)
893 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
894 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
897 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
899 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
900 #if DUMP_KEYS_TO_STDERR
901 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
902 GNUNET_h2s ((struct GNUNET_HashCode *) key));
904 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
905 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
906 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
907 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
916 * @param key Key to use.
917 * @param hash[out] Resulting HMAC.
918 * @param source Source key material (data to HMAC).
919 * @param len Length of @a source.
922 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
923 struct GNUNET_HashCode *hash,
924 void *source, unsigned int len)
926 static const char ctx[] = "axolotl HMAC-HASH";
927 struct GNUNET_CRYPTO_AuthKey auth_key;
929 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
932 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
937 * Derive a key from a HMAC-HASH.
939 * @param key Key to use for the HMAC.
940 * @param out Key to generate.
941 * @param source Source key material (data to HMAC).
942 * @param len Length of @a source.
945 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
946 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
947 void *source, unsigned int len)
949 static const char ctx[] = "axolotl derive key";
950 struct GNUNET_HashCode h;
952 t_ax_hmac_hash (key, &h, source, len);
953 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
954 &h, sizeof (h), NULL);
959 * Encrypt data with the axolotl tunnel key.
961 * @param t Tunnel whose key to use.
962 * @param dst Destination for the encrypted data.
963 * @param src Source of the plaintext. Can overlap with @c dst.
964 * @param size Size of the plaintext.
966 * @return Size of the encrypted data.
969 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
971 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
972 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
973 struct CadetTunnelAxolotl *ax;
976 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
980 ax->ratchet_counter++;
981 if (GNUNET_YES == ax->ratchet_allowed
982 && (ratchet_messages <= ax->ratchet_counter
983 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
985 ax->ratchet_flag = GNUNET_YES;
988 if (GNUNET_YES == ax->ratchet_flag)
990 /* Advance ratchet */
991 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
992 struct GNUNET_HashCode dh;
993 struct GNUNET_HashCode hmac;
994 static const char ctx[] = "axolotl ratchet";
996 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
999 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1000 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1001 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1002 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1003 &hmac, sizeof (hmac), NULL);
1010 ax->ratchet_flag = GNUNET_NO;
1011 ax->ratchet_allowed = GNUNET_NO;
1012 ax->ratchet_counter = 0;
1013 ax->ratchet_expiration =
1014 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1017 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1018 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1020 #if DUMP_KEYS_TO_STDERR
1021 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1022 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1023 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1024 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1027 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1029 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1031 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1038 * Decrypt data with the axolotl tunnel key.
1040 * @param t Tunnel whose key to use.
1041 * @param dst Destination for the decrypted data.
1042 * @param src Source of the ciphertext. Can overlap with @c dst.
1043 * @param size Size of the ciphertext.
1045 * @return Size of the decrypted data.
1048 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1050 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1051 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1052 struct CadetTunnelAxolotl *ax;
1055 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1059 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1060 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1062 #if DUMP_KEYS_TO_STDERR
1063 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1064 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1065 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1066 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1069 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1070 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1071 GNUNET_assert (out_size == size);
1073 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1075 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1082 * Encrypt header with the axolotl header key.
1084 * @param t Tunnel whose key to use.
1085 * @param msg Message whose header to encrypt.
1088 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1090 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1091 struct CadetTunnelAxolotl *ax;
1094 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1097 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1099 #if DUMP_KEYS_TO_STDERR
1100 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1101 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1104 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1105 &ax->HKs, &iv, &msg->Ns);
1107 GNUNET_assert (AX_HEADER_SIZE == out_size);
1109 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1114 * Decrypt header with the current axolotl header key.
1116 * @param t Tunnel whose current ax HK to use.
1117 * @param src Message whose header to decrypt.
1118 * @param dst Where to decrypt header to.
1121 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1122 struct GNUNET_CADET_AX *dst)
1124 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1125 struct CadetTunnelAxolotl *ax;
1128 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1131 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1133 #if DUMP_KEYS_TO_STDERR
1134 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1135 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1138 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1139 &ax->HKr, &iv, &dst->Ns);
1141 GNUNET_assert (AX_HEADER_SIZE == out_size);
1143 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1148 * Decrypt and verify data with the appropriate tunnel key.
1150 * @param key Key to use.
1151 * @param dst Destination for the plaintext.
1152 * @param src Source of the encrypted data. Can overlap with @c dst.
1153 * @param size Size of the encrypted data.
1154 * @param iv Initialization Vector to use.
1156 * @return Size of the decrypted data, -1 if an error was encountered.
1159 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1160 void *dst, const void *src, size_t size, uint32_t iv)
1162 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1165 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1166 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1167 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1168 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1169 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1170 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1177 * Decrypt and verify data with the most recent tunnel key.
1179 * @param t Tunnel whose key to use.
1180 * @param dst Destination for the plaintext.
1181 * @param src Source of the encrypted data. Can overlap with @c dst.
1182 * @param size Size of the encrypted data.
1183 * @param iv Initialization Vector to use.
1185 * @return Size of the decrypted data, -1 if an error was encountered.
1188 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1189 size_t size, uint32_t iv)
1193 #if DUMP_KEYS_TO_STDERR
1194 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1195 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1197 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1199 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1200 LOG (GNUNET_ERROR_TYPE_WARNING,
1201 "got data on %s without a valid key\n",
1203 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1207 out_size = decrypt (&t->d_key, dst, src, size, iv);
1214 * Decrypt and verify data with the appropriate tunnel key and verify that the
1215 * data has not been altered since it was sent by the remote peer.
1217 * @param t Tunnel whose key to use.
1218 * @param dst Destination for the plaintext.
1219 * @param src Source of the encrypted data. Can overlap with @c dst.
1220 * @param size Size of the encrypted data.
1221 * @param iv Initialization Vector to use.
1222 * @param msg_hmac HMAC of the message, cannot be NULL.
1224 * @return Size of the decrypted data, -1 if an error was encountered.
1227 t_decrypt_and_validate (struct CadetTunnel *t,
1228 void *dst, const void *src,
1229 size_t size, uint32_t iv,
1230 const struct GNUNET_CADET_Hash *msg_hmac)
1232 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1233 struct GNUNET_CADET_Hash hmac;
1236 /* Try primary (newest) key */
1238 decrypted_size = decrypt (key, dst, src, size, iv);
1239 t_hmac (src, size, iv, key, &hmac);
1240 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1241 return decrypted_size;
1243 /* If no key exchange is going on, we just failed. */
1244 if (NULL == t->kx_ctx)
1246 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1247 "Failed checksum validation on tunnel %s with no KX\n",
1249 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1253 /* Try secondary key, from previous KX period. */
1254 key = &t->kx_ctx->d_key_old;
1255 decrypted_size = decrypt (key, dst, src, size, iv);
1256 t_hmac (src, size, iv, key, &hmac);
1257 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1258 return decrypted_size;
1260 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1261 key = &t->kx_ctx->d_key_old2;
1262 decrypted_size = decrypt (key, dst, src, size, iv);
1263 t_hmac (src, size, iv, key, &hmac);
1264 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1265 return decrypted_size;
1267 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1268 "Failed checksum validation on tunnel %s with KX\n",
1270 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1276 * Decrypt and verify data with the appropriate tunnel key and verify that the
1277 * data has not been altered since it was sent by the remote peer.
1279 * @param t Tunnel whose key to use.
1280 * @param dst Destination for the plaintext.
1281 * @param src Source of the message. Can overlap with @c dst.
1282 * @param size Size of the message.
1284 * @return Size of the decrypted data, -1 if an error was encountered.
1287 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1288 const struct GNUNET_CADET_AX *src, size_t size)
1290 struct CadetTunnelSkippedKey *key;
1291 struct GNUNET_CADET_Hash hmac;
1292 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1297 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1299 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1300 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1306 #if DUMP_KEYS_TO_STDERR
1307 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1308 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1311 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1312 len = size - sizeof (struct GNUNET_CADET_AX);
1313 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1314 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1316 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1325 * Delete a key from the list of skipped keys.
1327 * @param t Tunnel to delete from.
1328 * @param HKr Header Key to use.
1331 store_skipped_key (struct CadetTunnel *t,
1332 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1334 struct CadetTunnelSkippedKey *key;
1336 key = GNUNET_new (struct CadetTunnelSkippedKey);
1337 key->timestamp = GNUNET_TIME_absolute_get ();
1338 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1339 #if DUMP_KEYS_TO_STDERR
1340 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1341 t->ax->Nr, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1342 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1343 GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1345 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1346 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1353 * Delete a key from the list of skipped keys.
1355 * @param t Tunnel to delete from.
1356 * @param key Key to delete.
1359 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1361 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1368 * Stage skipped AX keys and calculate the message key.
1370 * Stores each HK and MK for skipped messages.
1372 * @param t Tunnel where to stage the keys.
1373 * @param HKr Header key.
1374 * @param Np Received meesage number.
1377 store_ax_keys (struct CadetTunnel *t,
1378 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1383 gap = Np - t->ax->Nr;
1384 if (MAX_KEY_GAP < gap || 0 > gap)
1386 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1387 /* TODO: start new key exchange on return */
1388 GNUNET_break_op (0);
1392 while (t->ax->Nr < Np)
1393 store_skipped_key (t, HKr);
1395 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1396 delete_skipped_key (t, t->ax->skipped_tail);
1401 * Decrypt and verify data with the appropriate tunnel key and verify that the
1402 * data has not been altered since it was sent by the remote peer.
1404 * @param t Tunnel whose key to use.
1405 * @param dst Destination for the plaintext.
1406 * @param src Source of the message. Can overlap with @c dst.
1407 * @param size Size of the message.
1409 * @return Size of the decrypted data, -1 if an error was encountered.
1412 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1413 const struct GNUNET_CADET_AX *src, size_t size)
1415 struct CadetTunnelAxolotl *ax;
1416 struct GNUNET_CADET_Hash msg_hmac;
1417 struct GNUNET_HashCode hmac;
1418 struct GNUNET_CADET_AX *dstmsg;
1426 esize = size - sizeof (struct GNUNET_CADET_AX);
1431 /* Try current HK */
1432 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1433 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1435 static const char ctx[] = "axolotl ratchet";
1436 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1437 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1438 struct GNUNET_HashCode dh;
1439 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1442 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1443 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1445 /* Try the skipped keys, if that fails, we're out of luck. */
1446 return try_old_ax_keys (t, dst, src, size);
1448 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1452 t_h_decrypt (t, src, dstmsg);
1453 Np = ntohl (dstmsg->Ns);
1454 PNp = ntohl (dstmsg->PNs);
1455 DHRp = &dstmsg->DHRs;
1456 store_ax_keys (t, &HK, PNp);
1458 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1459 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1460 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1461 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1462 &hmac, sizeof (hmac), NULL);
1464 /* Commit "purported" keys */
1470 ax->ratchet_allowed = GNUNET_YES;
1474 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1475 t_h_decrypt (t, src, dstmsg);
1476 Np = ntohl (dstmsg->Ns);
1477 PNp = ntohl (dstmsg->PNs);
1481 store_ax_keys (t, &ax->HKr, Np);
1485 osize = t_ax_decrypt (t, dst, &src[1], esize);
1488 GNUNET_break_op (0);
1497 * Create key material by doing ECDH on the local and remote ephemeral keys.
1499 * @param key_material Where to store the key material.
1500 * @param ephemeral Peer's public ephemeral key.
1502 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1505 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1506 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1509 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1512 return GNUNET_SYSERR;
1519 * Create a symmetic key from the identities of both ends and the key material
1522 * @param key Destination for the generated key.
1523 * @param sender ID of the peer that will encrypt with @c key.
1524 * @param receiver ID of the peer that will decrypt with @c key.
1525 * @param key_material Hash created with ECDH with the ephemeral keys.
1528 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1529 const struct GNUNET_PeerIdentity *sender,
1530 const struct GNUNET_PeerIdentity *receiver,
1531 const struct GNUNET_HashCode *key_material)
1533 const char salt[] = "CADET kx salt";
1535 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1536 salt, sizeof (salt),
1537 key_material, sizeof (struct GNUNET_HashCode),
1538 sender, sizeof (struct GNUNET_PeerIdentity),
1539 receiver, sizeof (struct GNUNET_PeerIdentity),
1545 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1547 * @param t Tunnel for which to create the keys.
1549 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1552 create_otr_keys (struct CadetTunnel *t)
1554 struct GNUNET_HashCode km;
1556 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1557 return GNUNET_SYSERR;
1558 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1559 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1560 #if DUMP_KEYS_TO_STDERR
1561 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1562 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1563 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1564 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1565 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1566 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1567 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1568 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1569 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1576 * Create a new Key eXchange context for the tunnel.
1578 * If the old keys were verified, keep them for old traffic. Create a new KX
1579 * timestamp and a new nonce.
1581 * @param t Tunnel for which to create the KX ctx.
1583 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1586 create_kx_ctx (struct CadetTunnel *t)
1588 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1590 if (NULL != t->kx_ctx)
1592 if (NULL != t->kx_ctx->finish_task)
1594 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1595 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1596 t->kx_ctx->finish_task = NULL;
1601 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1602 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1606 if (CADET_TUNNEL_KEY_OK == t->estate)
1608 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1609 t->kx_ctx->d_key_old = t->d_key;
1610 t->kx_ctx->e_key_old = t->e_key;
1613 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1614 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1615 return create_otr_keys (t);
1620 * @brief Finish the Key eXchange and destroy the old keys.
1622 * @param cls Closure (Tunnel for which to finish the KX).
1623 * @param tc Task context.
1626 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1628 struct CadetTunnel *t = cls;
1630 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1632 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1634 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1638 GNUNET_free (t->kx_ctx);
1644 * Destroy a Key eXchange context for the tunnel. This function only schedules
1645 * the destruction, the freeing of the memory (and clearing of old key material)
1646 * happens after a delay!
1648 * @param t Tunnel whose KX ctx to destroy.
1651 destroy_kx_ctx (struct CadetTunnel *t)
1653 struct GNUNET_TIME_Relative delay;
1655 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1658 if (is_key_null (&t->kx_ctx->e_key_old))
1660 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1664 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1665 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1667 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1673 * Pick a connection on which send the next data message.
1675 * @param t Tunnel on which to send the message.
1677 * @return The connection on which to send the next message.
1679 static struct CadetConnection *
1680 tunnel_get_connection (struct CadetTunnel *t)
1682 struct CadetTConnection *iter;
1683 struct CadetConnection *best;
1685 unsigned int lowest_q;
1687 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1689 lowest_q = UINT_MAX;
1690 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1692 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1693 GCC_2s (iter->c), GCC_get_state (iter->c));
1694 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1696 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1697 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1705 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1711 * Callback called when a queued message is sent.
1713 * Calculates the average time and connection packet tracking.
1715 * @param cls Closure (TunnelQueue handle).
1716 * @param c Connection this message was on.
1717 * @param q Connection queue handle (unused).
1718 * @param type Type of message sent.
1719 * @param fwd Was this a FWD going message?
1720 * @param size Size of the message.
1723 tun_message_sent (void *cls,
1724 struct CadetConnection *c,
1725 struct CadetConnectionQueue *q,
1726 uint16_t type, int fwd, size_t size)
1728 struct CadetTunnelQueue *qt = cls;
1729 struct CadetTunnel *t;
1731 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1733 GNUNET_assert (NULL != qt->cont);
1734 t = NULL == c ? NULL : GCC_get_tunnel (c);
1735 qt->cont (qt->cont_cls, t, qt, type, size);
1741 count_queued_data (const struct CadetTunnel *t)
1743 struct CadetTunnelDelayed *iter;
1746 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1753 * Delete a queued message: either was sent or the channel was destroyed
1754 * before the tunnel's key exchange had a chance to finish.
1756 * @param tqd Delayed queue handle.
1759 unqueue_data (struct CadetTunnelDelayed *tqd)
1761 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1767 * Cache a message to be sent once tunnel is online.
1769 * @param t Tunnel to hold the message.
1770 * @param msg Message itself (copy will be made).
1772 static struct CadetTunnelDelayed *
1773 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1775 struct CadetTunnelDelayed *tqd;
1776 uint16_t size = ntohs (msg->size);
1778 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1780 GNUNET_assert (GNUNET_NO == is_ready (t));
1782 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1785 memcpy (&tqd[1], msg, size);
1786 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1792 * Sends an already built message on a tunnel, encrypting it and
1793 * choosing the best connection.
1795 * @param message Message to send. Function modifies it.
1796 * @param t Tunnel on which this message is transmitted.
1797 * @param c Connection to use (autoselect if NULL).
1798 * @param force Force the tunnel to take the message (buffer overfill).
1799 * @param cont Continuation to call once message is really sent.
1800 * @param cont_cls Closure for @c cont.
1801 * @param existing_q In case this a transmission of previously queued data,
1802 * this should be TunnelQueue given to the client.
1805 * @return Handle to cancel message.
1806 * NULL if @c cont is NULL or an error happens and message is dropped.
1808 static struct CadetTunnelQueue *
1809 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1810 struct CadetTunnel *t, struct CadetConnection *c,
1811 int force, GCT_sent cont, void *cont_cls,
1812 struct CadetTunnelQueue *existing_q)
1814 struct GNUNET_MessageHeader *msg;
1815 struct GNUNET_CADET_Encrypted *otr_msg;
1816 struct GNUNET_CADET_AX *ax_msg;
1817 struct CadetTunnelQueue *tq;
1818 size_t size = ntohs (message->size);
1819 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1820 + sizeof (struct GNUNET_CADET_AX);
1821 char cbuf[max_overhead + size];
1828 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1830 if (GNUNET_NO == is_ready (t))
1832 struct CadetTunnelDelayed *tqd;
1833 /* A non null existing_q indicates sending of queued data.
1834 * Should only happen after tunnel becomes ready.
1836 GNUNET_assert (NULL == existing_q);
1837 tqd = queue_data (t, message);
1840 tq = GNUNET_new (struct CadetTunnelQueue);
1844 tq->cont_cls = cont_cls;
1848 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1850 if (CADET_Axolotl == t->enc_type)
1852 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1853 msg = &ax_msg->header;
1854 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1855 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1856 ax_msg->reserved = 0;
1857 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1858 ax_msg->Ns = htonl (t->ax->Ns++);
1859 ax_msg->PNs = htonl (t->ax->PNs);
1860 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1861 t_h_encrypt (t, ax_msg);
1862 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1866 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1867 msg = &otr_msg->header;
1868 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1870 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1871 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1872 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1873 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1874 otr_msg->ttl = htonl (default_ttl);
1876 GNUNET_assert (esize == size);
1879 c = tunnel_get_connection (t);
1882 /* Why is tunnel 'ready'? Should have been queued! */
1883 if (NULL != t->destroy_task)
1886 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1888 return NULL; /* Drop... */
1892 type = ntohs (message->type);
1895 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1896 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1897 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1898 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1900 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1902 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1903 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1904 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1905 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1906 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1910 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1912 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1914 fwd = GCC_is_origin (c, GNUNET_YES);
1918 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1919 mid, c, fwd, force, NULL, NULL));
1922 if (NULL == existing_q)
1924 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1931 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1932 &tun_message_sent, tq);
1933 GNUNET_assert (NULL != tq->cq);
1935 tq->cont_cls = cont_cls;
1942 * Send all cached messages that we can, tunnel is online.
1944 * @param t Tunnel that holds the messages. Cannot be loopback.
1947 send_queued_data (struct CadetTunnel *t)
1949 struct CadetTunnelDelayed *tqd;
1950 struct CadetTunnelDelayed *next;
1953 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1955 if (GCT_is_loopback (t))
1961 if (GNUNET_NO == is_ready (t))
1963 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1964 estate2s (t->estate), cstate2s (t->cstate));
1968 room = GCT_get_connections_buffer (t);
1969 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1970 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1971 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1973 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1976 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1977 tqd->t, NULL, GNUNET_YES,
1978 NULL != tqd->tq ? tqd->tq->cont : NULL,
1979 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1983 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1988 * @brief Resend the AX KX until we complete the handshake.
1990 * @param cls Closure (tunnel).
1991 * @param tc Task context.
1994 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1996 struct CadetTunnel *t = cls;
1998 t->rekey_task = NULL;
2000 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2003 if (CADET_TUNNEL_KEY_OK == t->estate)
2006 GCT_send_ax_kx (t, GNUNET_YES);
2011 * Callback called when a queued message is sent.
2013 * @param cls Closure.
2014 * @param c Connection this message was on.
2015 * @param type Type of message sent.
2016 * @param fwd Was this a FWD going message?
2017 * @param size Size of the message.
2020 ephm_sent (void *cls,
2021 struct CadetConnection *c,
2022 struct CadetConnectionQueue *q,
2023 uint16_t type, int fwd, size_t size)
2025 struct CadetTunnel *t = cls;
2026 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2030 if (CADET_TUNNEL_KEY_OK == t->estate)
2033 if (CADET_Axolotl == t->enc_type && CADET_TUNNEL_KEY_OK != t->estate)
2035 if (NULL != t->rekey_task)
2038 GNUNET_SCHEDULER_cancel (t->rekey_task);
2040 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2047 * Callback called when a queued message is sent.
2049 * @param cls Closure.
2050 * @param c Connection this message was on.
2051 * @param type Type of message sent.
2052 * @param fwd Was this a FWD going message?
2053 * @param size Size of the message.
2056 pong_sent (void *cls,
2057 struct CadetConnection *c,
2058 struct CadetConnectionQueue *q,
2059 uint16_t type, int fwd, size_t size)
2061 struct CadetTunnel *t = cls;
2062 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2069 * Sends key exchange message on a tunnel, choosing the best connection.
2070 * Should not be called on loopback tunnels.
2072 * @param t Tunnel on which this message is transmitted.
2073 * @param message Message to send. Function modifies it.
2075 * @return Handle to the message in the connection queue.
2077 static struct CadetConnectionQueue *
2078 send_kx (struct CadetTunnel *t,
2079 const struct GNUNET_MessageHeader *message)
2081 struct CadetConnection *c;
2082 struct GNUNET_CADET_KX *msg;
2083 size_t size = ntohs (message->size);
2084 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2089 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2091 /* Avoid loopback. */
2092 if (GCT_is_loopback (t))
2097 type = ntohs (message->type);
2099 /* Even if tunnel is "being destroyed", send anyway.
2100 * Could be a response to a rekey initiated by remote peer,
2101 * who is trying to create a new channel!
2104 /* Must have a connection, or be looking for one. */
2105 if (NULL == t->connection_head)
2107 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2108 if (CADET_TUNNEL_SEARCHING != t->cstate)
2111 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2112 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2117 msg = (struct GNUNET_CADET_KX *) cbuf;
2118 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2119 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2120 c = tunnel_get_connection (t);
2123 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2126 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2132 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2133 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2134 GNUNET_assert (NULL == t->ephm_h);
2137 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2138 GNUNET_assert (NULL == t->pong_h);
2143 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2146 memcpy (&msg[1], message, size);
2148 fwd = GCC_is_origin (c, GNUNET_YES);
2150 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2157 * Send the ephemeral key on a tunnel.
2159 * @param t Tunnel on which to send the key.
2162 send_ephemeral (struct CadetTunnel *t)
2164 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2165 if (NULL != t->ephm_h)
2167 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2171 otr_kx_msg.sender_status = htonl (t->estate);
2172 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2173 otr_kx_msg.nonce = t->kx_ctx->challenge;
2174 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2175 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2176 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2177 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2178 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2183 * Send a pong message on a tunnel.
2185 * @param t Tunnel on which to send the pong.
2186 * @param challenge Value sent in the ping that we have to send back.
2189 send_pong (struct CadetTunnel *t, uint32_t challenge)
2191 struct GNUNET_CADET_KX_Pong msg;
2193 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2194 if (NULL != t->pong_h)
2196 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2199 msg.header.size = htons (sizeof (msg));
2200 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2201 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2202 msg.nonce = challenge;
2203 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2204 t_encrypt (t, &msg.nonce, &msg.nonce,
2205 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2206 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2208 t->pong_h = send_kx (t, &msg.header);
2213 * Initiate a rekey with the remote peer.
2215 * @param cls Closure (tunnel).
2216 * @param tc TaskContext.
2219 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2221 struct CadetTunnel *t = cls;
2223 t->rekey_task = NULL;
2225 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2226 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2229 GNUNET_assert (NULL != t->kx_ctx);
2230 struct GNUNET_TIME_Relative duration;
2232 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2233 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2234 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2236 // FIXME make duration of old keys configurable
2237 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2239 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2240 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2241 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2248 case CADET_TUNNEL_KEY_UNINITIALIZED:
2249 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2252 case CADET_TUNNEL_KEY_SENT:
2255 case CADET_TUNNEL_KEY_OK:
2257 * - state should have changed during rekey_iterator
2258 * - task should have been canceled at pong_handle
2261 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2264 case CADET_TUNNEL_KEY_PING:
2265 case CADET_TUNNEL_KEY_REKEY:
2269 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2272 // FIXME exponential backoff
2273 struct GNUNET_TIME_Relative delay;
2275 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2276 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2277 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2278 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2279 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2284 * Our ephemeral key has changed, create new session key on all tunnels.
2286 * Each tunnel will start the Key Exchange with a random delay between
2287 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2288 * per second, on average.
2290 * @param cls Closure (size of the hashmap).
2291 * @param key Current public key.
2292 * @param value Value in the hash map (tunnel).
2294 * @return #GNUNET_YES, so we should continue to iterate,
2297 rekey_iterator (void *cls,
2298 const struct GNUNET_PeerIdentity *key,
2301 struct CadetTunnel *t = value;
2302 struct GNUNET_TIME_Relative delay;
2303 long n = (long) cls;
2306 if (NULL != t->rekey_task)
2309 if (GNUNET_YES == GCT_is_loopback (t))
2312 if (CADET_OTR != t->enc_type)
2315 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2316 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2317 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2318 if (GNUNET_OK == create_kx_ctx (t))
2319 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2331 * Create a new ephemeral key and key message, schedule next rekeying.
2333 * @param cls Closure (unused).
2334 * @param tc TaskContext.
2337 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2339 struct GNUNET_TIME_Absolute time;
2344 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2347 GNUNET_free_non_null (otr_ephemeral_key);
2348 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2350 time = GNUNET_TIME_absolute_get ();
2351 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2352 time = GNUNET_TIME_absolute_add (time, rekey_period);
2353 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2354 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2355 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2356 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2357 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2359 GNUNET_assert (GNUNET_OK ==
2360 GNUNET_CRYPTO_eddsa_sign (id_key,
2361 &otr_kx_msg.purpose,
2362 &otr_kx_msg.signature));
2364 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2365 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2367 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2368 &global_otr_rekey, NULL);
2373 * Called only on shutdown, destroy every tunnel.
2375 * @param cls Closure (unused).
2376 * @param key Current public key.
2377 * @param value Value in the hash map (tunnel).
2379 * @return #GNUNET_YES, so we should continue to iterate,
2382 destroy_iterator (void *cls,
2383 const struct GNUNET_PeerIdentity *key,
2386 struct CadetTunnel *t = value;
2388 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2395 * Notify remote peer that we don't know a channel he is talking about,
2396 * probably CHANNEL_DESTROY was missed.
2398 * @param t Tunnel on which to notify.
2399 * @param gid ID of the channel.
2402 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2404 struct GNUNET_CADET_ChannelManage msg;
2406 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2407 msg.header.size = htons (sizeof (msg));
2408 msg.chid = htonl (gid);
2410 LOG (GNUNET_ERROR_TYPE_DEBUG,
2411 "WARNING destroying unknown channel %u on tunnel %s\n",
2413 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2418 * Demultiplex data per channel and call appropriate channel handler.
2420 * @param t Tunnel on which the data came.
2421 * @param msg Data message.
2422 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2423 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2424 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2425 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2428 handle_data (struct CadetTunnel *t,
2429 const struct GNUNET_CADET_Data *msg,
2432 struct CadetChannel *ch;
2436 size = ntohs (msg->header.size);
2438 sizeof (struct GNUNET_CADET_Data) +
2439 sizeof (struct GNUNET_MessageHeader))
2444 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2445 GC_m2s (ntohs (msg[1].header.type)));
2448 ch = GCT_get_channel (t, ntohl (msg->chid));
2451 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2453 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2455 send_channel_destroy (t, ntohl (msg->chid));
2459 GCCH_handle_data (ch, msg, fwd);
2464 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2466 * @param t Tunnel on which the DATA ACK came.
2467 * @param msg DATA ACK message.
2468 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2469 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2470 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2471 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2474 handle_data_ack (struct CadetTunnel *t,
2475 const struct GNUNET_CADET_DataACK *msg,
2478 struct CadetChannel *ch;
2482 size = ntohs (msg->header.size);
2483 if (size != sizeof (struct GNUNET_CADET_DataACK))
2490 ch = GCT_get_channel (t, ntohl (msg->chid));
2493 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2495 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2500 GCCH_handle_data_ack (ch, msg, fwd);
2505 * Handle channel create.
2507 * @param t Tunnel on which the data came.
2508 * @param msg Data message.
2511 handle_ch_create (struct CadetTunnel *t,
2512 const struct GNUNET_CADET_ChannelCreate *msg)
2514 struct CadetChannel *ch;
2518 size = ntohs (msg->header.size);
2519 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2526 ch = GCT_get_channel (t, ntohl (msg->chid));
2527 if (NULL != ch && ! GCT_is_loopback (t))
2529 /* Probably a retransmission, safe to ignore */
2530 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2532 ch = GCCH_handle_create (t, msg);
2534 GCT_add_channel (t, ch);
2540 * Handle channel NACK: check correctness and call channel handler for NACKs.
2542 * @param t Tunnel on which the NACK came.
2543 * @param msg NACK message.
2546 handle_ch_nack (struct CadetTunnel *t,
2547 const struct GNUNET_CADET_ChannelManage *msg)
2549 struct CadetChannel *ch;
2553 size = ntohs (msg->header.size);
2554 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2561 ch = GCT_get_channel (t, ntohl (msg->chid));
2564 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2566 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2571 GCCH_handle_nack (ch);
2576 * Handle a CHANNEL ACK (SYNACK/ACK).
2578 * @param t Tunnel on which the CHANNEL ACK came.
2579 * @param msg CHANNEL ACK message.
2580 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2581 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2582 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2583 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2586 handle_ch_ack (struct CadetTunnel *t,
2587 const struct GNUNET_CADET_ChannelManage *msg,
2590 struct CadetChannel *ch;
2594 size = ntohs (msg->header.size);
2595 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2602 ch = GCT_get_channel (t, ntohl (msg->chid));
2605 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2607 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2612 GCCH_handle_ack (ch, msg, fwd);
2617 * Handle a channel destruction message.
2619 * @param t Tunnel on which the message came.
2620 * @param msg Channel destroy message.
2621 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2622 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2623 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2624 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2627 handle_ch_destroy (struct CadetTunnel *t,
2628 const struct GNUNET_CADET_ChannelManage *msg,
2631 struct CadetChannel *ch;
2635 size = ntohs (msg->header.size);
2636 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2643 ch = GCT_get_channel (t, ntohl (msg->chid));
2646 /* Probably a retransmission, safe to ignore */
2650 GCCH_handle_destroy (ch, msg, fwd);
2655 * Create a new Axolotl ephemeral (ratchet) key.
2660 new_ephemeral (struct CadetTunnel *t)
2662 GNUNET_free_non_null (t->ax->DHRs);
2663 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2668 * Free Axolotl data.
2673 destroy_ax (struct CadetTunnel *t)
2678 GNUNET_free_non_null (t->ax->DHRs);
2679 GNUNET_free_non_null (t->ax->kx_0);
2681 GNUNET_free (t->ax);
2684 if (NULL != t->rekey_task)
2686 GNUNET_SCHEDULER_cancel (t->rekey_task);
2687 t->rekey_task = NULL;
2689 if (NULL != t->ephm_h)
2691 GCC_cancel (t->ephm_h);
2699 * The peer's ephemeral key has changed: update the symmetrical keys.
2701 * @param t Tunnel this message came on.
2702 * @param msg Key eXchange message.
2705 handle_ephemeral (struct CadetTunnel *t,
2706 const struct GNUNET_CADET_KX_Ephemeral *msg)
2708 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2710 if (GNUNET_OK != check_ephemeral (t, msg))
2712 GNUNET_break_op (0);
2716 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2720 t->enc_type = CADET_OTR;
2721 if (NULL != t->rekey_task)
2722 GNUNET_SCHEDULER_cancel (t->rekey_task);
2723 if (GNUNET_OK != create_kx_ctx (t))
2729 rekey_tunnel (t, NULL);
2730 GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2734 * If the key is different from what we know, derive the new E/D keys.
2735 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2737 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2738 sizeof (msg->ephemeral_key)))
2740 #if DUMP_KEYS_TO_STDERR
2741 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2742 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2743 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2744 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2746 t->peers_ephemeral_key = msg->ephemeral_key;
2748 if (GNUNET_OK != create_kx_ctx (t))
2755 if (CADET_TUNNEL_KEY_OK == t->estate)
2757 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2759 if (NULL != t->rekey_task)
2760 GNUNET_SCHEDULER_cancel (t->rekey_task);
2761 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2763 if (CADET_TUNNEL_KEY_SENT == t->estate)
2765 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2767 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2770 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2774 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2775 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2776 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2777 send_pong (t, nonce);
2783 * Peer has answer to our challenge.
2784 * If answer is successful, consider the key exchange finished and clean
2785 * up all related state.
2787 * @param t Tunnel this message came on.
2788 * @param msg Key eXchange Pong message.
2791 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2795 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2796 if (NULL == t->rekey_task)
2798 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2801 if (NULL == t->kx_ctx)
2803 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2807 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2808 if (challenge != t->kx_ctx->challenge)
2810 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2811 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2812 challenge, msg->nonce, t->kx_ctx->challenge);
2816 GNUNET_SCHEDULER_cancel (t->rekey_task);
2817 t->rekey_task = NULL;
2819 /* Don't free the old keys right away, but after a delay.
2820 * Rationale: the KX could have happened over a very fast connection,
2821 * with payload traffic still signed with the old key stuck in a slower
2823 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2827 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2832 * Handle Axolotl handshake.
2834 * @param t Tunnel this message came on.
2835 * @param msg Key eXchange Pong message.
2838 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2840 struct CadetTunnelAxolotl *ax;
2841 struct GNUNET_HashCode key_material[3];
2842 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2843 const char salt[] = "CADET Axolotl salt";
2844 const struct GNUNET_PeerIdentity *pid;
2847 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2851 /* Something is wrong if ax is NULL. Whose fault it is? */
2852 GNUNET_break_op (CADET_OTR == t->enc_type);
2853 GNUNET_break (CADET_Axolotl == t->enc_type);
2857 pid = GCT_get_destination (t);
2858 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2859 am_I_alice = GNUNET_YES;
2860 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2861 am_I_alice = GNUNET_NO;
2864 GNUNET_break_op (0);
2868 if (GNUNET_YES == ntohl (msg->force_reply))
2869 GCT_send_ax_kx (t, GNUNET_NO);
2871 if (CADET_TUNNEL_KEY_OK == t->estate)
2874 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2877 ax->DHRr = msg->ratchet_key;
2880 if (GNUNET_YES == am_I_alice)
2882 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2883 &msg->ephemeral_key, /* B0 */
2888 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
2889 &pid->public_key, /* A */
2894 if (GNUNET_YES == am_I_alice)
2896 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
2897 &pid->public_key, /* B */
2902 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2903 &msg->ephemeral_key, /* B0 */
2910 /* (This is the triple-DH, we could probably safely skip this,
2911 as A0/B0 are already in the key material.) */
2912 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
2913 &msg->ephemeral_key, /* B0 or A0 */
2916 #if DUMP_KEYS_TO_STDERR
2919 for (i = 0; i < 3; i++)
2920 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2921 i, GNUNET_h2s (&key_material[i]));
2926 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2927 salt, sizeof (salt),
2928 &key_material, sizeof (key_material), NULL);
2931 if (GNUNET_YES == am_I_alice)
2937 ax->ratchet_flag = GNUNET_YES;
2945 ax->ratchet_flag = GNUNET_NO;
2946 ax->ratchet_allowed = GNUNET_NO;
2947 ax->ratchet_counter = 0;
2948 ax->ratchet_expiration =
2949 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2951 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2956 * Demultiplex by message type and call appropriate handler for a message
2957 * towards a channel of a local tunnel.
2959 * @param t Tunnel this message came on.
2960 * @param msgh Message header.
2961 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2962 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2963 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2964 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2967 handle_decrypted (struct CadetTunnel *t,
2968 const struct GNUNET_MessageHeader *msgh,
2973 type = ntohs (msgh->type);
2974 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2978 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2979 /* Do nothing, connection aleady got updated. */
2980 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2983 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2984 /* Don't send hop ACK, wait for client to ACK */
2985 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2988 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2989 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2992 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2993 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2996 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2997 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3000 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3001 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3004 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3005 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3009 GNUNET_break_op (0);
3010 LOG (GNUNET_ERROR_TYPE_WARNING,
3011 "end-to-end message not known (%u)\n",
3012 ntohs (msgh->type));
3013 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3017 /******************************************************************************/
3018 /******************************** API ***********************************/
3019 /******************************************************************************/
3021 * Decrypt old format and demultiplex by message type. Call appropriate handler
3022 * for a message towards a channel of a local tunnel.
3024 * @param t Tunnel this message came on.
3025 * @param msg Message header.
3028 GCT_handle_encrypted (struct CadetTunnel *t,
3029 const struct GNUNET_MessageHeader *msg)
3031 uint16_t size = ntohs (msg->size);
3033 size_t payload_size;
3036 const struct GNUNET_MessageHeader *msgh;
3039 type = ntohs (msg->type);
3042 case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3044 const struct GNUNET_CADET_Encrypted *emsg;
3046 emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3047 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3048 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3049 emsg->iv, &emsg->hmac);
3052 case GNUNET_MESSAGE_TYPE_CADET_AX:
3054 const struct GNUNET_CADET_AX *emsg;
3056 emsg = (const struct GNUNET_CADET_AX *) msg;
3057 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3061 GNUNET_break_op (0);
3064 if (-1 == decrypted_size)
3066 GNUNET_break_op (0);
3070 /* FIXME: this is bad, as the structs returned from
3071 this loop may be unaligned, see util's MST for
3072 how to do this right. */
3074 while (off < decrypted_size)
3078 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3079 msize = ntohs (msgh->size);
3080 if (msize < sizeof (struct GNUNET_MessageHeader))
3082 GNUNET_break_op (0);
3085 handle_decrypted (t, msgh, GNUNET_SYSERR);
3092 * Demultiplex an encapsulated KX message by message type.
3094 * @param t Tunnel on which the message came.
3095 * @param message Payload of KX message.
3098 GCT_handle_kx (struct CadetTunnel *t,
3099 const struct GNUNET_MessageHeader *message)
3103 type = ntohs (message->type);
3104 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3107 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3108 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3111 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3112 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3115 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3116 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3120 GNUNET_break_op (0);
3121 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3126 * Initialize the tunnel subsystem.
3128 * @param c Configuration handle.
3129 * @param key ECC private key, to derive all other keys and do crypto.
3132 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3133 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3135 int expected_overhead;
3137 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3139 expected_overhead = 0;
3140 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3141 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3142 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3143 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3146 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3149 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3150 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3154 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3157 rekey_period = GNUNET_TIME_UNIT_DAYS;
3160 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3163 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3164 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3165 ratchet_messages = 64;
3168 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3171 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3172 "CADET", "RATCHET_TIME", "USING DEFAULT");
3173 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3179 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3180 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3181 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3182 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3183 otr_kx_msg.origin_identity = my_full_id;
3184 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3185 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3190 * Shut down the tunnel subsystem.
3195 if (NULL != rekey_task)
3197 GNUNET_SCHEDULER_cancel (rekey_task);
3200 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3201 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3208 * @param destination Peer this tunnel is towards.
3210 struct CadetTunnel *
3211 GCT_new (struct CadetPeer *destination)
3213 struct CadetTunnel *t;
3215 t = GNUNET_new (struct CadetTunnel);
3217 t->peer = destination;
3220 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3221 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3227 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3229 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3235 * Change the tunnel's connection state.
3237 * @param t Tunnel whose connection state to change.
3238 * @param cstate New connection state.
3241 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3245 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3246 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3247 if (myid != GCP_get_short_id (t->peer) &&
3248 CADET_TUNNEL_READY != t->cstate &&
3249 CADET_TUNNEL_READY == cstate)
3252 if (CADET_TUNNEL_KEY_OK == t->estate)
3254 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3255 send_queued_data (t);
3257 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3259 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3260 GCT_send_ax_kx (t, GNUNET_NO);
3264 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3269 if (CADET_TUNNEL_READY == cstate
3270 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3272 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3273 GCP_stop_search (t->peer);
3279 * Change the tunnel encryption state.
3281 * @param t Tunnel whose encryption state to change, or NULL.
3282 * @param state New encryption state.
3285 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3287 enum CadetTunnelEState old;
3294 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3295 GCP_2s (t->peer), estate2s (old));
3296 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3297 GCP_2s (t->peer), estate2s (t->estate));
3299 /* Send queued data if enc state changes to OK */
3300 if (myid != GCP_get_short_id (t->peer) &&
3301 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3303 send_queued_data (t);
3309 * @brief Check if tunnel has too many connections, and remove one if necessary.
3311 * Currently this means the newest connection, unless it is a direct one.
3312 * Implemented as a task to avoid freeing a connection that is in the middle
3313 * of being created/processed.
3315 * @param cls Closure (Tunnel to check).
3316 * @param tc Task context.
3319 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3321 struct CadetTunnel *t = cls;
3323 t->trim_connections_task = NULL;
3325 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3328 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3330 struct CadetTConnection *iter;
3331 struct CadetTConnection *c;
3333 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3335 if ((iter->created.abs_value_us > c->created.abs_value_us)
3336 && GNUNET_NO == GCC_is_direct (iter->c))
3343 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3345 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3358 * Add a connection to a tunnel.
3361 * @param c Connection.
3364 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3366 struct CadetTConnection *aux;
3368 GNUNET_assert (NULL != c);
3370 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3371 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3372 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3376 aux = GNUNET_new (struct CadetTConnection);
3378 aux->created = GNUNET_TIME_absolute_get ();
3380 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3382 if (CADET_TUNNEL_SEARCHING == t->cstate)
3383 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3385 if (NULL != t->trim_connections_task)
3386 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3391 * Remove a connection from a tunnel.
3394 * @param c Connection.
3397 GCT_remove_connection (struct CadetTunnel *t,
3398 struct CadetConnection *c)
3400 struct CadetTConnection *aux;
3401 struct CadetTConnection *next;
3404 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3405 GCC_2s (c), GCT_2s (t));
3406 for (aux = t->connection_head; aux != NULL; aux = next)
3411 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3416 conns = GCT_count_connections (t);
3418 && NULL == t->destroy_task
3419 && CADET_TUNNEL_SHUTDOWN != t->cstate
3420 && GNUNET_NO == shutting_down)
3422 if (0 == GCT_count_any_connections (t))
3423 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3425 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3428 /* Start new connections if needed */
3429 if (CONNECTIONS_PER_TUNNEL > conns
3430 && NULL == t->destroy_task
3431 && CADET_TUNNEL_SHUTDOWN != t->cstate
3432 && GNUNET_NO == shutting_down)
3434 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3435 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3439 /* If not marked as ready, no change is needed */
3440 if (CADET_TUNNEL_READY != t->cstate)
3443 /* Check if any connection is ready to maintain cstate */
3444 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3445 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3451 * Add a channel to a tunnel.
3454 * @param ch Channel.
3457 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3459 struct CadetTChannel *aux;
3461 GNUNET_assert (NULL != ch);
3463 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3465 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3467 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3472 aux = GNUNET_new (struct CadetTChannel);
3474 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3475 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3477 if (NULL != t->destroy_task)
3479 GNUNET_SCHEDULER_cancel (t->destroy_task);
3480 t->destroy_task = NULL;
3481 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3487 * Remove a channel from a tunnel.
3490 * @param ch Channel.
3493 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3495 struct CadetTChannel *aux;
3497 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3498 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3502 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3503 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3512 * Search for a channel by global ID.
3514 * @param t Tunnel containing the channel.
3515 * @param chid Public channel number.
3517 * @return channel handler, NULL if doesn't exist
3519 struct CadetChannel *
3520 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3522 struct CadetTChannel *iter;
3527 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3529 if (GCCH_get_id (iter->ch) == chid)
3533 return NULL == iter ? NULL : iter->ch;
3538 * @brief Destroy a tunnel and free all resources.
3540 * Should only be called a while after the tunnel has been marked as destroyed,
3541 * in case there is a new channel added to the same peer shortly after marking
3542 * the tunnel. This way we avoid a new public key handshake.
3544 * @param cls Closure (tunnel to destroy).
3545 * @param tc Task context.
3548 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3550 struct CadetTunnel *t = cls;
3551 struct CadetTConnection *iter;
3553 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3554 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3556 LOG (GNUNET_ERROR_TYPE_WARNING,
3557 "Not destroying tunnel, due to shutdown. "
3558 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3561 t->destroy_task = NULL;
3562 t->cstate = CADET_TUNNEL_SHUTDOWN;
3564 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3566 GCC_send_destroy (iter->c);
3573 * Tunnel is empty: destroy it.
3575 * Notifies all connections about the destruction.
3577 * @param t Tunnel to destroy.
3580 GCT_destroy_empty (struct CadetTunnel *t)
3582 if (GNUNET_YES == shutting_down)
3583 return; /* Will be destroyed immediately anyway */
3585 if (NULL != t->destroy_task)
3587 LOG (GNUNET_ERROR_TYPE_WARNING,
3588 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3590 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3592 /* should never happen, tunnel can only become empty once, and the
3593 * task identifier should be NO_TASK (cleaned when the tunnel was created
3594 * or became un-empty)
3599 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3602 // FIXME make delay a config option
3603 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3604 &delayed_destroy, t);
3605 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3606 t, t->destroy_task);
3611 * Destroy tunnel if empty (no more channels).
3613 * @param t Tunnel to destroy if empty.
3616 GCT_destroy_if_empty (struct CadetTunnel *t)
3618 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3619 if (0 < GCT_count_channels (t))
3622 GCT_destroy_empty (t);
3627 * Destroy the tunnel.
3629 * This function does not generate any warning traffic to clients or peers.
3632 * Cancel messages belonging to this tunnel queued to neighbors.
3633 * Free any allocated resources linked to the tunnel.
3635 * @param t The tunnel to destroy.
3638 GCT_destroy (struct CadetTunnel *t)
3640 struct CadetTConnection *iter_c;
3641 struct CadetTConnection *next_c;
3642 struct CadetTChannel *iter_ch;
3643 struct CadetTChannel *next_ch;
3648 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3650 GNUNET_break (GNUNET_YES ==
3651 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3652 GCP_get_id (t->peer), t));
3654 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3656 next_c = iter_c->next;
3657 GCC_destroy (iter_c->c);
3659 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3661 next_ch = iter_ch->next;
3662 GCCH_destroy (iter_ch->ch);
3663 /* Should only happen on shutdown, but it's ok. */
3666 if (NULL != t->destroy_task)
3668 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3669 GNUNET_SCHEDULER_cancel (t->destroy_task);
3670 t->destroy_task = NULL;
3673 if (NULL != t->trim_connections_task)
3675 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3676 t->trim_connections_task);
3677 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3678 t->trim_connections_task = NULL;
3681 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3682 GCP_set_tunnel (t->peer, NULL);
3684 if (NULL != t->rekey_task)
3686 GNUNET_SCHEDULER_cancel (t->rekey_task);
3687 t->rekey_task = NULL;
3689 if (NULL != t->kx_ctx)
3691 if (NULL != t->kx_ctx->finish_task)
3692 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3693 GNUNET_free (t->kx_ctx);
3704 * @brief Use the given path for the tunnel.
3705 * Update the next and prev hops (and RCs).
3706 * (Re)start the path refresh in case the tunnel is locally owned.
3708 * @param t Tunnel to update.
3709 * @param p Path to use.
3711 * @return Connection created.
3713 struct CadetConnection *
3714 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3716 struct CadetConnection *c;
3717 struct GNUNET_CADET_Hash cid;
3718 unsigned int own_pos;
3720 if (NULL == t || NULL == p)
3726 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3732 for (own_pos = 0; own_pos < p->length; own_pos++)
3734 if (p->peers[own_pos] == myid)
3737 if (own_pos >= p->length)
3739 GNUNET_break_op (0);
3743 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3744 c = GCC_new (&cid, t, p, own_pos);
3747 /* Path was flawed */
3750 GCT_add_connection (t, c);
3756 * Count all created connections of a tunnel. Not necessarily ready connections!
3758 * @param t Tunnel on which to count.
3760 * @return Number of connections created, either being established or ready.
3763 GCT_count_any_connections (struct CadetTunnel *t)
3765 struct CadetTConnection *iter;
3771 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3779 * Count established (ready) connections of a tunnel.
3781 * @param t Tunnel on which to count.
3783 * @return Number of connections.
3786 GCT_count_connections (struct CadetTunnel *t)
3788 struct CadetTConnection *iter;
3794 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3795 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3803 * Count channels of a tunnel.
3805 * @param t Tunnel on which to count.
3807 * @return Number of channels.
3810 GCT_count_channels (struct CadetTunnel *t)
3812 struct CadetTChannel *iter;
3815 for (count = 0, iter = t->channel_head;
3817 iter = iter->next, count++) /* skip */;
3824 * Get the connectivity state of a tunnel.
3828 * @return Tunnel's connectivity state.
3830 enum CadetTunnelCState
3831 GCT_get_cstate (struct CadetTunnel *t)
3836 return (enum CadetTunnelCState) -1;
3843 * Get the encryption state of a tunnel.
3847 * @return Tunnel's encryption state.
3849 enum CadetTunnelEState
3850 GCT_get_estate (struct CadetTunnel *t)
3855 return (enum CadetTunnelEState) -1;
3861 * Get the maximum buffer space for a tunnel towards a local client.
3865 * @return Biggest buffer space offered by any channel in the tunnel.
3868 GCT_get_channels_buffer (struct CadetTunnel *t)
3870 struct CadetTChannel *iter;
3871 unsigned int buffer;
3872 unsigned int ch_buf;
3874 if (NULL == t->channel_head)
3876 /* Probably getting buffer for a channel create/handshake. */
3877 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3882 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3884 ch_buf = get_channel_buffer (iter);
3885 if (ch_buf > buffer)
3893 * Get the total buffer space for a tunnel for P2P traffic.
3897 * @return Buffer space offered by all connections in the tunnel.
3900 GCT_get_connections_buffer (struct CadetTunnel *t)
3902 struct CadetTConnection *iter;
3903 unsigned int buffer;
3905 if (GNUNET_NO == is_ready (t))
3907 if (count_queued_data (t) >= 3)
3914 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3916 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3920 buffer += get_connection_buffer (iter);
3928 * Get the tunnel's destination.
3932 * @return ID of the destination peer.
3934 const struct GNUNET_PeerIdentity *
3935 GCT_get_destination (struct CadetTunnel *t)
3937 return GCP_get_id (t->peer);
3942 * Get the tunnel's next free global channel ID.
3946 * @return GID of a channel free to use.
3949 GCT_get_next_chid (struct CadetTunnel *t)
3951 CADET_ChannelNumber chid;
3952 CADET_ChannelNumber mask;
3955 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3956 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3957 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3959 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3964 t->next_chid |= mask;
3966 while (NULL != GCT_get_channel (t, t->next_chid))
3968 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3969 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3970 t->next_chid |= mask;
3972 chid = t->next_chid;
3973 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3974 t->next_chid |= mask;
3981 * Send ACK on one or more channels due to buffer in connections.
3983 * @param t Channel which has some free buffer space.
3986 GCT_unchoke_channels (struct CadetTunnel *t)
3988 struct CadetTChannel *iter;
3989 unsigned int buffer;
3990 unsigned int channels = GCT_count_channels (t);
3991 unsigned int choked_n;
3992 struct CadetChannel *choked[channels];
3994 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3995 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3996 if (NULL != t->channel_head)
3997 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3999 if (NULL != t->tq_head)
4000 send_queued_data (t);
4002 /* Get buffer space */
4003 buffer = GCT_get_connections_buffer (t);
4009 /* Count and remember choked channels */
4011 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4013 if (GNUNET_NO == get_channel_allowed (iter))
4015 choked[choked_n++] = iter->ch;
4019 /* Unchoke random channels */
4020 while (0 < buffer && 0 < choked_n)
4022 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4024 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4027 choked[r] = choked[choked_n];
4033 * Send ACK on one or more connections due to buffer space to the client.
4035 * Iterates all connections of the tunnel and sends ACKs appropriately.
4040 GCT_send_connection_acks (struct CadetTunnel *t)
4042 struct CadetTConnection *iter;
4045 uint32_t allow_per_connection;
4047 unsigned int buffer;
4049 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4058 if (CADET_TUNNEL_READY != t->cstate)
4061 buffer = GCT_get_channels_buffer (t);
4062 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4064 /* Count connections, how many messages are already allowed */
4065 cs = GCT_count_connections (t);
4066 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4068 allowed += get_connection_allowed (iter);
4070 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4072 /* Make sure there is no overflow */
4073 if (allowed > buffer)
4076 /* Authorize connections to send more data */
4077 to_allow = buffer - allowed;
4079 for (iter = t->connection_head;
4080 NULL != iter && to_allow > 0;
4083 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4084 || get_connection_allowed (iter) > 64 / 3)
4088 allow_per_connection = to_allow/cs;
4089 to_allow -= allow_per_connection;
4091 GCC_allow (iter->c, allow_per_connection,
4092 GCC_is_origin (iter->c, GNUNET_NO));
4097 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4098 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4104 * Cancel a previously sent message while it's in the queue.
4106 * ONLY can be called before the continuation given to the send function
4107 * is called. Once the continuation is called, the message is no longer in the
4110 * @param q Handle to the queue.
4113 GCT_cancel (struct CadetTunnelQueue *q)
4118 /* tun_message_sent() will be called and free q */
4120 else if (NULL != q->tqd)
4122 unqueue_data (q->tqd);
4124 if (NULL != q->cont)
4125 q->cont (q->cont_cls, NULL, q, 0, 0);
4136 * Sends an already built message on a tunnel, encrypting it and
4137 * choosing the best connection if not provided.
4139 * @param message Message to send. Function modifies it.
4140 * @param t Tunnel on which this message is transmitted.
4141 * @param c Connection to use (autoselect if NULL).
4142 * @param force Force the tunnel to take the message (buffer overfill).
4143 * @param cont Continuation to call once message is really sent.
4144 * @param cont_cls Closure for @c cont.
4146 * @return Handle to cancel message. NULL if @c cont is NULL.
4148 struct CadetTunnelQueue *
4149 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4150 struct CadetTunnel *t, struct CadetConnection *c,
4151 int force, GCT_sent cont, void *cont_cls)
4153 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4158 * Send an Axolotl KX message.
4160 * @param t Tunnel on which to send it.
4161 * @param force_reply Force the other peer to reply with a KX message.
4164 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4166 struct GNUNET_CADET_AX_KX msg;
4168 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4169 if (NULL != t->ephm_h)
4171 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4175 msg.header.size = htons (sizeof (msg));
4176 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4177 msg.force_reply = htonl (force_reply);
4178 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4179 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4181 t->ephm_h = send_kx (t, &msg.header);
4182 if (CADET_TUNNEL_KEY_OK != t->estate)
4183 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4188 * Sends an already built and encrypted message on a tunnel, choosing the best
4189 * connection. Useful for re-queueing messages queued on a destroyed connection.
4191 * @param message Message to send. Function modifies it.
4192 * @param t Tunnel on which this message is transmitted.
4195 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4196 struct CadetTunnel *t)
4198 struct CadetConnection *c;
4201 c = tunnel_get_connection (t);
4204 /* TODO queue in tunnel, marked as encrypted */
4205 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4208 fwd = GCC_is_origin (c, GNUNET_YES);
4209 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4210 GNUNET_YES, NULL, NULL));
4215 * Is the tunnel directed towards the local peer?
4219 * @return #GNUNET_YES if it is loopback.
4222 GCT_is_loopback (const struct CadetTunnel *t)
4224 return (myid == GCP_get_short_id (t->peer));
4229 * Is the tunnel this path already?
4234 * @return #GNUNET_YES a connection uses this path.
4237 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4239 struct CadetTConnection *iter;
4241 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4242 if (path_equivalent (GCC_get_path (iter->c), p))
4250 * Get a cost of a path for a tunnel considering existing connections.
4253 * @param path Candidate path.
4255 * @return Cost of the path (path length + number of overlapping nodes)
4258 GCT_get_path_cost (const struct CadetTunnel *t,
4259 const struct CadetPeerPath *path)
4261 struct CadetTConnection *iter;
4262 const struct CadetPeerPath *aux;
4263 unsigned int overlap;
4271 GNUNET_assert (NULL != t);
4273 for (i = 0; i < path->length; i++)
4275 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4277 aux = GCC_get_path (iter->c);
4281 for (j = 0; j < aux->length; j++)
4283 if (path->peers[i] == aux->peers[j])
4291 return path->length + overlap;
4296 * Get the static string for the peer this tunnel is directed.
4300 * @return Static string the destination peer's ID.
4303 GCT_2s (const struct CadetTunnel *t)
4308 return GCP_2s (t->peer);
4312 /******************************************************************************/
4313 /***************************** INFO/DEBUG *******************************/
4314 /******************************************************************************/
4317 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4319 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4320 struct CadetTunnelSkippedKey *iter;
4323 LOG2 (level, "TTT RK\t %s\n",
4324 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4326 LOG2 (level, "TTT HKs\t %s\n",
4327 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4328 LOG2 (level, "TTT HKr\t %s\n",
4329 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4330 LOG2 (level, "TTT NHKs\t %s\n",
4331 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4332 LOG2 (level, "TTT NHKr\t %s\n",
4333 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4335 LOG2 (level, "TTT CKs\t %s\n",
4336 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4337 LOG2 (level, "TTT CKr\t %s\n",
4338 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4340 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4341 LOG2 (level, "TTT DHRs\t %s\n",
4342 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4343 LOG2 (level, "TTT DHRr\t %s\n",
4344 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4346 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4347 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4348 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4350 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4352 LOG2 (level, "TTT HK\t %s\n",
4353 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4354 LOG2 (level, "TTT MK\t %s\n",
4355 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4360 * Log all possible info about the tunnel state.
4362 * @param t Tunnel to debug.
4363 * @param level Debug level to use.
4366 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4368 struct CadetTChannel *iterch;
4369 struct CadetTConnection *iterc;
4372 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4374 __FILE__, __FUNCTION__, __LINE__);
4378 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4379 LOG2 (level, "TTT cstate %s, estate %s\n",
4380 cstate2s (t->cstate), estate2s (t->estate));
4381 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4382 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4383 #if DUMP_KEYS_TO_STDERR
4384 if (CADET_Axolotl == t->enc_type)
4386 ax_debug (t->ax, level);
4390 LOG2 (level, "TTT my EPHM\t %s\n",
4391 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4392 LOG2 (level, "TTT peers EPHM:\t %s\n",
4393 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4394 LOG2 (level, "TTT ENC key:\t %s\n",
4395 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4396 LOG2 (level, "TTT DEC key:\t %s\n",
4397 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4400 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4401 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4402 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4403 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4407 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4408 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4410 LOG2 (level, "TTT channels:\n");
4411 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4413 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4416 LOG2 (level, "TTT connections:\n");
4417 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4419 GCC_debug (iterc->c, level);
4422 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4427 * Iterate all tunnels.
4429 * @param iter Iterator.
4430 * @param cls Closure for @c iter.
4433 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4435 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4440 * Count all tunnels.
4442 * @return Number of tunnels to remote peers kept by this peer.
4445 GCT_count_all (void)
4447 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4452 * Iterate all connections of a tunnel.
4454 * @param t Tunnel whose connections to iterate.
4455 * @param iter Iterator.
4456 * @param cls Closure for @c iter.
4459 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4461 struct CadetTConnection *ct;
4463 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4469 * Iterate all channels of a tunnel.
4471 * @param t Tunnel whose channels to iterate.
4472 * @param iter Iterator.
4473 * @param cls Closure for @c iter.
4476 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4478 struct CadetTChannel *cht;
4480 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4481 iter (cls, cht->ch);