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_CADET_AX_KX_FLAG_FORCE_REPLY ==
2869 (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2870 GCT_send_ax_kx (t, GNUNET_NO);
2872 if (CADET_TUNNEL_KEY_OK == t->estate)
2875 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2878 ax->DHRr = msg->ratchet_key;
2881 if (GNUNET_YES == am_I_alice)
2883 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2884 &msg->ephemeral_key, /* B0 */
2889 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
2890 &pid->public_key, /* A */
2895 if (GNUNET_YES == am_I_alice)
2897 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
2898 &pid->public_key, /* B */
2903 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2904 &msg->ephemeral_key, /* B0 */
2911 /* (This is the triple-DH, we could probably safely skip this,
2912 as A0/B0 are already in the key material.) */
2913 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
2914 &msg->ephemeral_key, /* B0 or A0 */
2917 #if DUMP_KEYS_TO_STDERR
2920 for (i = 0; i < 3; i++)
2921 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2922 i, GNUNET_h2s (&key_material[i]));
2927 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2928 salt, sizeof (salt),
2929 &key_material, sizeof (key_material), NULL);
2932 if (GNUNET_YES == am_I_alice)
2938 ax->ratchet_flag = GNUNET_YES;
2946 ax->ratchet_flag = GNUNET_NO;
2947 ax->ratchet_allowed = GNUNET_NO;
2948 ax->ratchet_counter = 0;
2949 ax->ratchet_expiration =
2950 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2952 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2957 * Demultiplex by message type and call appropriate handler for a message
2958 * towards a channel of a local tunnel.
2960 * @param t Tunnel this message came on.
2961 * @param msgh Message header.
2962 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2963 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2964 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2965 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2968 handle_decrypted (struct CadetTunnel *t,
2969 const struct GNUNET_MessageHeader *msgh,
2974 type = ntohs (msgh->type);
2975 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2979 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2980 /* Do nothing, connection aleady got updated. */
2981 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2984 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2985 /* Don't send hop ACK, wait for client to ACK */
2986 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2989 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2990 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2993 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2994 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2997 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2998 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3001 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3002 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3005 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3006 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3010 GNUNET_break_op (0);
3011 LOG (GNUNET_ERROR_TYPE_WARNING,
3012 "end-to-end message not known (%u)\n",
3013 ntohs (msgh->type));
3014 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3018 /******************************************************************************/
3019 /******************************** API ***********************************/
3020 /******************************************************************************/
3022 * Decrypt old format and demultiplex by message type. Call appropriate handler
3023 * for a message towards a channel of a local tunnel.
3025 * @param t Tunnel this message came on.
3026 * @param msg Message header.
3029 GCT_handle_encrypted (struct CadetTunnel *t,
3030 const struct GNUNET_MessageHeader *msg)
3032 uint16_t size = ntohs (msg->size);
3034 size_t payload_size;
3037 const struct GNUNET_MessageHeader *msgh;
3040 type = ntohs (msg->type);
3043 case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3045 const struct GNUNET_CADET_Encrypted *emsg;
3047 emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3048 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3049 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3050 emsg->iv, &emsg->hmac);
3053 case GNUNET_MESSAGE_TYPE_CADET_AX:
3055 const struct GNUNET_CADET_AX *emsg;
3057 emsg = (const struct GNUNET_CADET_AX *) msg;
3058 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3062 GNUNET_break_op (0);
3065 if (-1 == decrypted_size)
3067 GNUNET_break_op (0);
3071 /* FIXME: this is bad, as the structs returned from
3072 this loop may be unaligned, see util's MST for
3073 how to do this right. */
3075 while (off < decrypted_size)
3079 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3080 msize = ntohs (msgh->size);
3081 if (msize < sizeof (struct GNUNET_MessageHeader))
3083 GNUNET_break_op (0);
3086 handle_decrypted (t, msgh, GNUNET_SYSERR);
3093 * Demultiplex an encapsulated KX message by message type.
3095 * @param t Tunnel on which the message came.
3096 * @param message Payload of KX message.
3099 GCT_handle_kx (struct CadetTunnel *t,
3100 const struct GNUNET_MessageHeader *message)
3104 type = ntohs (message->type);
3105 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3108 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3109 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3112 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3113 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3116 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3117 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3121 GNUNET_break_op (0);
3122 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3127 * Initialize the tunnel subsystem.
3129 * @param c Configuration handle.
3130 * @param key ECC private key, to derive all other keys and do crypto.
3133 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3134 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3136 int expected_overhead;
3138 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3140 expected_overhead = 0;
3141 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3142 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3143 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3144 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3147 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3150 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3151 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3155 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3158 rekey_period = GNUNET_TIME_UNIT_DAYS;
3161 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3164 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3165 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3166 ratchet_messages = 64;
3169 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3172 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3173 "CADET", "RATCHET_TIME", "USING DEFAULT");
3174 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3180 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3181 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3182 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3183 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3184 otr_kx_msg.origin_identity = my_full_id;
3185 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3186 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3191 * Shut down the tunnel subsystem.
3196 if (NULL != rekey_task)
3198 GNUNET_SCHEDULER_cancel (rekey_task);
3201 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3202 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3209 * @param destination Peer this tunnel is towards.
3211 struct CadetTunnel *
3212 GCT_new (struct CadetPeer *destination)
3214 struct CadetTunnel *t;
3216 t = GNUNET_new (struct CadetTunnel);
3218 t->peer = destination;
3221 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3222 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3228 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3230 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3236 * Change the tunnel's connection state.
3238 * @param t Tunnel whose connection state to change.
3239 * @param cstate New connection state.
3242 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3246 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3247 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3248 if (myid != GCP_get_short_id (t->peer) &&
3249 CADET_TUNNEL_READY != t->cstate &&
3250 CADET_TUNNEL_READY == cstate)
3253 if (CADET_TUNNEL_KEY_OK == t->estate)
3255 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3256 send_queued_data (t);
3258 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3260 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3261 GCT_send_ax_kx (t, GNUNET_NO);
3265 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3270 if (CADET_TUNNEL_READY == cstate
3271 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3273 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3274 GCP_stop_search (t->peer);
3280 * Change the tunnel encryption state.
3282 * @param t Tunnel whose encryption state to change, or NULL.
3283 * @param state New encryption state.
3286 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3288 enum CadetTunnelEState old;
3295 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3296 GCP_2s (t->peer), estate2s (old));
3297 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3298 GCP_2s (t->peer), estate2s (t->estate));
3300 /* Send queued data if enc state changes to OK */
3301 if (myid != GCP_get_short_id (t->peer) &&
3302 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3304 send_queued_data (t);
3310 * @brief Check if tunnel has too many connections, and remove one if necessary.
3312 * Currently this means the newest connection, unless it is a direct one.
3313 * Implemented as a task to avoid freeing a connection that is in the middle
3314 * of being created/processed.
3316 * @param cls Closure (Tunnel to check).
3317 * @param tc Task context.
3320 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3322 struct CadetTunnel *t = cls;
3324 t->trim_connections_task = NULL;
3326 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3329 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3331 struct CadetTConnection *iter;
3332 struct CadetTConnection *c;
3334 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3336 if ((iter->created.abs_value_us > c->created.abs_value_us)
3337 && GNUNET_NO == GCC_is_direct (iter->c))
3344 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3346 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3359 * Add a connection to a tunnel.
3362 * @param c Connection.
3365 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3367 struct CadetTConnection *aux;
3369 GNUNET_assert (NULL != c);
3371 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3372 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3373 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3377 aux = GNUNET_new (struct CadetTConnection);
3379 aux->created = GNUNET_TIME_absolute_get ();
3381 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3383 if (CADET_TUNNEL_SEARCHING == t->cstate)
3384 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3386 if (NULL != t->trim_connections_task)
3387 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3392 * Remove a connection from a tunnel.
3395 * @param c Connection.
3398 GCT_remove_connection (struct CadetTunnel *t,
3399 struct CadetConnection *c)
3401 struct CadetTConnection *aux;
3402 struct CadetTConnection *next;
3405 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3406 GCC_2s (c), GCT_2s (t));
3407 for (aux = t->connection_head; aux != NULL; aux = next)
3412 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3417 conns = GCT_count_connections (t);
3419 && NULL == t->destroy_task
3420 && CADET_TUNNEL_SHUTDOWN != t->cstate
3421 && GNUNET_NO == shutting_down)
3423 if (0 == GCT_count_any_connections (t))
3424 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3426 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3429 /* Start new connections if needed */
3430 if (CONNECTIONS_PER_TUNNEL > conns
3431 && NULL == t->destroy_task
3432 && CADET_TUNNEL_SHUTDOWN != t->cstate
3433 && GNUNET_NO == shutting_down)
3435 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3436 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3440 /* If not marked as ready, no change is needed */
3441 if (CADET_TUNNEL_READY != t->cstate)
3444 /* Check if any connection is ready to maintain cstate */
3445 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3446 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3452 * Add a channel to a tunnel.
3455 * @param ch Channel.
3458 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3460 struct CadetTChannel *aux;
3462 GNUNET_assert (NULL != ch);
3464 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3466 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3468 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3473 aux = GNUNET_new (struct CadetTChannel);
3475 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3476 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3478 if (NULL != t->destroy_task)
3480 GNUNET_SCHEDULER_cancel (t->destroy_task);
3481 t->destroy_task = NULL;
3482 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3488 * Remove a channel from a tunnel.
3491 * @param ch Channel.
3494 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3496 struct CadetTChannel *aux;
3498 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3499 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3503 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3504 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3513 * Search for a channel by global ID.
3515 * @param t Tunnel containing the channel.
3516 * @param chid Public channel number.
3518 * @return channel handler, NULL if doesn't exist
3520 struct CadetChannel *
3521 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3523 struct CadetTChannel *iter;
3528 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3530 if (GCCH_get_id (iter->ch) == chid)
3534 return NULL == iter ? NULL : iter->ch;
3539 * @brief Destroy a tunnel and free all resources.
3541 * Should only be called a while after the tunnel has been marked as destroyed,
3542 * in case there is a new channel added to the same peer shortly after marking
3543 * the tunnel. This way we avoid a new public key handshake.
3545 * @param cls Closure (tunnel to destroy).
3546 * @param tc Task context.
3549 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3551 struct CadetTunnel *t = cls;
3552 struct CadetTConnection *iter;
3554 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3555 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3557 LOG (GNUNET_ERROR_TYPE_WARNING,
3558 "Not destroying tunnel, due to shutdown. "
3559 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3562 t->destroy_task = NULL;
3563 t->cstate = CADET_TUNNEL_SHUTDOWN;
3565 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3567 GCC_send_destroy (iter->c);
3574 * Tunnel is empty: destroy it.
3576 * Notifies all connections about the destruction.
3578 * @param t Tunnel to destroy.
3581 GCT_destroy_empty (struct CadetTunnel *t)
3583 if (GNUNET_YES == shutting_down)
3584 return; /* Will be destroyed immediately anyway */
3586 if (NULL != t->destroy_task)
3588 LOG (GNUNET_ERROR_TYPE_WARNING,
3589 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3591 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3593 /* should never happen, tunnel can only become empty once, and the
3594 * task identifier should be NO_TASK (cleaned when the tunnel was created
3595 * or became un-empty)
3600 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3603 // FIXME make delay a config option
3604 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3605 &delayed_destroy, t);
3606 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3607 t, t->destroy_task);
3612 * Destroy tunnel if empty (no more channels).
3614 * @param t Tunnel to destroy if empty.
3617 GCT_destroy_if_empty (struct CadetTunnel *t)
3619 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3620 if (0 < GCT_count_channels (t))
3623 GCT_destroy_empty (t);
3628 * Destroy the tunnel.
3630 * This function does not generate any warning traffic to clients or peers.
3633 * Cancel messages belonging to this tunnel queued to neighbors.
3634 * Free any allocated resources linked to the tunnel.
3636 * @param t The tunnel to destroy.
3639 GCT_destroy (struct CadetTunnel *t)
3641 struct CadetTConnection *iter_c;
3642 struct CadetTConnection *next_c;
3643 struct CadetTChannel *iter_ch;
3644 struct CadetTChannel *next_ch;
3649 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3651 GNUNET_break (GNUNET_YES ==
3652 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3653 GCP_get_id (t->peer), t));
3655 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3657 next_c = iter_c->next;
3658 GCC_destroy (iter_c->c);
3660 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3662 next_ch = iter_ch->next;
3663 GCCH_destroy (iter_ch->ch);
3664 /* Should only happen on shutdown, but it's ok. */
3667 if (NULL != t->destroy_task)
3669 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3670 GNUNET_SCHEDULER_cancel (t->destroy_task);
3671 t->destroy_task = NULL;
3674 if (NULL != t->trim_connections_task)
3676 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3677 t->trim_connections_task);
3678 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3679 t->trim_connections_task = NULL;
3682 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3683 GCP_set_tunnel (t->peer, NULL);
3685 if (NULL != t->rekey_task)
3687 GNUNET_SCHEDULER_cancel (t->rekey_task);
3688 t->rekey_task = NULL;
3690 if (NULL != t->kx_ctx)
3692 if (NULL != t->kx_ctx->finish_task)
3693 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3694 GNUNET_free (t->kx_ctx);
3705 * @brief Use the given path for the tunnel.
3706 * Update the next and prev hops (and RCs).
3707 * (Re)start the path refresh in case the tunnel is locally owned.
3709 * @param t Tunnel to update.
3710 * @param p Path to use.
3712 * @return Connection created.
3714 struct CadetConnection *
3715 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3717 struct CadetConnection *c;
3718 struct GNUNET_CADET_Hash cid;
3719 unsigned int own_pos;
3721 if (NULL == t || NULL == p)
3727 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3733 for (own_pos = 0; own_pos < p->length; own_pos++)
3735 if (p->peers[own_pos] == myid)
3738 if (own_pos >= p->length)
3740 GNUNET_break_op (0);
3744 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3745 c = GCC_new (&cid, t, p, own_pos);
3748 /* Path was flawed */
3751 GCT_add_connection (t, c);
3757 * Count all created connections of a tunnel. Not necessarily ready connections!
3759 * @param t Tunnel on which to count.
3761 * @return Number of connections created, either being established or ready.
3764 GCT_count_any_connections (struct CadetTunnel *t)
3766 struct CadetTConnection *iter;
3772 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3780 * Count established (ready) connections of a tunnel.
3782 * @param t Tunnel on which to count.
3784 * @return Number of connections.
3787 GCT_count_connections (struct CadetTunnel *t)
3789 struct CadetTConnection *iter;
3795 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3796 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3804 * Count channels of a tunnel.
3806 * @param t Tunnel on which to count.
3808 * @return Number of channels.
3811 GCT_count_channels (struct CadetTunnel *t)
3813 struct CadetTChannel *iter;
3816 for (count = 0, iter = t->channel_head;
3818 iter = iter->next, count++) /* skip */;
3825 * Get the connectivity state of a tunnel.
3829 * @return Tunnel's connectivity state.
3831 enum CadetTunnelCState
3832 GCT_get_cstate (struct CadetTunnel *t)
3837 return (enum CadetTunnelCState) -1;
3844 * Get the encryption state of a tunnel.
3848 * @return Tunnel's encryption state.
3850 enum CadetTunnelEState
3851 GCT_get_estate (struct CadetTunnel *t)
3856 return (enum CadetTunnelEState) -1;
3862 * Get the maximum buffer space for a tunnel towards a local client.
3866 * @return Biggest buffer space offered by any channel in the tunnel.
3869 GCT_get_channels_buffer (struct CadetTunnel *t)
3871 struct CadetTChannel *iter;
3872 unsigned int buffer;
3873 unsigned int ch_buf;
3875 if (NULL == t->channel_head)
3877 /* Probably getting buffer for a channel create/handshake. */
3878 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3883 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3885 ch_buf = get_channel_buffer (iter);
3886 if (ch_buf > buffer)
3894 * Get the total buffer space for a tunnel for P2P traffic.
3898 * @return Buffer space offered by all connections in the tunnel.
3901 GCT_get_connections_buffer (struct CadetTunnel *t)
3903 struct CadetTConnection *iter;
3904 unsigned int buffer;
3906 if (GNUNET_NO == is_ready (t))
3908 if (count_queued_data (t) >= 3)
3915 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3917 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3921 buffer += get_connection_buffer (iter);
3929 * Get the tunnel's destination.
3933 * @return ID of the destination peer.
3935 const struct GNUNET_PeerIdentity *
3936 GCT_get_destination (struct CadetTunnel *t)
3938 return GCP_get_id (t->peer);
3943 * Get the tunnel's next free global channel ID.
3947 * @return GID of a channel free to use.
3950 GCT_get_next_chid (struct CadetTunnel *t)
3952 CADET_ChannelNumber chid;
3953 CADET_ChannelNumber mask;
3956 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3957 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3958 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3960 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3965 t->next_chid |= mask;
3967 while (NULL != GCT_get_channel (t, t->next_chid))
3969 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3970 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3971 t->next_chid |= mask;
3973 chid = t->next_chid;
3974 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3975 t->next_chid |= mask;
3982 * Send ACK on one or more channels due to buffer in connections.
3984 * @param t Channel which has some free buffer space.
3987 GCT_unchoke_channels (struct CadetTunnel *t)
3989 struct CadetTChannel *iter;
3990 unsigned int buffer;
3991 unsigned int channels = GCT_count_channels (t);
3992 unsigned int choked_n;
3993 struct CadetChannel *choked[channels];
3995 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3996 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3997 if (NULL != t->channel_head)
3998 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4000 if (NULL != t->tq_head)
4001 send_queued_data (t);
4003 /* Get buffer space */
4004 buffer = GCT_get_connections_buffer (t);
4010 /* Count and remember choked channels */
4012 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4014 if (GNUNET_NO == get_channel_allowed (iter))
4016 choked[choked_n++] = iter->ch;
4020 /* Unchoke random channels */
4021 while (0 < buffer && 0 < choked_n)
4023 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4025 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4028 choked[r] = choked[choked_n];
4034 * Send ACK on one or more connections due to buffer space to the client.
4036 * Iterates all connections of the tunnel and sends ACKs appropriately.
4041 GCT_send_connection_acks (struct CadetTunnel *t)
4043 struct CadetTConnection *iter;
4046 uint32_t allow_per_connection;
4048 unsigned int buffer;
4050 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4059 if (CADET_TUNNEL_READY != t->cstate)
4062 buffer = GCT_get_channels_buffer (t);
4063 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4065 /* Count connections, how many messages are already allowed */
4066 cs = GCT_count_connections (t);
4067 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4069 allowed += get_connection_allowed (iter);
4071 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4073 /* Make sure there is no overflow */
4074 if (allowed > buffer)
4077 /* Authorize connections to send more data */
4078 to_allow = buffer - allowed;
4080 for (iter = t->connection_head;
4081 NULL != iter && to_allow > 0;
4084 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4085 || get_connection_allowed (iter) > 64 / 3)
4089 allow_per_connection = to_allow/cs;
4090 to_allow -= allow_per_connection;
4092 GCC_allow (iter->c, allow_per_connection,
4093 GCC_is_origin (iter->c, GNUNET_NO));
4098 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4099 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4105 * Cancel a previously sent message while it's in the queue.
4107 * ONLY can be called before the continuation given to the send function
4108 * is called. Once the continuation is called, the message is no longer in the
4111 * @param q Handle to the queue.
4114 GCT_cancel (struct CadetTunnelQueue *q)
4119 /* tun_message_sent() will be called and free q */
4121 else if (NULL != q->tqd)
4123 unqueue_data (q->tqd);
4125 if (NULL != q->cont)
4126 q->cont (q->cont_cls, NULL, q, 0, 0);
4137 * Sends an already built message on a tunnel, encrypting it and
4138 * choosing the best connection if not provided.
4140 * @param message Message to send. Function modifies it.
4141 * @param t Tunnel on which this message is transmitted.
4142 * @param c Connection to use (autoselect if NULL).
4143 * @param force Force the tunnel to take the message (buffer overfill).
4144 * @param cont Continuation to call once message is really sent.
4145 * @param cont_cls Closure for @c cont.
4147 * @return Handle to cancel message. NULL if @c cont is NULL.
4149 struct CadetTunnelQueue *
4150 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4151 struct CadetTunnel *t, struct CadetConnection *c,
4152 int force, GCT_sent cont, void *cont_cls)
4154 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4159 * Send an Axolotl KX message.
4161 * @param t Tunnel on which to send it.
4162 * @param force_reply Force the other peer to reply with a KX message.
4165 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4167 struct GNUNET_CADET_AX_KX msg;
4168 enum GNUNET_CADET_AX_KX_Flags flags;
4170 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4171 if (NULL != t->ephm_h)
4173 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4177 msg.header.size = htons (sizeof (msg));
4178 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4179 flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4181 flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4182 msg.flags = htonl (flags);
4183 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4184 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4186 t->ephm_h = send_kx (t, &msg.header);
4187 if (CADET_TUNNEL_KEY_OK != t->estate)
4188 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4193 * Sends an already built and encrypted message on a tunnel, choosing the best
4194 * connection. Useful for re-queueing messages queued on a destroyed connection.
4196 * @param message Message to send. Function modifies it.
4197 * @param t Tunnel on which this message is transmitted.
4200 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4201 struct CadetTunnel *t)
4203 struct CadetConnection *c;
4206 c = tunnel_get_connection (t);
4209 /* TODO queue in tunnel, marked as encrypted */
4210 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4213 fwd = GCC_is_origin (c, GNUNET_YES);
4214 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4215 GNUNET_YES, NULL, NULL));
4220 * Is the tunnel directed towards the local peer?
4224 * @return #GNUNET_YES if it is loopback.
4227 GCT_is_loopback (const struct CadetTunnel *t)
4229 return (myid == GCP_get_short_id (t->peer));
4234 * Is the tunnel this path already?
4239 * @return #GNUNET_YES a connection uses this path.
4242 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4244 struct CadetTConnection *iter;
4246 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4247 if (path_equivalent (GCC_get_path (iter->c), p))
4255 * Get a cost of a path for a tunnel considering existing connections.
4258 * @param path Candidate path.
4260 * @return Cost of the path (path length + number of overlapping nodes)
4263 GCT_get_path_cost (const struct CadetTunnel *t,
4264 const struct CadetPeerPath *path)
4266 struct CadetTConnection *iter;
4267 const struct CadetPeerPath *aux;
4268 unsigned int overlap;
4276 GNUNET_assert (NULL != t);
4278 for (i = 0; i < path->length; i++)
4280 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4282 aux = GCC_get_path (iter->c);
4286 for (j = 0; j < aux->length; j++)
4288 if (path->peers[i] == aux->peers[j])
4296 return path->length + overlap;
4301 * Get the static string for the peer this tunnel is directed.
4305 * @return Static string the destination peer's ID.
4308 GCT_2s (const struct CadetTunnel *t)
4313 return GCP_2s (t->peer);
4317 /******************************************************************************/
4318 /***************************** INFO/DEBUG *******************************/
4319 /******************************************************************************/
4322 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4324 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4325 struct CadetTunnelSkippedKey *iter;
4328 LOG2 (level, "TTT RK\t %s\n",
4329 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4331 LOG2 (level, "TTT HKs\t %s\n",
4332 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4333 LOG2 (level, "TTT HKr\t %s\n",
4334 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4335 LOG2 (level, "TTT NHKs\t %s\n",
4336 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4337 LOG2 (level, "TTT NHKr\t %s\n",
4338 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4340 LOG2 (level, "TTT CKs\t %s\n",
4341 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4342 LOG2 (level, "TTT CKr\t %s\n",
4343 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4345 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4346 LOG2 (level, "TTT DHRs\t %s\n",
4347 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4348 LOG2 (level, "TTT DHRr\t %s\n",
4349 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4351 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4352 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4353 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4355 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4357 LOG2 (level, "TTT HK\t %s\n",
4358 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4359 LOG2 (level, "TTT MK\t %s\n",
4360 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4365 * Log all possible info about the tunnel state.
4367 * @param t Tunnel to debug.
4368 * @param level Debug level to use.
4371 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4373 struct CadetTChannel *iterch;
4374 struct CadetTConnection *iterc;
4377 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4379 __FILE__, __FUNCTION__, __LINE__);
4383 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4384 LOG2 (level, "TTT cstate %s, estate %s\n",
4385 cstate2s (t->cstate), estate2s (t->estate));
4386 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4387 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4388 #if DUMP_KEYS_TO_STDERR
4389 if (CADET_Axolotl == t->enc_type)
4391 ax_debug (t->ax, level);
4395 LOG2 (level, "TTT my EPHM\t %s\n",
4396 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4397 LOG2 (level, "TTT peers EPHM:\t %s\n",
4398 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4399 LOG2 (level, "TTT ENC key:\t %s\n",
4400 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4401 LOG2 (level, "TTT DEC key:\t %s\n",
4402 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4405 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4406 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4407 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4408 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4412 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4413 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4415 LOG2 (level, "TTT channels:\n");
4416 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4418 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4421 LOG2 (level, "TTT connections:\n");
4422 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4424 GCC_debug (iterc->c, level);
4427 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4432 * Iterate all tunnels.
4434 * @param iter Iterator.
4435 * @param cls Closure for @c iter.
4438 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4440 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4445 * Count all tunnels.
4447 * @return Number of tunnels to remote peers kept by this peer.
4450 GCT_count_all (void)
4452 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4457 * Iterate all connections of a tunnel.
4459 * @param t Tunnel whose connections to iterate.
4460 * @param iter Iterator.
4461 * @param cls Closure for @c iter.
4464 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4466 struct CadetTConnection *ct;
4468 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4474 * Iterate all channels of a tunnel.
4476 * @param t Tunnel whose channels to iterate.
4477 * @param iter Iterator.
4478 * @param cls Closure for @c iter.
4481 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4483 struct CadetTChannel *cht;
4485 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4486 iter (cls, cht->ch);