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 MIN_TUNNEL_BUFFER 8
47 #define MAX_TUNNEL_BUFFER 64
48 #define MAX_SKIPPED_KEYS 64
49 #define MAX_KEY_GAP 256
50 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
51 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
54 /******************************************************************************/
55 /******************************** STRUCTS **********************************/
56 /******************************************************************************/
60 struct CadetTChannel *next;
61 struct CadetTChannel *prev;
62 struct CadetChannel *ch;
67 * Connection list and metadata.
69 struct CadetTConnection
74 struct CadetTConnection *next;
79 struct CadetTConnection *prev;
84 struct CadetConnection *c;
87 * Creation time, to keep oldest connection alive.
89 struct GNUNET_TIME_Absolute created;
92 * Connection throughput, to keep fastest connection alive.
98 * Structure used during a Key eXchange.
100 struct CadetTunnelKXCtx
103 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
104 * end before the key exchange is finished or times out.
106 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
109 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
110 * the other end before the key exchange started.
112 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
115 * Same as @c e_key_old, for the case of two simultaneous KX.
116 * This can happen if cadet decides to start a re-key while the peer has also
117 * started its re-key (due to network delay this is impossible to avoid).
118 * In this case, the key material generated with the peer's old ephemeral
119 * *might* (but doesn't have to) be incorrect.
120 * Since no more than two re-keys can happen simultaneously, this is enough.
122 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
125 * Same as @c d_key_old, for the case described in @c e_key_old2.
127 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
130 * Challenge to send and expect in the PONG.
135 * When the rekey started. One minute after this the new key will be used.
137 struct GNUNET_TIME_Absolute rekey_start_time;
140 * Task for delayed destruction of the Key eXchange context, to allow delayed
141 * messages with the old key to be decrypted successfully.
143 struct GNUNET_SCHEDULER_Task *finish_task;
147 * Encryption systems possible.
149 enum CadetTunnelEncryption
152 * Default Axolotl system.
157 * Fallback OTR-style encryption.
163 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
165 struct CadetTunnelSkippedKey
170 struct CadetTunnelSkippedKey *next;
175 struct CadetTunnelSkippedKey *prev;
178 * When was this key stored (for timeout).
180 struct GNUNET_TIME_Absolute timestamp;
185 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
190 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
195 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
197 struct CadetTunnelAxolotl
200 * A (double linked) list of stored message keys and associated header keys
201 * for "skipped" messages, i.e. messages that have not been
202 * received despite the reception of more recent messages, (head).
204 struct CadetTunnelSkippedKey *skipped_head;
207 * Skipped messages' keys DLL, tail.
209 struct CadetTunnelSkippedKey *skipped_tail;
212 * Elements in @a skipped_head <-> @a skipped_tail.
214 unsigned int skipped;
217 * 32-byte root key which gets updated by DH ratchet.
219 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
222 * 32-byte header key (send).
224 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
227 * 32-byte header key (recv)
229 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
232 * 32-byte next header key (send).
234 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
237 * 32-byte next header key (recv).
239 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
242 * 32-byte chain keys (used for forward-secrecy updating, send).
244 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
247 * 32-byte chain keys (used for forward-secrecy updating, recv).
249 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
252 * ECDH for key exchange (A0 / B0).
254 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
257 * ECDH Ratchet key (send).
259 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
262 * ECDH Ratchet key (recv).
264 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
267 * Message number (reset to 0 with each new ratchet, next message to send).
272 * Message number (reset to 0 with each new ratchet, next message to recv).
277 * Previous message numbers (# of msgs sent under prev ratchet)
282 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
287 * Number of messages recieved since our last ratchet advance.
288 * - If this counter = 0, we cannot send a new ratchet key in next msg.
289 * - If this counter > 0, we can (but don't yet have to) send a new key.
291 unsigned int ratchet_allowed;
294 * Number of messages recieved since our last ratchet advance.
295 * - If this counter = 0, we cannot send a new ratchet key in next msg.
296 * - If this counter > 0, we can (but don't yet have to) send a new key.
298 unsigned int ratchet_counter;
301 * When does this ratchet expire and a new one is triggered.
303 struct GNUNET_TIME_Absolute ratchet_expiration;
307 * Struct containing all information regarding a tunnel to a peer.
312 * Endpoint of the tunnel.
314 struct CadetPeer *peer;
317 * Type of encryption used in the tunnel.
319 enum CadetTunnelEncryption enc_type;
324 struct CadetTunnelAxolotl *ax;
327 * State of the tunnel connectivity.
329 enum CadetTunnelCState cstate;
332 * State of the tunnel encryption.
334 enum CadetTunnelEState estate;
337 * Key eXchange context.
339 struct CadetTunnelKXCtx *kx_ctx;
342 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
345 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
348 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
350 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
353 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
355 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
358 * Task to start the rekey process.
360 struct GNUNET_SCHEDULER_Task * rekey_task;
363 * Paths that are actively used to reach the destination peer.
365 struct CadetTConnection *connection_head;
366 struct CadetTConnection *connection_tail;
369 * Next connection number.
374 * Channels inside this tunnel.
376 struct CadetTChannel *channel_head;
377 struct CadetTChannel *channel_tail;
380 * Channel ID for the next created channel.
382 CADET_ChannelNumber next_chid;
385 * Destroy flag: if true, destroy on last message.
387 struct GNUNET_SCHEDULER_Task * destroy_task;
390 * Queued messages, to transmit once tunnel gets connected.
392 struct CadetTunnelDelayed *tq_head;
393 struct CadetTunnelDelayed *tq_tail;
396 * Task to trim connections if too many are present.
398 struct GNUNET_SCHEDULER_Task * trim_connections_task;
401 * Ephemeral message in the queue (to avoid queueing more than one).
403 struct CadetConnectionQueue *ephm_h;
406 * Pong message in the queue.
408 struct CadetConnectionQueue *pong_h;
413 * Struct used to save messages in a non-ready tunnel to send once connected.
415 struct CadetTunnelDelayed
420 struct CadetTunnelDelayed *next;
421 struct CadetTunnelDelayed *prev;
426 struct CadetTunnel *t;
429 * Tunnel queue given to the channel to cancel request. Update on send_queued.
431 struct CadetTunnelQueue *tq;
436 /* struct GNUNET_MessageHeader *msg; */
441 * Handle for messages queued but not yet sent.
443 struct CadetTunnelQueue
446 * Connection queue handle, to cancel if necessary.
448 struct CadetConnectionQueue *cq;
451 * Handle in case message hasn't been given to a connection yet.
453 struct CadetTunnelDelayed *tqd;
456 * Continuation to call once sent.
461 * Closure for @c cont.
467 /******************************************************************************/
468 /******************************* GLOBALS ***********************************/
469 /******************************************************************************/
472 * Global handle to the statistics service.
474 extern struct GNUNET_STATISTICS_Handle *stats;
477 * Local peer own ID (memory efficient handle).
479 extern GNUNET_PEER_Id myid;
482 * Local peer own ID (full value).
484 extern struct GNUNET_PeerIdentity my_full_id;
488 * Don't try to recover tunnels if shutting down.
490 extern int shutting_down;
494 * Set of all tunnels, in order to trigger a new exchange on rekey.
495 * Indexed by peer's ID.
497 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
500 * Default TTL for payload packets.
502 static unsigned long long default_ttl;
505 * Own Peer ID private key.
507 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
510 /******************************** AXOLOTL ************************************/
513 * How many messages are needed to trigger a ratchet advance.
515 static unsigned long long ratchet_messages;
518 * How long until we trigger a ratched advance.
520 static struct GNUNET_TIME_Relative ratchet_time;
523 /******************************** OTR ***********************************/
526 * Own global OTR ephemeral private key.
528 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
531 * Cached message used to perform a OTR key exchange.
533 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
536 * Task to generate a new OTR ephemeral key.
538 static struct GNUNET_SCHEDULER_Task *rekey_task;
543 static struct GNUNET_TIME_Relative rekey_period;
546 /******************************************************************************/
547 /******************************** STATIC ***********************************/
548 /******************************************************************************/
551 * Get string description for tunnel connectivity state.
553 * @param cs Tunnel state.
555 * @return String representation.
558 cstate2s (enum CadetTunnelCState cs)
564 case CADET_TUNNEL_NEW:
565 return "CADET_TUNNEL_NEW";
566 case CADET_TUNNEL_SEARCHING:
567 return "CADET_TUNNEL_SEARCHING";
568 case CADET_TUNNEL_WAITING:
569 return "CADET_TUNNEL_WAITING";
570 case CADET_TUNNEL_READY:
571 return "CADET_TUNNEL_READY";
572 case CADET_TUNNEL_SHUTDOWN:
573 return "CADET_TUNNEL_SHUTDOWN";
575 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
583 * Get string description for tunnel encryption state.
585 * @param es Tunnel state.
587 * @return String representation.
590 estate2s (enum CadetTunnelEState es)
596 case CADET_TUNNEL_KEY_UNINITIALIZED:
597 return "CADET_TUNNEL_KEY_UNINITIALIZED";
598 case CADET_TUNNEL_KEY_SENT:
599 return "CADET_TUNNEL_KEY_SENT";
600 case CADET_TUNNEL_KEY_PING:
601 return "CADET_TUNNEL_KEY_PING";
602 case CADET_TUNNEL_KEY_OK:
603 return "CADET_TUNNEL_KEY_OK";
604 case CADET_TUNNEL_KEY_REKEY:
605 return "CADET_TUNNEL_KEY_REKEY";
607 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
615 * @brief Check if tunnel is ready to send traffic.
617 * Tunnel must be connected and with encryption correctly set up.
619 * @param t Tunnel to check.
621 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
624 is_ready (struct CadetTunnel *t)
628 ready = CADET_TUNNEL_READY == t->cstate
629 && (CADET_TUNNEL_KEY_OK == t->estate
630 || CADET_TUNNEL_KEY_REKEY == t->estate);
631 ready = ready || GCT_is_loopback (t);
637 * Check if a key is invalid (NULL pointer or all 0)
639 * @param key Key to check.
641 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
644 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
646 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
651 memset (&null_key, 0, sizeof (null_key));
652 if (0 == memcmp (key, &null_key, sizeof (null_key)))
659 * Ephemeral key message purpose size.
661 * @return Size of the part of the ephemeral key message that must be signed.
664 ephemeral_purpose_size (void)
666 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
667 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
668 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
669 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
670 sizeof (struct GNUNET_PeerIdentity);
675 * Size of the encrypted part of a ping message.
677 * @return Size of the encrypted part of a ping message.
680 ping_encryption_size (void)
682 return sizeof (uint32_t);
687 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
689 * @param tch Tunnel's channel handle.
691 * @return Amount of messages the channel can still buffer towards the client.
694 get_channel_buffer (const struct CadetTChannel *tch)
698 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
699 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
701 return GCCH_get_buffer (tch->ch, fwd);
706 * Get the channel's allowance status.
708 * @param tch Tunnel's channel handle.
710 * @return #GNUNET_YES if we allowed the client to send data to us.
713 get_channel_allowed (const struct CadetTChannel *tch)
717 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
718 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
720 return GCCH_get_allowed (tch->ch, fwd);
725 * Get the connection's buffer.
727 * @param tc Tunnel's connection handle.
729 * @return Amount of messages the connection can still buffer.
732 get_connection_buffer (const struct CadetTConnection *tc)
736 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
737 fwd = GCC_is_origin (tc->c, GNUNET_YES);
739 return GCC_get_buffer (tc->c, fwd);
744 * Get the connection's allowance.
746 * @param tc Tunnel's connection handle.
748 * @return Amount of messages we have allowed the next peer to send us.
751 get_connection_allowed (const struct CadetTConnection *tc)
755 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
756 fwd = GCC_is_origin (tc->c, GNUNET_YES);
758 return GCC_get_allowed (tc->c, fwd);
763 * Check that a ephemeral key message s well formed and correctly signed.
765 * @param t Tunnel on which the message came.
766 * @param msg The ephemeral key message.
768 * @return #GNUNET_OK if message is fine, #GNUNET_SYSERR otherwise.
771 check_ephemeral (struct CadetTunnel *t,
772 const struct GNUNET_CADET_KX_Ephemeral *msg)
774 /* Check message size */
775 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
776 return GNUNET_SYSERR;
778 /* Check signature size */
779 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
780 return GNUNET_SYSERR;
783 if (0 != memcmp (&msg->origin_identity,
784 GCP_get_id (t->peer),
785 sizeof (struct GNUNET_PeerIdentity)))
786 return GNUNET_SYSERR;
788 /* Check signature */
790 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
793 &msg->origin_identity.public_key))
794 return GNUNET_SYSERR;
801 * Select the best key to use for encryption (send), based on KX status.
803 * Normally, return the current key. If there is a KX in progress and the old
804 * key is fresh enough, return the old key.
806 * @param t Tunnel to choose the key from.
808 * @return The optimal key to encrypt/hmac outgoing traffic.
810 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
811 select_key (const struct CadetTunnel *t)
813 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
815 if (NULL != t->kx_ctx
816 && NULL == t->kx_ctx->finish_task)
818 struct GNUNET_TIME_Relative age;
820 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
821 LOG (GNUNET_ERROR_TYPE_DEBUG,
822 " key exchange in progress, started %s ago\n",
823 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
824 // FIXME make duration of old keys configurable
825 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
827 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
828 key = &t->kx_ctx->e_key_old;
832 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
838 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
848 * @param plaintext Content to HMAC.
849 * @param size Size of @c plaintext.
850 * @param iv Initialization vector for the message.
851 * @param key Key to use.
852 * @param hmac[out] Destination to store the HMAC.
855 t_hmac (const void *plaintext, size_t size,
856 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
857 struct GNUNET_CADET_Hash *hmac)
859 static const char ctx[] = "cadet authentication key";
860 struct GNUNET_CRYPTO_AuthKey auth_key;
861 struct GNUNET_HashCode hash;
863 #if DUMP_KEYS_TO_STDERR
864 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
865 GNUNET_h2s ((struct GNUNET_HashCode *) key));
867 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
872 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
873 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
874 memcpy (hmac, &hash, sizeof (*hmac));
879 * Encrypt daforce_newest_keyta with the tunnel key.
881 * @param t Tunnel whose key to use.
882 * @param dst Destination for the encrypted data.
883 * @param src Source of the plaintext. Can overlap with @c dst.
884 * @param size Size of the plaintext.
885 * @param iv Initialization Vector to use.
886 * @param force_newest_key Force the use of the newest key, otherwise
887 * CADET will use the old key when allowed.
888 * This can happen in the case when a KX is going on
889 * and the old one hasn't expired.
892 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
893 size_t size, uint32_t iv, int force_newest_key)
895 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
896 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
899 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
901 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
902 #if DUMP_KEYS_TO_STDERR
903 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
904 GNUNET_h2s ((struct GNUNET_HashCode *) key));
906 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
907 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
908 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
909 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
918 * @param key Key to use.
919 * @param hash[out] Resulting HMAC.
920 * @param source Source key material (data to HMAC).
921 * @param len Length of @a source.
924 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
925 struct GNUNET_HashCode *hash,
926 void *source, unsigned int len)
928 static const char ctx[] = "axolotl HMAC-HASH";
929 struct GNUNET_CRYPTO_AuthKey auth_key;
931 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
934 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
939 * Derive a key from a HMAC-HASH.
941 * @param key Key to use for the HMAC.
942 * @param out Key to generate.
943 * @param source Source key material (data to HMAC).
944 * @param len Length of @a source.
947 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
948 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
949 void *source, unsigned int len)
951 static const char ctx[] = "axolotl derive key";
952 struct GNUNET_HashCode h;
954 t_ax_hmac_hash (key, &h, source, len);
955 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
956 &h, sizeof (h), NULL);
961 * Encrypt data with the axolotl tunnel key.
963 * @param t Tunnel whose key to use.
964 * @param dst Destination for the encrypted data.
965 * @param src Source of the plaintext. Can overlap with @c dst.
966 * @param size Size of the plaintext.
968 * @return Size of the encrypted data.
971 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
973 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
974 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
975 struct CadetTunnelAxolotl *ax;
978 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
982 ax->ratchet_counter++;
983 if (GNUNET_YES == ax->ratchet_allowed
984 && (ratchet_messages <= ax->ratchet_counter
985 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
987 ax->ratchet_flag = GNUNET_YES;
990 if (GNUNET_YES == ax->ratchet_flag)
992 /* Advance ratchet */
993 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
994 struct GNUNET_HashCode dh;
995 struct GNUNET_HashCode hmac;
996 static const char ctx[] = "axolotl ratchet";
998 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1001 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1002 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1003 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1004 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1005 &hmac, sizeof (hmac), NULL);
1012 ax->ratchet_flag = GNUNET_NO;
1013 ax->ratchet_allowed = GNUNET_NO;
1014 ax->ratchet_counter = 0;
1015 ax->ratchet_expiration =
1016 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1019 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1020 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1022 #if DUMP_KEYS_TO_STDERR
1023 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1024 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1025 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1026 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1029 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1031 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1033 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1040 * Decrypt data with the axolotl tunnel key.
1042 * @param t Tunnel whose key to use.
1043 * @param dst Destination for the decrypted data.
1044 * @param src Source of the ciphertext. Can overlap with @c dst.
1045 * @param size Size of the ciphertext.
1047 * @return Size of the decrypted data.
1050 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1052 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1053 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1054 struct CadetTunnelAxolotl *ax;
1057 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1061 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1062 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1064 #if DUMP_KEYS_TO_STDERR
1065 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1066 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1067 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1068 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1071 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1072 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1073 GNUNET_assert (out_size == size);
1075 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1077 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1084 * Encrypt header with the axolotl header key.
1086 * @param t Tunnel whose key to use.
1087 * @param msg Message whose header to encrypt.
1090 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1092 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1093 struct CadetTunnelAxolotl *ax;
1096 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1099 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1101 #if DUMP_KEYS_TO_STDERR
1102 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1103 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1106 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1107 &ax->HKs, &iv, &msg->Ns);
1109 GNUNET_assert (AX_HEADER_SIZE == out_size);
1111 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1116 * Decrypt header with the current axolotl header key.
1118 * @param t Tunnel whose current ax HK to use.
1119 * @param src Message whose header to decrypt.
1120 * @param dst Where to decrypt header to.
1123 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1124 struct GNUNET_CADET_AX *dst)
1126 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1127 struct CadetTunnelAxolotl *ax;
1130 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1133 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1135 #if DUMP_KEYS_TO_STDERR
1136 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1137 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1140 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1141 &ax->HKr, &iv, &dst->Ns);
1143 GNUNET_assert (AX_HEADER_SIZE == out_size);
1145 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1150 * Decrypt and verify data with the appropriate tunnel key.
1152 * @param key Key to use.
1153 * @param dst Destination for the plaintext.
1154 * @param src Source of the encrypted data. Can overlap with @c dst.
1155 * @param size Size of the encrypted data.
1156 * @param iv Initialization Vector to use.
1158 * @return Size of the decrypted data, -1 if an error was encountered.
1161 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1162 void *dst, const void *src, size_t size, uint32_t iv)
1164 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1167 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1168 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1169 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1170 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1171 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1172 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1179 * Decrypt and verify data with the most recent tunnel key.
1181 * @param t Tunnel whose key to use.
1182 * @param dst Destination for the plaintext.
1183 * @param src Source of the encrypted data. Can overlap with @c dst.
1184 * @param size Size of the encrypted data.
1185 * @param iv Initialization Vector to use.
1187 * @return Size of the decrypted data, -1 if an error was encountered.
1190 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1191 size_t size, uint32_t iv)
1195 #if DUMP_KEYS_TO_STDERR
1196 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1197 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1199 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1201 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1202 LOG (GNUNET_ERROR_TYPE_WARNING,
1203 "got data on %s without a valid key\n",
1205 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1209 out_size = decrypt (&t->d_key, dst, src, size, iv);
1216 * Decrypt and verify data with the appropriate tunnel key and verify that the
1217 * data has not been altered since it was sent by the remote peer.
1219 * @param t Tunnel whose key to use.
1220 * @param dst Destination for the plaintext.
1221 * @param src Source of the encrypted data. Can overlap with @c dst.
1222 * @param size Size of the encrypted data.
1223 * @param iv Initialization Vector to use.
1224 * @param msg_hmac HMAC of the message, cannot be NULL.
1226 * @return Size of the decrypted data, -1 if an error was encountered.
1229 t_decrypt_and_validate (struct CadetTunnel *t,
1230 void *dst, const void *src,
1231 size_t size, uint32_t iv,
1232 const struct GNUNET_CADET_Hash *msg_hmac)
1234 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1235 struct GNUNET_CADET_Hash hmac;
1238 /* Try primary (newest) key */
1240 decrypted_size = decrypt (key, dst, src, size, iv);
1241 t_hmac (src, size, iv, key, &hmac);
1242 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1243 return decrypted_size;
1245 /* If no key exchange is going on, we just failed. */
1246 if (NULL == t->kx_ctx)
1248 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1249 "Failed checksum validation on tunnel %s with no KX\n",
1251 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1255 /* Try secondary key, from previous KX period. */
1256 key = &t->kx_ctx->d_key_old;
1257 decrypted_size = decrypt (key, dst, src, size, iv);
1258 t_hmac (src, size, iv, key, &hmac);
1259 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1260 return decrypted_size;
1262 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1263 key = &t->kx_ctx->d_key_old2;
1264 decrypted_size = decrypt (key, dst, src, size, iv);
1265 t_hmac (src, size, iv, key, &hmac);
1266 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1267 return decrypted_size;
1269 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1270 "Failed checksum validation on tunnel %s with KX\n",
1272 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1278 * Decrypt and verify data with the appropriate tunnel key and verify that the
1279 * data has not been altered since it was sent by the remote peer.
1281 * @param t Tunnel whose key to use.
1282 * @param dst Destination for the plaintext.
1283 * @param src Source of the message. Can overlap with @c dst.
1284 * @param size Size of the message.
1286 * @return Size of the decrypted data, -1 if an error was encountered.
1289 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1290 const struct GNUNET_CADET_AX *src, size_t size)
1292 struct CadetTunnelSkippedKey *key;
1293 struct GNUNET_CADET_Hash hmac;
1294 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1299 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1301 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1302 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1308 #if DUMP_KEYS_TO_STDERR
1309 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1310 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1313 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1314 len = size - sizeof (struct GNUNET_CADET_AX);
1315 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1316 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1318 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1327 * Delete a key from the list of skipped keys.
1329 * @param t Tunnel to delete from.
1330 * @param HKr Header Key to use.
1333 store_skipped_key (struct CadetTunnel *t,
1334 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1336 struct CadetTunnelSkippedKey *key;
1338 key = GNUNET_new (struct CadetTunnelSkippedKey);
1339 key->timestamp = GNUNET_TIME_absolute_get ();
1340 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1341 #if DUMP_KEYS_TO_STDERR
1342 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1343 t->ax->Nr, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1344 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1345 GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1347 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1348 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1355 * Delete a key from the list of skipped keys.
1357 * @param t Tunnel to delete from.
1358 * @param key Key to delete.
1361 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1363 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1370 * Stage skipped AX keys and calculate the message key.
1372 * Stores each HK and MK for skipped messages.
1374 * @param t Tunnel where to stage the keys.
1375 * @param HKr Header key.
1376 * @param Np Received meesage number.
1379 store_ax_keys (struct CadetTunnel *t,
1380 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1385 gap = Np - t->ax->Nr;
1386 if (MAX_KEY_GAP < gap || 0 > gap)
1388 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1389 /* TODO: start new key exchange on return */
1390 GNUNET_break_op (0);
1394 while (t->ax->Nr < Np)
1395 store_skipped_key (t, HKr);
1397 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1398 delete_skipped_key (t, t->ax->skipped_tail);
1403 * Decrypt and verify data with the appropriate tunnel key and verify that the
1404 * data has not been altered since it was sent by the remote peer.
1406 * @param t Tunnel whose key to use.
1407 * @param dst Destination for the plaintext.
1408 * @param src Source of the message. Can overlap with @c dst.
1409 * @param size Size of the message.
1411 * @return Size of the decrypted data, -1 if an error was encountered.
1414 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1415 const struct GNUNET_CADET_AX *src, size_t size)
1417 struct CadetTunnelAxolotl *ax;
1418 struct GNUNET_CADET_Hash msg_hmac;
1419 struct GNUNET_HashCode hmac;
1420 struct GNUNET_CADET_AX *dstmsg;
1428 esize = size - sizeof (struct GNUNET_CADET_AX);
1433 /* Try current HK */
1434 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1435 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1437 static const char ctx[] = "axolotl ratchet";
1438 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1439 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1440 struct GNUNET_HashCode dh;
1441 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1444 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1445 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1447 /* Try the skipped keys, if that fails, we're out of luck. */
1448 return try_old_ax_keys (t, dst, src, size);
1450 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1454 t_h_decrypt (t, src, dstmsg);
1455 Np = ntohl (dstmsg->Ns);
1456 PNp = ntohl (dstmsg->PNs);
1457 DHRp = &dstmsg->DHRs;
1458 store_ax_keys (t, &HK, PNp);
1460 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1461 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1462 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1463 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1464 &hmac, sizeof (hmac), NULL);
1466 /* Commit "purported" keys */
1472 ax->ratchet_allowed = GNUNET_YES;
1476 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1477 t_h_decrypt (t, src, dstmsg);
1478 Np = ntohl (dstmsg->Ns);
1479 PNp = ntohl (dstmsg->PNs);
1483 store_ax_keys (t, &ax->HKr, Np);
1487 osize = t_ax_decrypt (t, dst, &src[1], esize);
1490 GNUNET_break_op (0);
1499 * Create key material by doing ECDH on the local and remote ephemeral keys.
1501 * @param key_material Where to store the key material.
1502 * @param ephemeral Peer's public ephemeral key.
1504 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1507 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1508 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1511 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1514 return GNUNET_SYSERR;
1521 * Create a symmetic key from the identities of both ends and the key material
1524 * @param key Destination for the generated key.
1525 * @param sender ID of the peer that will encrypt with @c key.
1526 * @param receiver ID of the peer that will decrypt with @c key.
1527 * @param key_material Hash created with ECDH with the ephemeral keys.
1530 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1531 const struct GNUNET_PeerIdentity *sender,
1532 const struct GNUNET_PeerIdentity *receiver,
1533 const struct GNUNET_HashCode *key_material)
1535 const char salt[] = "CADET kx salt";
1537 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1538 salt, sizeof (salt),
1539 key_material, sizeof (struct GNUNET_HashCode),
1540 sender, sizeof (struct GNUNET_PeerIdentity),
1541 receiver, sizeof (struct GNUNET_PeerIdentity),
1547 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1549 * @param t Tunnel for which to create the keys.
1551 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1554 create_otr_keys (struct CadetTunnel *t)
1556 struct GNUNET_HashCode km;
1558 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1559 return GNUNET_SYSERR;
1560 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1561 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1562 #if DUMP_KEYS_TO_STDERR
1563 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1564 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1565 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1566 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1567 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1568 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1569 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1570 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1571 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1578 * Create a new Key eXchange context for the tunnel.
1580 * If the old keys were verified, keep them for old traffic. Create a new KX
1581 * timestamp and a new nonce.
1583 * @param t Tunnel for which to create the KX ctx.
1585 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1588 create_kx_ctx (struct CadetTunnel *t)
1590 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1592 if (NULL != t->kx_ctx)
1594 if (NULL != t->kx_ctx->finish_task)
1596 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1597 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1598 t->kx_ctx->finish_task = NULL;
1603 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1604 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1608 if (CADET_TUNNEL_KEY_OK == t->estate)
1610 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1611 t->kx_ctx->d_key_old = t->d_key;
1612 t->kx_ctx->e_key_old = t->e_key;
1615 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1616 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1617 return create_otr_keys (t);
1622 * @brief Finish the Key eXchange and destroy the old keys.
1624 * @param cls Closure (Tunnel for which to finish the KX).
1625 * @param tc Task context.
1628 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1630 struct CadetTunnel *t = cls;
1632 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1634 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1636 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1640 GNUNET_free (t->kx_ctx);
1646 * Destroy a Key eXchange context for the tunnel. This function only schedules
1647 * the destruction, the freeing of the memory (and clearing of old key material)
1648 * happens after a delay!
1650 * @param t Tunnel whose KX ctx to destroy.
1653 destroy_kx_ctx (struct CadetTunnel *t)
1655 struct GNUNET_TIME_Relative delay;
1657 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1660 if (is_key_null (&t->kx_ctx->e_key_old))
1662 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1666 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1667 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1669 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1675 * Pick a connection on which send the next data message.
1677 * @param t Tunnel on which to send the message.
1679 * @return The connection on which to send the next message.
1681 static struct CadetConnection *
1682 tunnel_get_connection (struct CadetTunnel *t)
1684 struct CadetTConnection *iter;
1685 struct CadetConnection *best;
1687 unsigned int lowest_q;
1689 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1691 lowest_q = UINT_MAX;
1692 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1694 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1695 GCC_2s (iter->c), GCC_get_state (iter->c));
1696 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1698 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1699 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1707 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1713 * Callback called when a queued message is sent.
1715 * Calculates the average time and connection packet tracking.
1717 * @param cls Closure (TunnelQueue handle).
1718 * @param c Connection this message was on.
1719 * @param q Connection queue handle (unused).
1720 * @param type Type of message sent.
1721 * @param fwd Was this a FWD going message?
1722 * @param size Size of the message.
1725 tun_message_sent (void *cls,
1726 struct CadetConnection *c,
1727 struct CadetConnectionQueue *q,
1728 uint16_t type, int fwd, size_t size)
1730 struct CadetTunnelQueue *qt = cls;
1731 struct CadetTunnel *t;
1733 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1735 GNUNET_assert (NULL != qt->cont);
1736 t = NULL == c ? NULL : GCC_get_tunnel (c);
1737 qt->cont (qt->cont_cls, t, qt, type, size);
1743 count_queued_data (const struct CadetTunnel *t)
1745 struct CadetTunnelDelayed *iter;
1748 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1755 * Delete a queued message: either was sent or the channel was destroyed
1756 * before the tunnel's key exchange had a chance to finish.
1758 * @param tqd Delayed queue handle.
1761 unqueue_data (struct CadetTunnelDelayed *tqd)
1763 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1769 * Cache a message to be sent once tunnel is online.
1771 * @param t Tunnel to hold the message.
1772 * @param msg Message itself (copy will be made).
1774 static struct CadetTunnelDelayed *
1775 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1777 struct CadetTunnelDelayed *tqd;
1778 uint16_t size = ntohs (msg->size);
1780 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1782 GNUNET_assert (GNUNET_NO == is_ready (t));
1784 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1787 memcpy (&tqd[1], msg, size);
1788 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1794 * Sends an already built message on a tunnel, encrypting it and
1795 * choosing the best connection.
1797 * @param message Message to send. Function modifies it.
1798 * @param t Tunnel on which this message is transmitted.
1799 * @param c Connection to use (autoselect if NULL).
1800 * @param force Force the tunnel to take the message (buffer overfill).
1801 * @param cont Continuation to call once message is really sent.
1802 * @param cont_cls Closure for @c cont.
1803 * @param existing_q In case this a transmission of previously queued data,
1804 * this should be TunnelQueue given to the client.
1807 * @return Handle to cancel message.
1808 * NULL if @c cont is NULL or an error happens and message is dropped.
1810 static struct CadetTunnelQueue *
1811 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1812 struct CadetTunnel *t, struct CadetConnection *c,
1813 int force, GCT_sent cont, void *cont_cls,
1814 struct CadetTunnelQueue *existing_q)
1816 struct GNUNET_MessageHeader *msg;
1817 struct GNUNET_CADET_Encrypted *otr_msg;
1818 struct GNUNET_CADET_AX *ax_msg;
1819 struct CadetTunnelQueue *tq;
1820 size_t size = ntohs (message->size);
1821 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1822 + sizeof (struct GNUNET_CADET_AX);
1823 char cbuf[max_overhead + size];
1830 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1832 if (GNUNET_NO == is_ready (t))
1834 struct CadetTunnelDelayed *tqd;
1835 /* A non null existing_q indicates sending of queued data.
1836 * Should only happen after tunnel becomes ready.
1838 GNUNET_assert (NULL == existing_q);
1839 tqd = queue_data (t, message);
1842 tq = GNUNET_new (struct CadetTunnelQueue);
1846 tq->cont_cls = cont_cls;
1850 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1852 if (CADET_Axolotl == t->enc_type)
1854 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1855 msg = &ax_msg->header;
1856 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1857 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1858 ax_msg->reserved = 0;
1859 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1860 ax_msg->Ns = htonl (t->ax->Ns++);
1861 ax_msg->PNs = htonl (t->ax->PNs);
1862 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1863 t_h_encrypt (t, ax_msg);
1864 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1868 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1869 msg = &otr_msg->header;
1870 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1872 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1873 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1874 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1875 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1876 otr_msg->ttl = htonl (default_ttl);
1878 GNUNET_assert (esize == size);
1881 c = tunnel_get_connection (t);
1884 /* Why is tunnel 'ready'? Should have been queued! */
1885 if (NULL != t->destroy_task)
1888 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1890 return NULL; /* Drop... */
1894 type = ntohs (message->type);
1897 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1898 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1899 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1900 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1902 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1904 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1905 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1906 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1907 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1908 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1912 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1914 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1916 fwd = GCC_is_origin (c, GNUNET_YES);
1920 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1921 mid, c, fwd, force, NULL, NULL));
1924 if (NULL == existing_q)
1926 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1933 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1934 &tun_message_sent, tq);
1935 GNUNET_assert (NULL != tq->cq);
1937 tq->cont_cls = cont_cls;
1944 * Send all cached messages that we can, tunnel is online.
1946 * @param t Tunnel that holds the messages. Cannot be loopback.
1949 send_queued_data (struct CadetTunnel *t)
1951 struct CadetTunnelDelayed *tqd;
1952 struct CadetTunnelDelayed *next;
1955 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1957 if (GCT_is_loopback (t))
1963 if (GNUNET_NO == is_ready (t))
1965 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1966 estate2s (t->estate), cstate2s (t->cstate));
1970 room = GCT_get_connections_buffer (t);
1971 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1972 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1973 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1975 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1978 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1979 tqd->t, NULL, GNUNET_YES,
1980 NULL != tqd->tq ? tqd->tq->cont : NULL,
1981 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1985 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1990 * @brief Resend the AX KX until we complete the handshake.
1992 * @param cls Closure (tunnel).
1993 * @param tc Task context.
1996 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1998 struct CadetTunnel *t = cls;
2000 t->rekey_task = NULL;
2002 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2005 if (CADET_TUNNEL_KEY_OK == t->estate)
2008 GCT_send_ax_kx (t, GNUNET_YES);
2013 * Callback called when a queued message is sent.
2015 * @param cls Closure.
2016 * @param c Connection this message was on.
2017 * @param type Type of message sent.
2018 * @param fwd Was this a FWD going message?
2019 * @param size Size of the message.
2022 ephm_sent (void *cls,
2023 struct CadetConnection *c,
2024 struct CadetConnectionQueue *q,
2025 uint16_t type, int fwd, size_t size)
2027 struct CadetTunnel *t = cls;
2028 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2032 if (CADET_TUNNEL_KEY_OK == t->estate)
2035 if (CADET_Axolotl == t->enc_type && CADET_TUNNEL_KEY_OK != t->estate)
2037 if (NULL != t->rekey_task)
2040 GNUNET_SCHEDULER_cancel (t->rekey_task);
2042 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2049 * Callback called when a queued message is sent.
2051 * @param cls Closure.
2052 * @param c Connection this message was on.
2053 * @param type Type of message sent.
2054 * @param fwd Was this a FWD going message?
2055 * @param size Size of the message.
2058 pong_sent (void *cls,
2059 struct CadetConnection *c,
2060 struct CadetConnectionQueue *q,
2061 uint16_t type, int fwd, size_t size)
2063 struct CadetTunnel *t = cls;
2064 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2071 * Sends key exchange message on a tunnel, choosing the best connection.
2072 * Should not be called on loopback tunnels.
2074 * @param t Tunnel on which this message is transmitted.
2075 * @param message Message to send. Function modifies it.
2077 * @return Handle to the message in the connection queue.
2079 static struct CadetConnectionQueue *
2080 send_kx (struct CadetTunnel *t,
2081 const struct GNUNET_MessageHeader *message)
2083 struct CadetConnection *c;
2084 struct GNUNET_CADET_KX *msg;
2085 size_t size = ntohs (message->size);
2086 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2091 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2093 /* Avoid loopback. */
2094 if (GCT_is_loopback (t))
2099 type = ntohs (message->type);
2101 /* Even if tunnel is "being destroyed", send anyway.
2102 * Could be a response to a rekey initiated by remote peer,
2103 * who is trying to create a new channel!
2106 /* Must have a connection, or be looking for one. */
2107 if (NULL == t->connection_head)
2109 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2110 if (CADET_TUNNEL_SEARCHING != t->cstate)
2113 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2114 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2119 msg = (struct GNUNET_CADET_KX *) cbuf;
2120 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2121 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2122 c = tunnel_get_connection (t);
2125 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2128 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2134 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2135 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2136 GNUNET_assert (NULL == t->ephm_h);
2139 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2140 GNUNET_assert (NULL == t->pong_h);
2145 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2148 memcpy (&msg[1], message, size);
2150 fwd = GCC_is_origin (c, GNUNET_YES);
2152 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2159 * Send the ephemeral key on a tunnel.
2161 * @param t Tunnel on which to send the key.
2164 send_ephemeral (struct CadetTunnel *t)
2166 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2167 if (NULL != t->ephm_h)
2169 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2173 otr_kx_msg.sender_status = htonl (t->estate);
2174 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2175 otr_kx_msg.nonce = t->kx_ctx->challenge;
2176 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2177 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2178 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2179 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2180 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2185 * Send a pong message on a tunnel.
2187 * @param t Tunnel on which to send the pong.
2188 * @param challenge Value sent in the ping that we have to send back.
2191 send_pong (struct CadetTunnel *t, uint32_t challenge)
2193 struct GNUNET_CADET_KX_Pong msg;
2195 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2196 if (NULL != t->pong_h)
2198 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2201 msg.header.size = htons (sizeof (msg));
2202 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2203 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2204 msg.nonce = challenge;
2205 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2206 t_encrypt (t, &msg.nonce, &msg.nonce,
2207 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2208 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2210 t->pong_h = send_kx (t, &msg.header);
2215 * Initiate a rekey with the remote peer.
2217 * @param cls Closure (tunnel).
2218 * @param tc TaskContext.
2221 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2223 struct CadetTunnel *t = cls;
2225 t->rekey_task = NULL;
2227 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2228 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2231 GNUNET_assert (NULL != t->kx_ctx);
2232 struct GNUNET_TIME_Relative duration;
2234 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2235 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2236 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2238 // FIXME make duration of old keys configurable
2239 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2241 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2242 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2243 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2250 case CADET_TUNNEL_KEY_UNINITIALIZED:
2251 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2254 case CADET_TUNNEL_KEY_SENT:
2257 case CADET_TUNNEL_KEY_OK:
2259 * - state should have changed during rekey_iterator
2260 * - task should have been canceled at pong_handle
2263 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2266 case CADET_TUNNEL_KEY_PING:
2267 case CADET_TUNNEL_KEY_REKEY:
2271 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2274 // FIXME exponential backoff
2275 struct GNUNET_TIME_Relative delay;
2277 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2278 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2279 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2280 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2281 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2286 * Our ephemeral key has changed, create new session key on all tunnels.
2288 * Each tunnel will start the Key Exchange with a random delay between
2289 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2290 * per second, on average.
2292 * @param cls Closure (size of the hashmap).
2293 * @param key Current public key.
2294 * @param value Value in the hash map (tunnel).
2296 * @return #GNUNET_YES, so we should continue to iterate,
2299 rekey_iterator (void *cls,
2300 const struct GNUNET_PeerIdentity *key,
2303 struct CadetTunnel *t = value;
2304 struct GNUNET_TIME_Relative delay;
2305 long n = (long) cls;
2308 if (NULL != t->rekey_task)
2311 if (GNUNET_YES == GCT_is_loopback (t))
2314 if (CADET_OTR != t->enc_type)
2317 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2318 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2319 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2320 if (GNUNET_OK == create_kx_ctx (t))
2321 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2333 * Create a new ephemeral key and key message, schedule next rekeying.
2335 * @param cls Closure (unused).
2336 * @param tc TaskContext.
2339 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2341 struct GNUNET_TIME_Absolute time;
2346 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2349 GNUNET_free_non_null (otr_ephemeral_key);
2350 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2352 time = GNUNET_TIME_absolute_get ();
2353 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2354 time = GNUNET_TIME_absolute_add (time, rekey_period);
2355 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2356 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2357 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2358 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2359 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2361 GNUNET_assert (GNUNET_OK ==
2362 GNUNET_CRYPTO_eddsa_sign (id_key,
2363 &otr_kx_msg.purpose,
2364 &otr_kx_msg.signature));
2366 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2367 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2369 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2370 &global_otr_rekey, NULL);
2375 * Called only on shutdown, destroy every tunnel.
2377 * @param cls Closure (unused).
2378 * @param key Current public key.
2379 * @param value Value in the hash map (tunnel).
2381 * @return #GNUNET_YES, so we should continue to iterate,
2384 destroy_iterator (void *cls,
2385 const struct GNUNET_PeerIdentity *key,
2388 struct CadetTunnel *t = value;
2390 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2397 * Notify remote peer that we don't know a channel he is talking about,
2398 * probably CHANNEL_DESTROY was missed.
2400 * @param t Tunnel on which to notify.
2401 * @param gid ID of the channel.
2404 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2406 struct GNUNET_CADET_ChannelManage msg;
2408 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2409 msg.header.size = htons (sizeof (msg));
2410 msg.chid = htonl (gid);
2412 LOG (GNUNET_ERROR_TYPE_DEBUG,
2413 "WARNING destroying unknown channel %u on tunnel %s\n",
2415 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2420 * Demultiplex data per channel and call appropriate channel handler.
2422 * @param t Tunnel on which the data came.
2423 * @param msg Data message.
2424 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2425 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2426 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2427 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2430 handle_data (struct CadetTunnel *t,
2431 const struct GNUNET_CADET_Data *msg,
2434 struct CadetChannel *ch;
2438 size = ntohs (msg->header.size);
2440 sizeof (struct GNUNET_CADET_Data) +
2441 sizeof (struct GNUNET_MessageHeader))
2446 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2447 GC_m2s (ntohs (msg[1].header.type)));
2450 ch = GCT_get_channel (t, ntohl (msg->chid));
2453 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2455 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2457 send_channel_destroy (t, ntohl (msg->chid));
2461 GCCH_handle_data (ch, msg, fwd);
2466 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2468 * @param t Tunnel on which the DATA ACK came.
2469 * @param msg DATA ACK message.
2470 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2471 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2472 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2473 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2476 handle_data_ack (struct CadetTunnel *t,
2477 const struct GNUNET_CADET_DataACK *msg,
2480 struct CadetChannel *ch;
2484 size = ntohs (msg->header.size);
2485 if (size != sizeof (struct GNUNET_CADET_DataACK))
2492 ch = GCT_get_channel (t, ntohl (msg->chid));
2495 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2497 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2502 GCCH_handle_data_ack (ch, msg, fwd);
2507 * Handle channel create.
2509 * @param t Tunnel on which the data came.
2510 * @param msg Data message.
2513 handle_ch_create (struct CadetTunnel *t,
2514 const struct GNUNET_CADET_ChannelCreate *msg)
2516 struct CadetChannel *ch;
2520 size = ntohs (msg->header.size);
2521 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2528 ch = GCT_get_channel (t, ntohl (msg->chid));
2529 if (NULL != ch && ! GCT_is_loopback (t))
2531 /* Probably a retransmission, safe to ignore */
2532 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2534 ch = GCCH_handle_create (t, msg);
2536 GCT_add_channel (t, ch);
2542 * Handle channel NACK: check correctness and call channel handler for NACKs.
2544 * @param t Tunnel on which the NACK came.
2545 * @param msg NACK message.
2548 handle_ch_nack (struct CadetTunnel *t,
2549 const struct GNUNET_CADET_ChannelManage *msg)
2551 struct CadetChannel *ch;
2555 size = ntohs (msg->header.size);
2556 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2563 ch = GCT_get_channel (t, ntohl (msg->chid));
2566 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2568 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2573 GCCH_handle_nack (ch);
2578 * Handle a CHANNEL ACK (SYNACK/ACK).
2580 * @param t Tunnel on which the CHANNEL ACK came.
2581 * @param msg CHANNEL ACK message.
2582 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2583 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2584 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2585 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2588 handle_ch_ack (struct CadetTunnel *t,
2589 const struct GNUNET_CADET_ChannelManage *msg,
2592 struct CadetChannel *ch;
2596 size = ntohs (msg->header.size);
2597 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2604 ch = GCT_get_channel (t, ntohl (msg->chid));
2607 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2609 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2614 GCCH_handle_ack (ch, msg, fwd);
2619 * Handle a channel destruction message.
2621 * @param t Tunnel on which the message came.
2622 * @param msg Channel destroy message.
2623 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2624 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2625 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2626 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2629 handle_ch_destroy (struct CadetTunnel *t,
2630 const struct GNUNET_CADET_ChannelManage *msg,
2633 struct CadetChannel *ch;
2637 size = ntohs (msg->header.size);
2638 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2645 ch = GCT_get_channel (t, ntohl (msg->chid));
2648 /* Probably a retransmission, safe to ignore */
2652 GCCH_handle_destroy (ch, msg, fwd);
2657 * Create a new Axolotl ephemeral (ratchet) key.
2662 new_ephemeral (struct CadetTunnel *t)
2664 GNUNET_free_non_null (t->ax->DHRs);
2665 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2670 * Free Axolotl data.
2675 destroy_ax (struct CadetTunnel *t)
2680 GNUNET_free_non_null (t->ax->DHRs);
2681 GNUNET_free_non_null (t->ax->kx_0);
2683 GNUNET_free (t->ax);
2686 if (NULL != t->rekey_task)
2688 GNUNET_SCHEDULER_cancel (t->rekey_task);
2689 t->rekey_task = NULL;
2691 if (NULL != t->ephm_h)
2693 GCC_cancel (t->ephm_h);
2700 * The peer's ephemeral key has changed: update the symmetrical keys.
2702 * @param t Tunnel this message came on.
2703 * @param msg Key eXchange message.
2706 handle_ephemeral (struct CadetTunnel *t,
2707 const struct GNUNET_CADET_KX_Ephemeral *msg)
2709 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2711 if (GNUNET_OK != check_ephemeral (t, msg))
2713 GNUNET_break_op (0);
2717 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2721 t->enc_type = CADET_OTR;
2722 if (NULL != t->rekey_task)
2723 GNUNET_SCHEDULER_cancel (t->rekey_task);
2724 if (GNUNET_OK != create_kx_ctx (t))
2730 rekey_tunnel (t, NULL);
2731 GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2735 * If the key is different from what we know, derive the new E/D keys.
2736 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2738 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2739 sizeof (msg->ephemeral_key)))
2741 #if DUMP_KEYS_TO_STDERR
2742 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2743 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2744 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2745 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2747 t->peers_ephemeral_key = msg->ephemeral_key;
2749 if (GNUNET_OK != create_kx_ctx (t))
2756 if (CADET_TUNNEL_KEY_OK == t->estate)
2758 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2760 if (NULL != t->rekey_task)
2761 GNUNET_SCHEDULER_cancel (t->rekey_task);
2762 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2764 if (CADET_TUNNEL_KEY_SENT == t->estate)
2766 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2768 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2771 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2775 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2776 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2777 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2778 send_pong (t, nonce);
2784 * Peer has answer to our challenge.
2785 * If answer is successful, consider the key exchange finished and clean
2786 * up all related state.
2788 * @param t Tunnel this message came on.
2789 * @param msg Key eXchange Pong message.
2792 handle_pong (struct CadetTunnel *t,
2793 const struct GNUNET_CADET_KX_Pong *msg)
2797 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2798 if (NULL == t->rekey_task)
2800 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2803 if (NULL == t->kx_ctx)
2805 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2809 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2810 if (challenge != t->kx_ctx->challenge)
2812 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2813 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2814 challenge, msg->nonce, t->kx_ctx->challenge);
2818 GNUNET_SCHEDULER_cancel (t->rekey_task);
2819 t->rekey_task = NULL;
2821 /* Don't free the old keys right away, but after a delay.
2822 * Rationale: the KX could have happened over a very fast connection,
2823 * with payload traffic still signed with the old key stuck in a slower
2825 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2829 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2834 * Handle Axolotl handshake.
2836 * @param t Tunnel this message came on.
2837 * @param msg Key eXchange Pong message.
2840 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2842 struct CadetTunnelAxolotl *ax;
2843 struct GNUNET_HashCode key_material[3];
2844 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2845 const char salt[] = "CADET Axolotl salt";
2846 const struct GNUNET_PeerIdentity *pid;
2849 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2853 /* Something is wrong if ax is NULL. Whose fault it is? */
2854 GNUNET_break_op (CADET_OTR == t->enc_type);
2855 GNUNET_break (CADET_Axolotl == t->enc_type);
2859 pid = GCT_get_destination (t);
2860 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2861 am_I_alice = GNUNET_YES;
2862 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2863 am_I_alice = GNUNET_NO;
2866 GNUNET_break_op (0);
2870 if (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY ==
2871 (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2872 GCT_send_ax_kx (t, GNUNET_NO);
2874 if (CADET_TUNNEL_KEY_OK == t->estate)
2877 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2880 ax->DHRr = msg->ratchet_key;
2883 if (GNUNET_YES == am_I_alice)
2885 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2886 &msg->ephemeral_key, /* B0 */
2891 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
2892 &pid->public_key, /* A */
2897 if (GNUNET_YES == am_I_alice)
2899 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
2900 &pid->public_key, /* B */
2905 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2906 &msg->ephemeral_key, /* B0 */
2913 /* (This is the triple-DH, we could probably safely skip this,
2914 as A0/B0 are already in the key material.) */
2915 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
2916 &msg->ephemeral_key, /* B0 or A0 */
2919 #if DUMP_KEYS_TO_STDERR
2922 for (i = 0; i < 3; i++)
2923 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2924 i, GNUNET_h2s (&key_material[i]));
2929 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2930 salt, sizeof (salt),
2931 &key_material, sizeof (key_material), NULL);
2934 if (GNUNET_YES == am_I_alice)
2940 ax->ratchet_flag = GNUNET_YES;
2948 ax->ratchet_flag = GNUNET_NO;
2949 ax->ratchet_allowed = GNUNET_NO;
2950 ax->ratchet_counter = 0;
2951 ax->ratchet_expiration =
2952 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2954 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2959 * Demultiplex by message type and call appropriate handler for a message
2960 * towards a channel of a local tunnel.
2962 * @param t Tunnel this message came on.
2963 * @param msgh Message header.
2964 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2965 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2966 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2967 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2970 handle_decrypted (struct CadetTunnel *t,
2971 const struct GNUNET_MessageHeader *msgh,
2976 type = ntohs (msgh->type);
2977 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2981 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2982 /* Do nothing, connection aleady got updated. */
2983 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2986 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2987 /* Don't send hop ACK, wait for client to ACK */
2988 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2991 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2992 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2995 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2996 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2999 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3000 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3003 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3004 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3007 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3008 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3012 GNUNET_break_op (0);
3013 LOG (GNUNET_ERROR_TYPE_WARNING,
3014 "end-to-end message not known (%u)\n",
3015 ntohs (msgh->type));
3016 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3020 /******************************************************************************/
3021 /******************************** API ***********************************/
3022 /******************************************************************************/
3024 * Decrypt old format and demultiplex by message type. Call appropriate handler
3025 * for a message towards a channel of a local tunnel.
3027 * @param t Tunnel this message came on.
3028 * @param msg Message header.
3031 GCT_handle_encrypted (struct CadetTunnel *t,
3032 const struct GNUNET_MessageHeader *msg)
3034 uint16_t size = ntohs (msg->size);
3036 size_t payload_size;
3039 const struct GNUNET_MessageHeader *msgh;
3042 type = ntohs (msg->type);
3045 case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3047 const struct GNUNET_CADET_Encrypted *emsg;
3049 emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3050 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3051 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3052 emsg->iv, &emsg->hmac);
3055 case GNUNET_MESSAGE_TYPE_CADET_AX:
3057 const struct GNUNET_CADET_AX *emsg;
3059 emsg = (const struct GNUNET_CADET_AX *) msg;
3060 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3064 GNUNET_break_op (0);
3067 if (-1 == decrypted_size)
3069 GNUNET_break_op (0);
3073 /* FIXME: this is bad, as the structs returned from
3074 this loop may be unaligned, see util's MST for
3075 how to do this right. */
3077 while (off < decrypted_size)
3081 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3082 msize = ntohs (msgh->size);
3083 if (msize < sizeof (struct GNUNET_MessageHeader))
3085 GNUNET_break_op (0);
3088 handle_decrypted (t, msgh, GNUNET_SYSERR);
3095 * Demultiplex an encapsulated KX message by message type.
3097 * @param t Tunnel on which the message came.
3098 * @param message Payload of KX message.
3101 GCT_handle_kx (struct CadetTunnel *t,
3102 const struct GNUNET_MessageHeader *message)
3106 type = ntohs (message->type);
3107 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3110 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3111 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3114 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3115 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3118 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3119 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3123 GNUNET_break_op (0);
3124 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3129 * Initialize the tunnel subsystem.
3131 * @param c Configuration handle.
3132 * @param key ECC private key, to derive all other keys and do crypto.
3135 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3136 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3138 int expected_overhead;
3140 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3142 expected_overhead = 0;
3143 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3144 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3145 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3146 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3149 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3152 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3153 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3157 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3160 rekey_period = GNUNET_TIME_UNIT_DAYS;
3163 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3166 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3167 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3168 ratchet_messages = 64;
3171 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3174 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3175 "CADET", "RATCHET_TIME", "USING DEFAULT");
3176 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3182 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3183 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3184 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3185 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3186 otr_kx_msg.origin_identity = my_full_id;
3187 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3188 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3193 * Shut down the tunnel subsystem.
3198 if (NULL != rekey_task)
3200 GNUNET_SCHEDULER_cancel (rekey_task);
3203 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3204 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3211 * @param destination Peer this tunnel is towards.
3213 struct CadetTunnel *
3214 GCT_new (struct CadetPeer *destination)
3216 struct CadetTunnel *t;
3218 t = GNUNET_new (struct CadetTunnel);
3220 t->peer = destination;
3223 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3224 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3230 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3232 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3238 * Change the tunnel's connection state.
3240 * @param t Tunnel whose connection state to change.
3241 * @param cstate New connection state.
3244 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3248 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3249 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3250 if (myid != GCP_get_short_id (t->peer) &&
3251 CADET_TUNNEL_READY != t->cstate &&
3252 CADET_TUNNEL_READY == cstate)
3255 if (CADET_TUNNEL_KEY_OK == t->estate)
3257 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3258 send_queued_data (t);
3260 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3262 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3263 GCT_send_ax_kx (t, GNUNET_NO);
3267 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3272 if (CADET_TUNNEL_READY == cstate
3273 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3275 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3276 GCP_stop_search (t->peer);
3282 * Change the tunnel encryption state.
3284 * @param t Tunnel whose encryption state to change, or NULL.
3285 * @param state New encryption state.
3288 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3290 enum CadetTunnelEState old;
3297 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3298 GCP_2s (t->peer), estate2s (old));
3299 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3300 GCP_2s (t->peer), estate2s (t->estate));
3302 /* Send queued data if enc state changes to OK */
3303 if (myid != GCP_get_short_id (t->peer) &&
3304 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3306 send_queued_data (t);
3312 * @brief Check if tunnel has too many connections, and remove one if necessary.
3314 * Currently this means the newest connection, unless it is a direct one.
3315 * Implemented as a task to avoid freeing a connection that is in the middle
3316 * of being created/processed.
3318 * @param cls Closure (Tunnel to check).
3319 * @param tc Task context.
3322 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3324 struct CadetTunnel *t = cls;
3326 t->trim_connections_task = NULL;
3328 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3331 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3333 struct CadetTConnection *iter;
3334 struct CadetTConnection *c;
3336 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3338 if ((iter->created.abs_value_us > c->created.abs_value_us)
3339 && GNUNET_NO == GCC_is_direct (iter->c))
3346 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3348 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3361 * Add a connection to a tunnel.
3364 * @param c Connection.
3367 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3369 struct CadetTConnection *aux;
3371 GNUNET_assert (NULL != c);
3373 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3374 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3375 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3379 aux = GNUNET_new (struct CadetTConnection);
3381 aux->created = GNUNET_TIME_absolute_get ();
3383 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3385 if (CADET_TUNNEL_SEARCHING == t->cstate)
3386 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3388 if (NULL != t->trim_connections_task)
3389 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3394 * Remove a connection from a tunnel.
3397 * @param c Connection.
3400 GCT_remove_connection (struct CadetTunnel *t,
3401 struct CadetConnection *c)
3403 struct CadetTConnection *aux;
3404 struct CadetTConnection *next;
3407 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3408 GCC_2s (c), GCT_2s (t));
3409 for (aux = t->connection_head; aux != NULL; aux = next)
3414 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3419 conns = GCT_count_connections (t);
3421 && NULL == t->destroy_task
3422 && CADET_TUNNEL_SHUTDOWN != t->cstate
3423 && GNUNET_NO == shutting_down)
3425 if (0 == GCT_count_any_connections (t))
3426 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3428 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3431 /* Start new connections if needed */
3432 if (CONNECTIONS_PER_TUNNEL > conns
3433 && NULL == t->destroy_task
3434 && CADET_TUNNEL_SHUTDOWN != t->cstate
3435 && GNUNET_NO == shutting_down)
3437 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3438 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3442 /* If not marked as ready, no change is needed */
3443 if (CADET_TUNNEL_READY != t->cstate)
3446 /* Check if any connection is ready to maintain cstate */
3447 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3448 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3454 * Add a channel to a tunnel.
3457 * @param ch Channel.
3460 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3462 struct CadetTChannel *aux;
3464 GNUNET_assert (NULL != ch);
3466 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3468 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3470 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3475 aux = GNUNET_new (struct CadetTChannel);
3477 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3478 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3480 if (NULL != t->destroy_task)
3482 GNUNET_SCHEDULER_cancel (t->destroy_task);
3483 t->destroy_task = NULL;
3484 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3490 * Remove a channel from a tunnel.
3493 * @param ch Channel.
3496 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3498 struct CadetTChannel *aux;
3500 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3501 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3505 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3506 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3515 * Search for a channel by global ID.
3517 * @param t Tunnel containing the channel.
3518 * @param chid Public channel number.
3520 * @return channel handler, NULL if doesn't exist
3522 struct CadetChannel *
3523 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3525 struct CadetTChannel *iter;
3530 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3532 if (GCCH_get_id (iter->ch) == chid)
3536 return NULL == iter ? NULL : iter->ch;
3541 * @brief Destroy a tunnel and free all resources.
3543 * Should only be called a while after the tunnel has been marked as destroyed,
3544 * in case there is a new channel added to the same peer shortly after marking
3545 * the tunnel. This way we avoid a new public key handshake.
3547 * @param cls Closure (tunnel to destroy).
3548 * @param tc Task context.
3551 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3553 struct CadetTunnel *t = cls;
3554 struct CadetTConnection *iter;
3556 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3557 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3559 LOG (GNUNET_ERROR_TYPE_WARNING,
3560 "Not destroying tunnel, due to shutdown. "
3561 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3564 t->destroy_task = NULL;
3565 t->cstate = CADET_TUNNEL_SHUTDOWN;
3567 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3569 GCC_send_destroy (iter->c);
3576 * Tunnel is empty: destroy it.
3578 * Notifies all connections about the destruction.
3580 * @param t Tunnel to destroy.
3583 GCT_destroy_empty (struct CadetTunnel *t)
3585 if (GNUNET_YES == shutting_down)
3586 return; /* Will be destroyed immediately anyway */
3588 if (NULL != t->destroy_task)
3590 LOG (GNUNET_ERROR_TYPE_WARNING,
3591 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3593 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3595 /* should never happen, tunnel can only become empty once, and the
3596 * task identifier should be NO_TASK (cleaned when the tunnel was created
3597 * or became un-empty)
3602 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3605 // FIXME make delay a config option
3606 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3607 &delayed_destroy, t);
3608 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3609 t, t->destroy_task);
3614 * Destroy tunnel if empty (no more channels).
3616 * @param t Tunnel to destroy if empty.
3619 GCT_destroy_if_empty (struct CadetTunnel *t)
3621 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3622 if (0 < GCT_count_channels (t))
3625 GCT_destroy_empty (t);
3630 * Destroy the tunnel.
3632 * This function does not generate any warning traffic to clients or peers.
3635 * Cancel messages belonging to this tunnel queued to neighbors.
3636 * Free any allocated resources linked to the tunnel.
3638 * @param t The tunnel to destroy.
3641 GCT_destroy (struct CadetTunnel *t)
3643 struct CadetTConnection *iter_c;
3644 struct CadetTConnection *next_c;
3645 struct CadetTChannel *iter_ch;
3646 struct CadetTChannel *next_ch;
3651 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3653 GNUNET_break (GNUNET_YES ==
3654 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3655 GCP_get_id (t->peer), t));
3657 while (NULL != t->tq_head)
3658 unqueue_data (t->tq_head);
3660 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3662 next_c = iter_c->next;
3663 GCC_destroy (iter_c->c);
3665 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3667 next_ch = iter_ch->next;
3668 GCCH_destroy (iter_ch->ch);
3669 /* Should only happen on shutdown, but it's ok. */
3672 if (NULL != t->destroy_task)
3674 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3675 GNUNET_SCHEDULER_cancel (t->destroy_task);
3676 t->destroy_task = NULL;
3679 if (NULL != t->trim_connections_task)
3681 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3682 t->trim_connections_task);
3683 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3684 t->trim_connections_task = NULL;
3687 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3688 GCP_set_tunnel (t->peer, NULL);
3690 if (NULL != t->rekey_task)
3692 GNUNET_SCHEDULER_cancel (t->rekey_task);
3693 t->rekey_task = NULL;
3695 if (NULL != t->kx_ctx)
3697 if (NULL != t->kx_ctx->finish_task)
3698 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3699 GNUNET_free (t->kx_ctx);
3710 * @brief Use the given path for the tunnel.
3711 * Update the next and prev hops (and RCs).
3712 * (Re)start the path refresh in case the tunnel is locally owned.
3714 * @param t Tunnel to update.
3715 * @param p Path to use.
3717 * @return Connection created.
3719 struct CadetConnection *
3720 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3722 struct CadetConnection *c;
3723 struct GNUNET_CADET_Hash cid;
3724 unsigned int own_pos;
3726 if (NULL == t || NULL == p)
3732 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3738 for (own_pos = 0; own_pos < p->length; own_pos++)
3740 if (p->peers[own_pos] == myid)
3743 if (own_pos >= p->length)
3745 GNUNET_break_op (0);
3749 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3750 c = GCC_new (&cid, t, p, own_pos);
3753 /* Path was flawed */
3756 GCT_add_connection (t, c);
3762 * Count all created connections of a tunnel. Not necessarily ready connections!
3764 * @param t Tunnel on which to count.
3766 * @return Number of connections created, either being established or ready.
3769 GCT_count_any_connections (struct CadetTunnel *t)
3771 struct CadetTConnection *iter;
3777 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3785 * Count established (ready) connections of a tunnel.
3787 * @param t Tunnel on which to count.
3789 * @return Number of connections.
3792 GCT_count_connections (struct CadetTunnel *t)
3794 struct CadetTConnection *iter;
3800 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3801 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3809 * Count channels of a tunnel.
3811 * @param t Tunnel on which to count.
3813 * @return Number of channels.
3816 GCT_count_channels (struct CadetTunnel *t)
3818 struct CadetTChannel *iter;
3821 for (count = 0, iter = t->channel_head;
3823 iter = iter->next, count++) /* skip */;
3830 * Get the connectivity state of a tunnel.
3834 * @return Tunnel's connectivity state.
3836 enum CadetTunnelCState
3837 GCT_get_cstate (struct CadetTunnel *t)
3842 return (enum CadetTunnelCState) -1;
3849 * Get the encryption state of a tunnel.
3853 * @return Tunnel's encryption state.
3855 enum CadetTunnelEState
3856 GCT_get_estate (struct CadetTunnel *t)
3861 return (enum CadetTunnelEState) -1;
3867 * Get the maximum buffer space for a tunnel towards a local client.
3871 * @return Biggest buffer space offered by any channel in the tunnel.
3874 GCT_get_channels_buffer (struct CadetTunnel *t)
3876 struct CadetTChannel *iter;
3877 unsigned int buffer;
3878 unsigned int ch_buf;
3880 if (NULL == t->channel_head)
3882 /* Probably getting buffer for a channel create/handshake. */
3883 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3884 return MIN_TUNNEL_BUFFER;
3888 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3890 ch_buf = get_channel_buffer (iter);
3891 if (ch_buf > buffer)
3894 if (MIN_TUNNEL_BUFFER > buffer)
3895 return MIN_TUNNEL_BUFFER;
3897 if (MAX_TUNNEL_BUFFER < buffer)
3900 return MAX_TUNNEL_BUFFER;
3907 * Get the total buffer space for a tunnel for P2P traffic.
3911 * @return Buffer space offered by all connections in the tunnel.
3914 GCT_get_connections_buffer (struct CadetTunnel *t)
3916 struct CadetTConnection *iter;
3917 unsigned int buffer;
3919 if (GNUNET_NO == is_ready (t))
3921 if (count_queued_data (t) >= 3)
3928 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3930 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3934 buffer += get_connection_buffer (iter);
3942 * Get the tunnel's destination.
3946 * @return ID of the destination peer.
3948 const struct GNUNET_PeerIdentity *
3949 GCT_get_destination (struct CadetTunnel *t)
3951 return GCP_get_id (t->peer);
3956 * Get the tunnel's next free global channel ID.
3960 * @return GID of a channel free to use.
3963 GCT_get_next_chid (struct CadetTunnel *t)
3965 CADET_ChannelNumber chid;
3966 CADET_ChannelNumber mask;
3969 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3970 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3971 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3973 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3978 t->next_chid |= mask;
3980 while (NULL != GCT_get_channel (t, t->next_chid))
3982 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3983 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3984 t->next_chid |= mask;
3986 chid = t->next_chid;
3987 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3988 t->next_chid |= mask;
3995 * Send ACK on one or more channels due to buffer in connections.
3997 * @param t Channel which has some free buffer space.
4000 GCT_unchoke_channels (struct CadetTunnel *t)
4002 struct CadetTChannel *iter;
4003 unsigned int buffer;
4004 unsigned int channels = GCT_count_channels (t);
4005 unsigned int choked_n;
4006 struct CadetChannel *choked[channels];
4008 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4009 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4010 if (NULL != t->channel_head)
4011 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4013 if (NULL != t->tq_head)
4014 send_queued_data (t);
4016 /* Get buffer space */
4017 buffer = GCT_get_connections_buffer (t);
4023 /* Count and remember choked channels */
4025 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4027 if (GNUNET_NO == get_channel_allowed (iter))
4029 choked[choked_n++] = iter->ch;
4033 /* Unchoke random channels */
4034 while (0 < buffer && 0 < choked_n)
4036 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4038 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4041 choked[r] = choked[choked_n];
4047 * Send ACK on one or more connections due to buffer space to the client.
4049 * Iterates all connections of the tunnel and sends ACKs appropriately.
4054 GCT_send_connection_acks (struct CadetTunnel *t)
4056 struct CadetTConnection *iter;
4059 uint32_t allow_per_connection;
4061 unsigned int buffer;
4063 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4072 if (CADET_TUNNEL_READY != t->cstate)
4075 buffer = GCT_get_channels_buffer (t);
4076 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4078 /* Count connections, how many messages are already allowed */
4079 cs = GCT_count_connections (t);
4080 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4082 allowed += get_connection_allowed (iter);
4084 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4086 /* Make sure there is no overflow */
4087 if (allowed > buffer)
4090 /* Authorize connections to send more data */
4091 to_allow = buffer - allowed;
4093 for (iter = t->connection_head;
4094 NULL != iter && to_allow > 0;
4097 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4098 || get_connection_allowed (iter) > 64 / 3)
4102 allow_per_connection = to_allow/cs;
4103 to_allow -= allow_per_connection;
4105 GCC_allow (iter->c, allow_per_connection,
4106 GCC_is_origin (iter->c, GNUNET_NO));
4111 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4112 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4118 * Cancel a previously sent message while it's in the queue.
4120 * ONLY can be called before the continuation given to the send function
4121 * is called. Once the continuation is called, the message is no longer in the
4124 * @param q Handle to the queue.
4127 GCT_cancel (struct CadetTunnelQueue *q)
4131 GNUNET_assert (NULL == q->tqd);
4133 /* tun_message_sent() will be called and free q */
4135 else if (NULL != q->tqd)
4137 unqueue_data (q->tqd);
4139 if (NULL != q->cont)
4140 q->cont (q->cont_cls, NULL, q, 0, 0);
4151 * Sends an already built message on a tunnel, encrypting it and
4152 * choosing the best connection if not provided.
4154 * @param message Message to send. Function modifies it.
4155 * @param t Tunnel on which this message is transmitted.
4156 * @param c Connection to use (autoselect if NULL).
4157 * @param force Force the tunnel to take the message (buffer overfill).
4158 * @param cont Continuation to call once message is really sent.
4159 * @param cont_cls Closure for @c cont.
4161 * @return Handle to cancel message. NULL if @c cont is NULL.
4163 struct CadetTunnelQueue *
4164 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4165 struct CadetTunnel *t, struct CadetConnection *c,
4166 int force, GCT_sent cont, void *cont_cls)
4168 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4173 * Send an Axolotl KX message.
4175 * @param t Tunnel on which to send it.
4176 * @param force_reply Force the other peer to reply with a KX message.
4179 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4181 struct GNUNET_CADET_AX_KX msg;
4182 enum GNUNET_CADET_AX_KX_Flags flags;
4184 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4185 if (NULL != t->ephm_h)
4187 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4191 msg.header.size = htons (sizeof (msg));
4192 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4193 flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4195 flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4196 msg.flags = htonl (flags);
4197 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4198 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4200 t->ephm_h = send_kx (t, &msg.header);
4201 if (CADET_TUNNEL_KEY_OK != t->estate)
4202 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4207 * Sends an already built and encrypted message on a tunnel, choosing the best
4208 * connection. Useful for re-queueing messages queued on a destroyed connection.
4210 * @param message Message to send. Function modifies it.
4211 * @param t Tunnel on which this message is transmitted.
4214 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4215 struct CadetTunnel *t)
4217 struct CadetConnection *c;
4220 c = tunnel_get_connection (t);
4223 /* TODO queue in tunnel, marked as encrypted */
4224 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4227 fwd = GCC_is_origin (c, GNUNET_YES);
4228 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4229 GNUNET_YES, NULL, NULL));
4234 * Is the tunnel directed towards the local peer?
4238 * @return #GNUNET_YES if it is loopback.
4241 GCT_is_loopback (const struct CadetTunnel *t)
4243 return (myid == GCP_get_short_id (t->peer));
4248 * Is the tunnel this path already?
4253 * @return #GNUNET_YES a connection uses this path.
4256 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4258 struct CadetTConnection *iter;
4260 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4261 if (path_equivalent (GCC_get_path (iter->c), p))
4269 * Get a cost of a path for a tunnel considering existing connections.
4272 * @param path Candidate path.
4274 * @return Cost of the path (path length + number of overlapping nodes)
4277 GCT_get_path_cost (const struct CadetTunnel *t,
4278 const struct CadetPeerPath *path)
4280 struct CadetTConnection *iter;
4281 const struct CadetPeerPath *aux;
4282 unsigned int overlap;
4290 GNUNET_assert (NULL != t);
4292 for (i = 0; i < path->length; i++)
4294 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4296 aux = GCC_get_path (iter->c);
4300 for (j = 0; j < aux->length; j++)
4302 if (path->peers[i] == aux->peers[j])
4310 return path->length + overlap;
4315 * Get the static string for the peer this tunnel is directed.
4319 * @return Static string the destination peer's ID.
4322 GCT_2s (const struct CadetTunnel *t)
4327 return GCP_2s (t->peer);
4331 /******************************************************************************/
4332 /***************************** INFO/DEBUG *******************************/
4333 /******************************************************************************/
4336 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4338 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4339 struct CadetTunnelSkippedKey *iter;
4342 LOG2 (level, "TTT RK\t %s\n",
4343 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4345 LOG2 (level, "TTT HKs\t %s\n",
4346 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4347 LOG2 (level, "TTT HKr\t %s\n",
4348 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4349 LOG2 (level, "TTT NHKs\t %s\n",
4350 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4351 LOG2 (level, "TTT NHKr\t %s\n",
4352 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4354 LOG2 (level, "TTT CKs\t %s\n",
4355 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4356 LOG2 (level, "TTT CKr\t %s\n",
4357 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4359 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4360 LOG2 (level, "TTT DHRs\t %s\n",
4361 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
4362 LOG2 (level, "TTT DHRr\t %s\n",
4363 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4365 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4366 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4367 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4369 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4371 LOG2 (level, "TTT HK\t %s\n",
4372 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4373 LOG2 (level, "TTT MK\t %s\n",
4374 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4379 * Log all possible info about the tunnel state.
4381 * @param t Tunnel to debug.
4382 * @param level Debug level to use.
4385 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4387 struct CadetTChannel *iterch;
4388 struct CadetTConnection *iterc;
4391 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4393 __FILE__, __FUNCTION__, __LINE__);
4397 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4398 LOG2 (level, "TTT cstate %s, estate %s\n",
4399 cstate2s (t->cstate), estate2s (t->estate));
4400 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4401 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4402 #if DUMP_KEYS_TO_STDERR
4403 if (CADET_Axolotl == t->enc_type)
4405 ax_debug (t->ax, level);
4409 LOG2 (level, "TTT my EPHM\t %s\n",
4410 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4411 LOG2 (level, "TTT peers EPHM:\t %s\n",
4412 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4413 LOG2 (level, "TTT ENC key:\t %s\n",
4414 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4415 LOG2 (level, "TTT DEC key:\t %s\n",
4416 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4419 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4420 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4421 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4422 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4426 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4427 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4429 LOG2 (level, "TTT channels:\n");
4430 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4432 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4435 LOG2 (level, "TTT connections:\n");
4436 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4438 GCC_debug (iterc->c, level);
4441 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4446 * Iterate all tunnels.
4448 * @param iter Iterator.
4449 * @param cls Closure for @c iter.
4452 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4454 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4459 * Count all tunnels.
4461 * @return Number of tunnels to remote peers kept by this peer.
4464 GCT_count_all (void)
4466 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4471 * Iterate all connections of a tunnel.
4473 * @param t Tunnel whose connections to iterate.
4474 * @param iter Iterator.
4475 * @param cls Closure for @c iter.
4478 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4480 struct CadetTConnection *ct;
4482 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4488 * Iterate all channels of a tunnel.
4490 * @param t Tunnel whose channels to iterate.
4491 * @param iter Iterator.
4492 * @param cls Closure for @c iter.
4495 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4497 struct CadetTChannel *cht;
4499 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4500 iter (cls, cht->ch);