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))
777 /* This is probably an old "MESH" version. */
778 LOG (GNUNET_ERROR_TYPE_INFO,
779 "Expected ephemeral of size %u, got %u\n",
780 sizeof (struct GNUNET_CADET_KX_Ephemeral),
781 ntohs (msg->header.size));
782 return GNUNET_SYSERR;
785 /* Check signature size */
786 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
788 LOG (GNUNET_ERROR_TYPE_WARNING,
789 "Expected signature purpose of size %u, got %u\n",
790 ephemeral_purpose_size (),
791 ntohs (msg->purpose.size));
792 return GNUNET_SYSERR;
796 if (0 != memcmp (&msg->origin_identity,
797 GCP_get_id (t->peer),
798 sizeof (struct GNUNET_PeerIdentity)))
800 LOG (GNUNET_ERROR_TYPE_WARNING,
801 "Unexpected origin, got %s\n",
802 GNUNET_i2s (&msg->origin_identity));
803 return GNUNET_SYSERR;
806 /* Check signature */
808 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
811 &msg->origin_identity.public_key))
813 LOG (GNUNET_ERROR_TYPE_WARNING, "Signature invalid\n");
814 return GNUNET_SYSERR;
822 * Select the best key to use for encryption (send), based on KX status.
824 * Normally, return the current key. If there is a KX in progress and the old
825 * key is fresh enough, return the old key.
827 * @param t Tunnel to choose the key from.
829 * @return The optimal key to encrypt/hmac outgoing traffic.
831 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
832 select_key (const struct CadetTunnel *t)
834 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
836 if (NULL != t->kx_ctx
837 && NULL == t->kx_ctx->finish_task)
839 struct GNUNET_TIME_Relative age;
841 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
842 LOG (GNUNET_ERROR_TYPE_DEBUG,
843 " key exchange in progress, started %s ago\n",
844 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
845 // FIXME make duration of old keys configurable
846 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
848 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
849 key = &t->kx_ctx->e_key_old;
853 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
859 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
867 * Create a new Axolotl ephemeral (ratchet) key.
872 new_ephemeral (struct CadetTunnel *t)
874 GNUNET_free_non_null (t->ax->DHRs);
875 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
882 * @param plaintext Content to HMAC.
883 * @param size Size of @c plaintext.
884 * @param iv Initialization vector for the message.
885 * @param key Key to use.
886 * @param hmac[out] Destination to store the HMAC.
889 t_hmac (const void *plaintext, size_t size,
890 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
891 struct GNUNET_CADET_Hash *hmac)
893 static const char ctx[] = "cadet authentication key";
894 struct GNUNET_CRYPTO_AuthKey auth_key;
895 struct GNUNET_HashCode hash;
897 #if DUMP_KEYS_TO_STDERR
898 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
899 GNUNET_h2s ((struct GNUNET_HashCode *) key));
901 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
906 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
907 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
908 memcpy (hmac, &hash, sizeof (*hmac));
913 * Encrypt daforce_newest_keyta with the tunnel key.
915 * @param t Tunnel whose key to use.
916 * @param dst Destination for the encrypted data.
917 * @param src Source of the plaintext. Can overlap with @c dst.
918 * @param size Size of the plaintext.
919 * @param iv Initialization Vector to use.
920 * @param force_newest_key Force the use of the newest key, otherwise
921 * CADET will use the old key when allowed.
922 * This can happen in the case when a KX is going on
923 * and the old one hasn't expired.
926 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
927 size_t size, uint32_t iv, int force_newest_key)
929 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
930 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
933 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
935 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
936 #if DUMP_KEYS_TO_STDERR
937 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
938 GNUNET_h2s ((struct GNUNET_HashCode *) key));
940 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
941 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
942 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
943 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
952 * @param key Key to use.
953 * @param hash[out] Resulting HMAC.
954 * @param source Source key material (data to HMAC).
955 * @param len Length of @a source.
958 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
959 struct GNUNET_HashCode *hash,
960 void *source, unsigned int len)
962 static const char ctx[] = "axolotl HMAC-HASH";
963 struct GNUNET_CRYPTO_AuthKey auth_key;
965 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
968 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
973 * Derive a key from a HMAC-HASH.
975 * @param key Key to use for the HMAC.
976 * @param out Key to generate.
977 * @param source Source key material (data to HMAC).
978 * @param len Length of @a source.
981 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
982 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
983 void *source, unsigned int len)
985 static const char ctx[] = "axolotl derive key";
986 struct GNUNET_HashCode h;
988 t_ax_hmac_hash (key, &h, source, len);
989 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
990 &h, sizeof (h), NULL);
995 * Encrypt data with the axolotl tunnel key.
997 * @param t Tunnel whose key to use.
998 * @param dst Destination for the encrypted data.
999 * @param src Source of the plaintext. Can overlap with @c dst.
1000 * @param size Size of the plaintext.
1002 * @return Size of the encrypted data.
1005 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1007 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1008 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1009 struct CadetTunnelAxolotl *ax;
1012 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
1016 ax->ratchet_counter++;
1017 if (GNUNET_YES == ax->ratchet_allowed
1018 && (ratchet_messages <= ax->ratchet_counter
1019 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
1021 ax->ratchet_flag = GNUNET_YES;
1024 if (GNUNET_YES == ax->ratchet_flag)
1026 /* Advance ratchet */
1027 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1028 struct GNUNET_HashCode dh;
1029 struct GNUNET_HashCode hmac;
1030 static const char ctx[] = "axolotl ratchet";
1035 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1036 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1037 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1038 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1039 &hmac, sizeof (hmac), NULL);
1046 ax->ratchet_flag = GNUNET_NO;
1047 ax->ratchet_allowed = GNUNET_NO;
1048 ax->ratchet_counter = 0;
1049 ax->ratchet_expiration =
1050 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1053 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1054 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1056 #if DUMP_KEYS_TO_STDERR
1057 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1058 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1059 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1060 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1063 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1065 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1067 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1074 * Decrypt data with the axolotl tunnel key.
1076 * @param t Tunnel whose key to use.
1077 * @param dst Destination for the decrypted data.
1078 * @param src Source of the ciphertext. Can overlap with @c dst.
1079 * @param size Size of the ciphertext.
1081 * @return Size of the decrypted data.
1084 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1086 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1087 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1088 struct CadetTunnelAxolotl *ax;
1091 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1095 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1096 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1098 #if DUMP_KEYS_TO_STDERR
1099 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1100 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1101 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1102 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1105 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1106 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1107 GNUNET_assert (out_size == size);
1109 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1111 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1118 * Encrypt header with the axolotl header key.
1120 * @param t Tunnel whose key to use.
1121 * @param msg Message whose header to encrypt.
1124 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1126 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1127 struct CadetTunnelAxolotl *ax;
1130 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1133 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1135 #if DUMP_KEYS_TO_STDERR
1136 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1137 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1140 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1141 &ax->HKs, &iv, &msg->Ns);
1143 GNUNET_assert (AX_HEADER_SIZE == out_size);
1145 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1150 * Decrypt header with the current axolotl header key.
1152 * @param t Tunnel whose current ax HK to use.
1153 * @param src Message whose header to decrypt.
1154 * @param dst Where to decrypt header to.
1157 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1158 struct GNUNET_CADET_AX *dst)
1160 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1161 struct CadetTunnelAxolotl *ax;
1164 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1167 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1169 #if DUMP_KEYS_TO_STDERR
1170 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1171 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1174 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1175 &ax->HKr, &iv, &dst->Ns);
1177 GNUNET_assert (AX_HEADER_SIZE == out_size);
1179 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1184 * Decrypt and verify data with the appropriate tunnel key.
1186 * @param key Key to use.
1187 * @param dst Destination for the plaintext.
1188 * @param src Source of the encrypted data. Can overlap with @c dst.
1189 * @param size Size of the encrypted data.
1190 * @param iv Initialization Vector to use.
1192 * @return Size of the decrypted data, -1 if an error was encountered.
1195 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1196 void *dst, const void *src, size_t size, uint32_t iv)
1198 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1201 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1202 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1203 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1204 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1205 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1206 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1213 * Decrypt and verify data with the most recent tunnel key.
1215 * @param t Tunnel whose key to use.
1216 * @param dst Destination for the plaintext.
1217 * @param src Source of the encrypted data. Can overlap with @c dst.
1218 * @param size Size of the encrypted data.
1219 * @param iv Initialization Vector to use.
1221 * @return Size of the decrypted data, -1 if an error was encountered.
1224 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1225 size_t size, uint32_t iv)
1229 #if DUMP_KEYS_TO_STDERR
1230 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1231 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1233 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1235 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1236 LOG (GNUNET_ERROR_TYPE_WARNING,
1237 "got data on %s without a valid key\n",
1239 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1243 out_size = decrypt (&t->d_key, dst, src, size, iv);
1250 * Decrypt and verify data with the appropriate tunnel key and verify that the
1251 * data has not been altered since it was sent by the remote peer.
1253 * @param t Tunnel whose key to use.
1254 * @param dst Destination for the plaintext.
1255 * @param src Source of the encrypted data. Can overlap with @c dst.
1256 * @param size Size of the encrypted data.
1257 * @param iv Initialization Vector to use.
1258 * @param msg_hmac HMAC of the message, cannot be NULL.
1260 * @return Size of the decrypted data, -1 if an error was encountered.
1263 t_decrypt_and_validate (struct CadetTunnel *t,
1264 void *dst, const void *src,
1265 size_t size, uint32_t iv,
1266 const struct GNUNET_CADET_Hash *msg_hmac)
1268 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1269 struct GNUNET_CADET_Hash hmac;
1272 /* Try primary (newest) key */
1274 decrypted_size = decrypt (key, dst, src, size, iv);
1275 t_hmac (src, size, iv, key, &hmac);
1276 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1277 return decrypted_size;
1279 /* If no key exchange is going on, we just failed. */
1280 if (NULL == t->kx_ctx)
1282 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1283 "Failed checksum validation on tunnel %s with no KX\n",
1285 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1289 /* Try secondary key, from previous KX period. */
1290 key = &t->kx_ctx->d_key_old;
1291 decrypted_size = decrypt (key, dst, src, size, iv);
1292 t_hmac (src, size, iv, key, &hmac);
1293 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1294 return decrypted_size;
1296 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1297 key = &t->kx_ctx->d_key_old2;
1298 decrypted_size = decrypt (key, dst, src, size, iv);
1299 t_hmac (src, size, iv, key, &hmac);
1300 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1301 return decrypted_size;
1303 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1304 "Failed checksum validation on tunnel %s with KX\n",
1306 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1312 * Decrypt and verify data with the appropriate tunnel key and verify that the
1313 * data has not been altered since it was sent by the remote peer.
1315 * @param t Tunnel whose key to use.
1316 * @param dst Destination for the plaintext.
1317 * @param src Source of the message. Can overlap with @c dst.
1318 * @param size Size of the message.
1320 * @return Size of the decrypted data, -1 if an error was encountered.
1323 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1324 const struct GNUNET_CADET_AX *src, size_t size)
1326 struct CadetTunnelSkippedKey *key;
1327 struct GNUNET_CADET_Hash hmac;
1328 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1333 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1335 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1336 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1342 #if DUMP_KEYS_TO_STDERR
1343 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1344 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1347 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1348 len = size - sizeof (struct GNUNET_CADET_AX);
1349 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1350 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1352 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1361 * Delete a key from the list of skipped keys.
1363 * @param t Tunnel to delete from.
1364 * @param HKr Header Key to use.
1367 store_skipped_key (struct CadetTunnel *t,
1368 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1370 struct CadetTunnelSkippedKey *key;
1372 key = GNUNET_new (struct CadetTunnelSkippedKey);
1373 key->timestamp = GNUNET_TIME_absolute_get ();
1374 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1375 #if DUMP_KEYS_TO_STDERR
1376 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1377 t->ax->Nr, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1378 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1379 GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1381 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1382 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1389 * Delete a key from the list of skipped keys.
1391 * @param t Tunnel to delete from.
1392 * @param key Key to delete.
1395 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1397 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1404 * Stage skipped AX keys and calculate the message key.
1406 * Stores each HK and MK for skipped messages.
1408 * @param t Tunnel where to stage the keys.
1409 * @param HKr Header key.
1410 * @param Np Received meesage number.
1413 store_ax_keys (struct CadetTunnel *t,
1414 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1419 gap = Np - t->ax->Nr;
1420 if (MAX_KEY_GAP < gap || 0 > gap)
1422 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1423 /* TODO: start new key exchange on return */
1424 GNUNET_break_op (0);
1428 while (t->ax->Nr < Np)
1429 store_skipped_key (t, HKr);
1431 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1432 delete_skipped_key (t, t->ax->skipped_tail);
1437 * Decrypt and verify data with the appropriate tunnel key and verify that the
1438 * data has not been altered since it was sent by the remote peer.
1440 * @param t Tunnel whose key to use.
1441 * @param dst Destination for the plaintext.
1442 * @param src Source of the message. Can overlap with @c dst.
1443 * @param size Size of the message.
1445 * @return Size of the decrypted data, -1 if an error was encountered.
1448 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1449 const struct GNUNET_CADET_AX *src, size_t size)
1451 struct CadetTunnelAxolotl *ax;
1452 struct GNUNET_CADET_Hash msg_hmac;
1453 struct GNUNET_HashCode hmac;
1454 struct GNUNET_CADET_AX *dstmsg;
1462 esize = size - sizeof (struct GNUNET_CADET_AX);
1467 /* Try current HK */
1468 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1469 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1471 static const char ctx[] = "axolotl ratchet";
1472 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1473 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1474 struct GNUNET_HashCode dh;
1475 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1478 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1479 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1481 /* Try the skipped keys, if that fails, we're out of luck. */
1482 return try_old_ax_keys (t, dst, src, size);
1484 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1488 t_h_decrypt (t, src, dstmsg);
1489 Np = ntohl (dstmsg->Ns);
1490 PNp = ntohl (dstmsg->PNs);
1491 DHRp = &dstmsg->DHRs;
1492 store_ax_keys (t, &HK, PNp);
1494 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1495 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1496 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1497 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1498 &hmac, sizeof (hmac), NULL);
1500 /* Commit "purported" keys */
1506 ax->ratchet_allowed = GNUNET_YES;
1510 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1511 t_h_decrypt (t, src, dstmsg);
1512 Np = ntohl (dstmsg->Ns);
1513 PNp = ntohl (dstmsg->PNs);
1517 store_ax_keys (t, &ax->HKr, Np);
1521 osize = t_ax_decrypt (t, dst, &src[1], esize);
1524 GNUNET_break_op (0);
1533 * Create key material by doing ECDH on the local and remote ephemeral keys.
1535 * @param key_material Where to store the key material.
1536 * @param ephemeral Peer's public ephemeral key.
1538 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1541 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1542 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1545 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1548 return GNUNET_SYSERR;
1555 * Create a symmetic key from the identities of both ends and the key material
1558 * @param key Destination for the generated key.
1559 * @param sender ID of the peer that will encrypt with @c key.
1560 * @param receiver ID of the peer that will decrypt with @c key.
1561 * @param key_material Hash created with ECDH with the ephemeral keys.
1564 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1565 const struct GNUNET_PeerIdentity *sender,
1566 const struct GNUNET_PeerIdentity *receiver,
1567 const struct GNUNET_HashCode *key_material)
1569 const char salt[] = "CADET kx salt";
1571 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1572 salt, sizeof (salt),
1573 key_material, sizeof (struct GNUNET_HashCode),
1574 sender, sizeof (struct GNUNET_PeerIdentity),
1575 receiver, sizeof (struct GNUNET_PeerIdentity),
1581 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1583 * @param t Tunnel for which to create the keys.
1585 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1588 create_otr_keys (struct CadetTunnel *t)
1590 struct GNUNET_HashCode km;
1592 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1593 return GNUNET_SYSERR;
1594 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1595 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1596 #if DUMP_KEYS_TO_STDERR
1597 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1598 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1599 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1600 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1601 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1602 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1603 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1604 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1605 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1612 * Create a new Key eXchange context for the tunnel.
1614 * If the old keys were verified, keep them for old traffic. Create a new KX
1615 * timestamp and a new nonce.
1617 * @param t Tunnel for which to create the KX ctx.
1619 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1622 create_kx_ctx (struct CadetTunnel *t)
1624 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1626 if (NULL != t->kx_ctx)
1628 if (NULL != t->kx_ctx->finish_task)
1630 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1631 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1632 t->kx_ctx->finish_task = NULL;
1637 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1638 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1642 if (CADET_TUNNEL_KEY_OK == t->estate)
1644 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1645 t->kx_ctx->d_key_old = t->d_key;
1646 t->kx_ctx->e_key_old = t->e_key;
1649 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1650 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1651 return create_otr_keys (t);
1656 * @brief Finish the Key eXchange and destroy the old keys.
1658 * @param cls Closure (Tunnel for which to finish the KX).
1659 * @param tc Task context.
1662 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1664 struct CadetTunnel *t = cls;
1666 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1668 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1670 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1674 GNUNET_free (t->kx_ctx);
1680 * Destroy a Key eXchange context for the tunnel. This function only schedules
1681 * the destruction, the freeing of the memory (and clearing of old key material)
1682 * happens after a delay!
1684 * @param t Tunnel whose KX ctx to destroy.
1687 destroy_kx_ctx (struct CadetTunnel *t)
1689 struct GNUNET_TIME_Relative delay;
1691 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1694 if (is_key_null (&t->kx_ctx->e_key_old))
1696 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1700 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1701 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1703 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1709 * Pick a connection on which send the next data message.
1711 * @param t Tunnel on which to send the message.
1713 * @return The connection on which to send the next message.
1715 static struct CadetConnection *
1716 tunnel_get_connection (struct CadetTunnel *t)
1718 struct CadetTConnection *iter;
1719 struct CadetConnection *best;
1721 unsigned int lowest_q;
1723 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1725 lowest_q = UINT_MAX;
1726 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1728 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1729 GCC_2s (iter->c), GCC_get_state (iter->c));
1730 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1732 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1733 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1741 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1747 * Callback called when a queued message is sent.
1749 * Calculates the average time and connection packet tracking.
1751 * @param cls Closure (TunnelQueue handle).
1752 * @param c Connection this message was on.
1753 * @param q Connection queue handle (unused).
1754 * @param type Type of message sent.
1755 * @param fwd Was this a FWD going message?
1756 * @param size Size of the message.
1759 tun_message_sent (void *cls,
1760 struct CadetConnection *c,
1761 struct CadetConnectionQueue *q,
1762 uint16_t type, int fwd, size_t size)
1764 struct CadetTunnelQueue *qt = cls;
1765 struct CadetTunnel *t;
1767 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1769 GNUNET_assert (NULL != qt->cont);
1770 t = NULL == c ? NULL : GCC_get_tunnel (c);
1771 qt->cont (qt->cont_cls, t, qt, type, size);
1777 count_queued_data (const struct CadetTunnel *t)
1779 struct CadetTunnelDelayed *iter;
1782 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1789 * Delete a queued message: either was sent or the channel was destroyed
1790 * before the tunnel's key exchange had a chance to finish.
1792 * @param tqd Delayed queue handle.
1795 unqueue_data (struct CadetTunnelDelayed *tqd)
1797 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1803 * Cache a message to be sent once tunnel is online.
1805 * @param t Tunnel to hold the message.
1806 * @param msg Message itself (copy will be made).
1808 static struct CadetTunnelDelayed *
1809 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1811 struct CadetTunnelDelayed *tqd;
1812 uint16_t size = ntohs (msg->size);
1814 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1816 GNUNET_assert (GNUNET_NO == is_ready (t));
1818 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1821 memcpy (&tqd[1], msg, size);
1822 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1828 * Sends an already built message on a tunnel, encrypting it and
1829 * choosing the best connection.
1831 * @param message Message to send. Function modifies it.
1832 * @param t Tunnel on which this message is transmitted.
1833 * @param c Connection to use (autoselect if NULL).
1834 * @param force Force the tunnel to take the message (buffer overfill).
1835 * @param cont Continuation to call once message is really sent.
1836 * @param cont_cls Closure for @c cont.
1837 * @param existing_q In case this a transmission of previously queued data,
1838 * this should be TunnelQueue given to the client.
1841 * @return Handle to cancel message.
1842 * NULL if @c cont is NULL or an error happens and message is dropped.
1844 static struct CadetTunnelQueue *
1845 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1846 struct CadetTunnel *t, struct CadetConnection *c,
1847 int force, GCT_sent cont, void *cont_cls,
1848 struct CadetTunnelQueue *existing_q)
1850 struct GNUNET_MessageHeader *msg;
1851 struct GNUNET_CADET_Encrypted *otr_msg;
1852 struct GNUNET_CADET_AX *ax_msg;
1853 struct CadetTunnelQueue *tq;
1854 size_t size = ntohs (message->size);
1855 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1856 + sizeof (struct GNUNET_CADET_AX);
1857 char cbuf[max_overhead + size];
1864 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1866 if (GNUNET_NO == is_ready (t))
1868 struct CadetTunnelDelayed *tqd;
1869 /* A non null existing_q indicates sending of queued data.
1870 * Should only happen after tunnel becomes ready.
1872 GNUNET_assert (NULL == existing_q);
1873 tqd = queue_data (t, message);
1876 tq = GNUNET_new (struct CadetTunnelQueue);
1880 tq->cont_cls = cont_cls;
1884 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1886 if (CADET_Axolotl == t->enc_type)
1888 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1889 msg = &ax_msg->header;
1890 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1891 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1892 ax_msg->reserved = 0;
1893 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1894 ax_msg->Ns = htonl (t->ax->Ns++);
1895 ax_msg->PNs = htonl (t->ax->PNs);
1896 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1897 t_h_encrypt (t, ax_msg);
1898 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1902 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1903 msg = &otr_msg->header;
1904 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1906 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1907 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1908 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1909 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1910 otr_msg->ttl = htonl (default_ttl);
1912 GNUNET_assert (esize == size);
1915 c = tunnel_get_connection (t);
1918 /* Why is tunnel 'ready'? Should have been queued! */
1919 if (NULL != t->destroy_task)
1922 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1924 return NULL; /* Drop... */
1928 type = ntohs (message->type);
1931 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1932 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1933 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1934 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1936 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1938 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1939 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1940 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1941 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1942 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1946 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1948 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1950 fwd = GCC_is_origin (c, GNUNET_YES);
1954 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1955 mid, c, fwd, force, NULL, NULL));
1958 if (NULL == existing_q)
1960 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1967 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1968 &tun_message_sent, tq);
1969 GNUNET_assert (NULL != tq->cq);
1971 tq->cont_cls = cont_cls;
1978 * Send all cached messages that we can, tunnel is online.
1980 * @param t Tunnel that holds the messages. Cannot be loopback.
1983 send_queued_data (struct CadetTunnel *t)
1985 struct CadetTunnelDelayed *tqd;
1986 struct CadetTunnelDelayed *next;
1989 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1991 if (GCT_is_loopback (t))
1997 if (GNUNET_NO == is_ready (t))
1999 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
2000 estate2s (t->estate), cstate2s (t->cstate));
2004 room = GCT_get_connections_buffer (t);
2005 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2006 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
2007 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
2009 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
2012 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2013 tqd->t, NULL, GNUNET_YES,
2014 NULL != tqd->tq ? tqd->tq->cont : NULL,
2015 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2019 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2024 * @brief Resend the AX KX until we complete the handshake.
2026 * @param cls Closure (tunnel).
2027 * @param tc Task context.
2030 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2032 struct CadetTunnel *t = cls;
2034 t->rekey_task = NULL;
2036 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2039 if (CADET_TUNNEL_KEY_OK == t->estate)
2042 GCT_send_ax_kx (t, GNUNET_YES);
2047 * Callback called when a queued message is sent.
2049 * @param cls Closure.
2050 * @param c Connection this message was on.
2051 * @param type Type of message sent.
2052 * @param fwd Was this a FWD going message?
2053 * @param size Size of the message.
2056 ephm_sent (void *cls,
2057 struct CadetConnection *c,
2058 struct CadetConnectionQueue *q,
2059 uint16_t type, int fwd, size_t size)
2061 struct CadetTunnel *t = cls;
2062 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2066 if (CADET_TUNNEL_KEY_OK == t->estate)
2069 if (CADET_Axolotl == t->enc_type && CADET_TUNNEL_KEY_OK != t->estate)
2071 if (NULL != t->rekey_task)
2074 GNUNET_SCHEDULER_cancel (t->rekey_task);
2076 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2083 * Callback called when a queued message is sent.
2085 * @param cls Closure.
2086 * @param c Connection this message was on.
2087 * @param type Type of message sent.
2088 * @param fwd Was this a FWD going message?
2089 * @param size Size of the message.
2092 pong_sent (void *cls,
2093 struct CadetConnection *c,
2094 struct CadetConnectionQueue *q,
2095 uint16_t type, int fwd, size_t size)
2097 struct CadetTunnel *t = cls;
2098 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2105 * Sends key exchange message on a tunnel, choosing the best connection.
2106 * Should not be called on loopback tunnels.
2108 * @param t Tunnel on which this message is transmitted.
2109 * @param message Message to send. Function modifies it.
2111 * @return Handle to the message in the connection queue.
2113 static struct CadetConnectionQueue *
2114 send_kx (struct CadetTunnel *t,
2115 const struct GNUNET_MessageHeader *message)
2117 struct CadetConnection *c;
2118 struct GNUNET_CADET_KX *msg;
2119 size_t size = ntohs (message->size);
2120 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2125 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2127 /* Avoid loopback. */
2128 if (GCT_is_loopback (t))
2133 type = ntohs (message->type);
2135 /* Even if tunnel is "being destroyed", send anyway.
2136 * Could be a response to a rekey initiated by remote peer,
2137 * who is trying to create a new channel!
2140 /* Must have a connection, or be looking for one. */
2141 if (NULL == t->connection_head)
2143 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2144 if (CADET_TUNNEL_SEARCHING != t->cstate)
2147 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2148 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2153 msg = (struct GNUNET_CADET_KX *) cbuf;
2154 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2155 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2156 c = tunnel_get_connection (t);
2159 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2162 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2168 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2169 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2170 GNUNET_assert (NULL == t->ephm_h);
2173 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2174 GNUNET_assert (NULL == t->pong_h);
2179 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2182 memcpy (&msg[1], message, size);
2184 fwd = GCC_is_origin (c, GNUNET_YES);
2186 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2193 * Send the ephemeral key on a tunnel.
2195 * @param t Tunnel on which to send the key.
2198 send_ephemeral (struct CadetTunnel *t)
2200 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2201 if (NULL != t->ephm_h)
2203 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2207 otr_kx_msg.sender_status = htonl (t->estate);
2208 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2209 otr_kx_msg.nonce = t->kx_ctx->challenge;
2210 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2211 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2212 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2213 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2214 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2219 * Send a pong message on a tunnel.
2221 * @param t Tunnel on which to send the pong.
2222 * @param challenge Value sent in the ping that we have to send back.
2225 send_pong (struct CadetTunnel *t, uint32_t challenge)
2227 struct GNUNET_CADET_KX_Pong msg;
2229 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2230 if (NULL != t->pong_h)
2232 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2235 msg.header.size = htons (sizeof (msg));
2236 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2237 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2238 msg.nonce = challenge;
2239 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2240 t_encrypt (t, &msg.nonce, &msg.nonce,
2241 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2242 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2244 t->pong_h = send_kx (t, &msg.header);
2249 * Initiate a rekey with the remote peer.
2251 * @param cls Closure (tunnel).
2252 * @param tc TaskContext.
2255 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2257 struct CadetTunnel *t = cls;
2259 t->rekey_task = NULL;
2261 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2262 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2265 GNUNET_assert (NULL != t->kx_ctx);
2266 struct GNUNET_TIME_Relative duration;
2268 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2269 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2270 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2272 // FIXME make duration of old keys configurable
2273 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2275 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2276 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2277 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2284 case CADET_TUNNEL_KEY_UNINITIALIZED:
2285 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2288 case CADET_TUNNEL_KEY_SENT:
2291 case CADET_TUNNEL_KEY_OK:
2293 * - state should have changed during rekey_iterator
2294 * - task should have been canceled at pong_handle
2297 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2300 case CADET_TUNNEL_KEY_PING:
2301 case CADET_TUNNEL_KEY_REKEY:
2305 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2308 // FIXME exponential backoff
2309 struct GNUNET_TIME_Relative delay;
2311 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2312 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2313 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2314 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2315 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2320 * Our ephemeral key has changed, create new session key on all tunnels.
2322 * Each tunnel will start the Key Exchange with a random delay between
2323 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2324 * per second, on average.
2326 * @param cls Closure (size of the hashmap).
2327 * @param key Current public key.
2328 * @param value Value in the hash map (tunnel).
2330 * @return #GNUNET_YES, so we should continue to iterate,
2333 rekey_iterator (void *cls,
2334 const struct GNUNET_PeerIdentity *key,
2337 struct CadetTunnel *t = value;
2338 struct GNUNET_TIME_Relative delay;
2339 long n = (long) cls;
2342 if (NULL != t->rekey_task)
2345 if (GNUNET_YES == GCT_is_loopback (t))
2348 if (CADET_OTR != t->enc_type)
2351 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2352 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2353 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2354 if (GNUNET_OK == create_kx_ctx (t))
2355 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2367 * Create a new ephemeral key and key message, schedule next rekeying.
2369 * @param cls Closure (unused).
2370 * @param tc TaskContext.
2373 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2375 struct GNUNET_TIME_Absolute time;
2380 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2383 GNUNET_free_non_null (otr_ephemeral_key);
2384 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2386 time = GNUNET_TIME_absolute_get ();
2387 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2388 time = GNUNET_TIME_absolute_add (time, rekey_period);
2389 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2390 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2391 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2392 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2393 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2395 GNUNET_assert (GNUNET_OK ==
2396 GNUNET_CRYPTO_eddsa_sign (id_key,
2397 &otr_kx_msg.purpose,
2398 &otr_kx_msg.signature));
2400 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2401 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2403 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2404 &global_otr_rekey, NULL);
2409 * Called only on shutdown, destroy every tunnel.
2411 * @param cls Closure (unused).
2412 * @param key Current public key.
2413 * @param value Value in the hash map (tunnel).
2415 * @return #GNUNET_YES, so we should continue to iterate,
2418 destroy_iterator (void *cls,
2419 const struct GNUNET_PeerIdentity *key,
2422 struct CadetTunnel *t = value;
2424 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2431 * Notify remote peer that we don't know a channel he is talking about,
2432 * probably CHANNEL_DESTROY was missed.
2434 * @param t Tunnel on which to notify.
2435 * @param gid ID of the channel.
2438 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2440 struct GNUNET_CADET_ChannelManage msg;
2442 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2443 msg.header.size = htons (sizeof (msg));
2444 msg.chid = htonl (gid);
2446 LOG (GNUNET_ERROR_TYPE_DEBUG,
2447 "WARNING destroying unknown channel %u on tunnel %s\n",
2449 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2454 * Demultiplex data per channel and call appropriate channel handler.
2456 * @param t Tunnel on which the data came.
2457 * @param msg Data message.
2458 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2459 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2460 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2461 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2464 handle_data (struct CadetTunnel *t,
2465 const struct GNUNET_CADET_Data *msg,
2468 struct CadetChannel *ch;
2472 size = ntohs (msg->header.size);
2474 sizeof (struct GNUNET_CADET_Data) +
2475 sizeof (struct GNUNET_MessageHeader))
2480 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2481 GC_m2s (ntohs (msg[1].header.type)));
2484 ch = GCT_get_channel (t, ntohl (msg->chid));
2487 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2489 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2491 send_channel_destroy (t, ntohl (msg->chid));
2495 GCCH_handle_data (ch, msg, fwd);
2500 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2502 * @param t Tunnel on which the DATA ACK came.
2503 * @param msg DATA ACK message.
2504 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2505 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2506 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2507 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2510 handle_data_ack (struct CadetTunnel *t,
2511 const struct GNUNET_CADET_DataACK *msg,
2514 struct CadetChannel *ch;
2518 size = ntohs (msg->header.size);
2519 if (size != sizeof (struct GNUNET_CADET_DataACK))
2526 ch = GCT_get_channel (t, ntohl (msg->chid));
2529 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2531 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2536 GCCH_handle_data_ack (ch, msg, fwd);
2541 * Handle channel create.
2543 * @param t Tunnel on which the data came.
2544 * @param msg Data message.
2547 handle_ch_create (struct CadetTunnel *t,
2548 const struct GNUNET_CADET_ChannelCreate *msg)
2550 struct CadetChannel *ch;
2554 size = ntohs (msg->header.size);
2555 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2562 ch = GCT_get_channel (t, ntohl (msg->chid));
2563 if (NULL != ch && ! GCT_is_loopback (t))
2565 /* Probably a retransmission, safe to ignore */
2566 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2568 ch = GCCH_handle_create (t, msg);
2570 GCT_add_channel (t, ch);
2576 * Handle channel NACK: check correctness and call channel handler for NACKs.
2578 * @param t Tunnel on which the NACK came.
2579 * @param msg NACK message.
2582 handle_ch_nack (struct CadetTunnel *t,
2583 const struct GNUNET_CADET_ChannelManage *msg)
2585 struct CadetChannel *ch;
2589 size = ntohs (msg->header.size);
2590 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2597 ch = GCT_get_channel (t, ntohl (msg->chid));
2600 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2602 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2607 GCCH_handle_nack (ch);
2612 * Handle a CHANNEL ACK (SYNACK/ACK).
2614 * @param t Tunnel on which the CHANNEL ACK came.
2615 * @param msg CHANNEL ACK message.
2616 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2617 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2618 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2619 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2622 handle_ch_ack (struct CadetTunnel *t,
2623 const struct GNUNET_CADET_ChannelManage *msg,
2626 struct CadetChannel *ch;
2630 size = ntohs (msg->header.size);
2631 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2638 ch = GCT_get_channel (t, ntohl (msg->chid));
2641 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2643 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2648 GCCH_handle_ack (ch, msg, fwd);
2653 * Handle a channel destruction message.
2655 * @param t Tunnel on which the message came.
2656 * @param msg Channel destroy message.
2657 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2658 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2659 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2660 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2663 handle_ch_destroy (struct CadetTunnel *t,
2664 const struct GNUNET_CADET_ChannelManage *msg,
2667 struct CadetChannel *ch;
2671 size = ntohs (msg->header.size);
2672 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2679 ch = GCT_get_channel (t, ntohl (msg->chid));
2682 /* Probably a retransmission, safe to ignore */
2686 GCCH_handle_destroy (ch, msg, fwd);
2691 * Free Axolotl data.
2696 destroy_ax (struct CadetTunnel *t)
2701 GNUNET_free_non_null (t->ax->DHRs);
2702 GNUNET_free_non_null (t->ax->kx_0);
2703 while (NULL != t->ax->skipped_head)
2704 delete_skipped_key (t, t->ax->skipped_head);
2705 GNUNET_assert (0 == t->ax->skipped);
2707 GNUNET_free (t->ax);
2710 if (NULL != t->rekey_task)
2712 GNUNET_SCHEDULER_cancel (t->rekey_task);
2713 t->rekey_task = NULL;
2715 if (NULL != t->ephm_h)
2717 GCC_cancel (t->ephm_h);
2724 * The peer's ephemeral key has changed: update the symmetrical keys.
2726 * @param t Tunnel this message came on.
2727 * @param msg Key eXchange message.
2730 handle_ephemeral (struct CadetTunnel *t,
2731 const struct GNUNET_CADET_KX_Ephemeral *msg)
2733 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2735 /* Some old versions are still around, don't log as error. */
2736 if (GNUNET_OK != check_ephemeral (t, msg))
2739 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2743 t->enc_type = CADET_OTR;
2744 if (NULL != t->rekey_task)
2745 GNUNET_SCHEDULER_cancel (t->rekey_task);
2746 if (GNUNET_OK != create_kx_ctx (t))
2752 rekey_tunnel (t, NULL);
2753 GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2757 * If the key is different from what we know, derive the new E/D keys.
2758 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2760 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2761 sizeof (msg->ephemeral_key)))
2763 #if DUMP_KEYS_TO_STDERR
2764 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2765 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2766 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2767 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2769 t->peers_ephemeral_key = msg->ephemeral_key;
2771 if (GNUNET_OK != create_kx_ctx (t))
2778 if (CADET_TUNNEL_KEY_OK == t->estate)
2780 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2782 if (NULL != t->rekey_task)
2783 GNUNET_SCHEDULER_cancel (t->rekey_task);
2784 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2786 if (CADET_TUNNEL_KEY_SENT == t->estate)
2788 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2790 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2793 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2797 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2798 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2799 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2800 send_pong (t, nonce);
2806 * Peer has answer to our challenge.
2807 * If answer is successful, consider the key exchange finished and clean
2808 * up all related state.
2810 * @param t Tunnel this message came on.
2811 * @param msg Key eXchange Pong message.
2814 handle_pong (struct CadetTunnel *t,
2815 const struct GNUNET_CADET_KX_Pong *msg)
2819 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2820 if (NULL == t->rekey_task)
2822 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2825 if (NULL == t->kx_ctx)
2827 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2831 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2832 if (challenge != t->kx_ctx->challenge)
2834 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2835 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2836 challenge, msg->nonce, t->kx_ctx->challenge);
2840 GNUNET_SCHEDULER_cancel (t->rekey_task);
2841 t->rekey_task = NULL;
2843 /* Don't free the old keys right away, but after a delay.
2844 * Rationale: the KX could have happened over a very fast connection,
2845 * with payload traffic still signed with the old key stuck in a slower
2847 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2851 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2856 * Handle Axolotl handshake.
2858 * @param t Tunnel this message came on.
2859 * @param msg Key eXchange Pong message.
2862 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2864 struct CadetTunnelAxolotl *ax;
2865 struct GNUNET_HashCode key_material[3];
2866 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2867 const char salt[] = "CADET Axolotl salt";
2868 const struct GNUNET_PeerIdentity *pid;
2871 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2875 /* Something is wrong if ax is NULL. Whose fault it is? */
2876 GNUNET_break_op (CADET_OTR == t->enc_type);
2877 GNUNET_break (CADET_Axolotl == t->enc_type);
2881 pid = GCT_get_destination (t);
2882 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2883 am_I_alice = GNUNET_YES;
2884 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2885 am_I_alice = GNUNET_NO;
2888 GNUNET_break_op (0);
2892 if (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY ==
2893 (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2894 GCT_send_ax_kx (t, GNUNET_NO);
2896 if (CADET_TUNNEL_KEY_OK == t->estate)
2899 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2902 ax->DHRr = msg->ratchet_key;
2905 if (GNUNET_YES == am_I_alice)
2907 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2908 &msg->ephemeral_key, /* B0 */
2913 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
2914 &pid->public_key, /* A */
2919 if (GNUNET_YES == am_I_alice)
2921 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
2922 &pid->public_key, /* B */
2927 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2928 &msg->ephemeral_key, /* B0 */
2935 /* (This is the triple-DH, we could probably safely skip this,
2936 as A0/B0 are already in the key material.) */
2937 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
2938 &msg->ephemeral_key, /* B0 or A0 */
2941 #if DUMP_KEYS_TO_STDERR
2944 for (i = 0; i < 3; i++)
2945 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2946 i, GNUNET_h2s (&key_material[i]));
2951 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2952 salt, sizeof (salt),
2953 &key_material, sizeof (key_material), NULL);
2956 if (GNUNET_YES == am_I_alice)
2962 ax->ratchet_flag = GNUNET_YES;
2970 ax->ratchet_flag = GNUNET_NO;
2971 ax->ratchet_allowed = GNUNET_NO;
2972 ax->ratchet_counter = 0;
2973 ax->ratchet_expiration =
2974 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2976 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2981 * Demultiplex by message type and call appropriate handler for a message
2982 * towards a channel of a local tunnel.
2984 * @param t Tunnel this message came on.
2985 * @param msgh Message header.
2986 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2987 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2988 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2989 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2992 handle_decrypted (struct CadetTunnel *t,
2993 const struct GNUNET_MessageHeader *msgh,
2998 type = ntohs (msgh->type);
2999 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
3003 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3004 /* Do nothing, connection aleady got updated. */
3005 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3008 case GNUNET_MESSAGE_TYPE_CADET_DATA:
3009 /* Don't send hop ACK, wait for client to ACK */
3010 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3013 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3014 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3017 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3018 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3021 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3022 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3025 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3026 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3029 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3030 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3034 GNUNET_break_op (0);
3035 LOG (GNUNET_ERROR_TYPE_WARNING,
3036 "end-to-end message not known (%u)\n",
3037 ntohs (msgh->type));
3038 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3042 /******************************************************************************/
3043 /******************************** API ***********************************/
3044 /******************************************************************************/
3046 * Decrypt old format and demultiplex by message type. Call appropriate handler
3047 * for a message towards a channel of a local tunnel.
3049 * @param t Tunnel this message came on.
3050 * @param msg Message header.
3053 GCT_handle_encrypted (struct CadetTunnel *t,
3054 const struct GNUNET_MessageHeader *msg)
3056 uint16_t size = ntohs (msg->size);
3058 size_t payload_size;
3061 const struct GNUNET_MessageHeader *msgh;
3064 type = ntohs (msg->type);
3067 case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3069 const struct GNUNET_CADET_Encrypted *emsg;
3071 emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3072 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3073 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3074 emsg->iv, &emsg->hmac);
3077 case GNUNET_MESSAGE_TYPE_CADET_AX:
3079 const struct GNUNET_CADET_AX *emsg;
3081 emsg = (const struct GNUNET_CADET_AX *) msg;
3082 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3086 GNUNET_break_op (0);
3089 if (-1 == decrypted_size)
3091 GNUNET_break_op (0);
3092 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto on tunnel %s\n", GCT_2s (t));
3093 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3097 /* FIXME: this is bad, as the structs returned from
3098 this loop may be unaligned, see util's MST for
3099 how to do this right. */
3101 while (off < decrypted_size)
3105 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3106 msize = ntohs (msgh->size);
3107 if (msize < sizeof (struct GNUNET_MessageHeader))
3109 GNUNET_break_op (0);
3112 handle_decrypted (t, msgh, GNUNET_SYSERR);
3119 * Demultiplex an encapsulated KX message by message type.
3121 * @param t Tunnel on which the message came.
3122 * @param message Payload of KX message.
3125 GCT_handle_kx (struct CadetTunnel *t,
3126 const struct GNUNET_MessageHeader *message)
3130 type = ntohs (message->type);
3131 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3134 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3135 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3138 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3139 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3142 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3143 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3147 GNUNET_break_op (0);
3148 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3153 * Initialize the tunnel subsystem.
3155 * @param c Configuration handle.
3156 * @param key ECC private key, to derive all other keys and do crypto.
3159 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3160 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3162 int expected_overhead;
3164 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3166 expected_overhead = 0;
3167 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3168 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3169 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3170 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3173 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3176 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3177 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3181 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3184 rekey_period = GNUNET_TIME_UNIT_DAYS;
3187 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3190 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3191 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3192 ratchet_messages = 64;
3195 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3198 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3199 "CADET", "RATCHET_TIME", "USING DEFAULT");
3200 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3206 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3207 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3208 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3209 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3210 otr_kx_msg.origin_identity = my_full_id;
3211 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3212 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3217 * Shut down the tunnel subsystem.
3222 if (NULL != rekey_task)
3224 GNUNET_SCHEDULER_cancel (rekey_task);
3227 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3228 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3235 * @param destination Peer this tunnel is towards.
3237 struct CadetTunnel *
3238 GCT_new (struct CadetPeer *destination)
3240 struct CadetTunnel *t;
3242 t = GNUNET_new (struct CadetTunnel);
3244 t->peer = destination;
3247 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3248 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3254 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3256 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3262 * Change the tunnel's connection state.
3264 * @param t Tunnel whose connection state to change.
3265 * @param cstate New connection state.
3268 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3272 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3273 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3274 if (myid != GCP_get_short_id (t->peer) &&
3275 CADET_TUNNEL_READY != t->cstate &&
3276 CADET_TUNNEL_READY == cstate)
3279 if (CADET_TUNNEL_KEY_OK == t->estate)
3281 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3282 send_queued_data (t);
3284 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3286 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3287 GCT_send_ax_kx (t, GNUNET_NO);
3291 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3296 if (CADET_TUNNEL_READY == cstate
3297 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3299 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3300 GCP_stop_search (t->peer);
3306 * Change the tunnel encryption state.
3308 * @param t Tunnel whose encryption state to change, or NULL.
3309 * @param state New encryption state.
3312 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3314 enum CadetTunnelEState old;
3321 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3322 GCP_2s (t->peer), estate2s (old));
3323 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3324 GCP_2s (t->peer), estate2s (t->estate));
3326 /* Send queued data if enc state changes to OK */
3327 if (myid != GCP_get_short_id (t->peer) &&
3328 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3330 send_queued_data (t);
3336 * @brief Check if tunnel has too many connections, and remove one if necessary.
3338 * Currently this means the newest connection, unless it is a direct one.
3339 * Implemented as a task to avoid freeing a connection that is in the middle
3340 * of being created/processed.
3342 * @param cls Closure (Tunnel to check).
3343 * @param tc Task context.
3346 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3348 struct CadetTunnel *t = cls;
3350 t->trim_connections_task = NULL;
3352 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3355 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3357 struct CadetTConnection *iter;
3358 struct CadetTConnection *c;
3360 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3362 if ((iter->created.abs_value_us > c->created.abs_value_us)
3363 && GNUNET_NO == GCC_is_direct (iter->c))
3370 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3372 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3385 * Add a connection to a tunnel.
3388 * @param c Connection.
3391 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3393 struct CadetTConnection *aux;
3395 GNUNET_assert (NULL != c);
3397 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3398 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3399 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3403 aux = GNUNET_new (struct CadetTConnection);
3405 aux->created = GNUNET_TIME_absolute_get ();
3407 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3409 if (CADET_TUNNEL_SEARCHING == t->cstate)
3410 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3412 if (NULL != t->trim_connections_task)
3413 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3418 * Remove a connection from a tunnel.
3421 * @param c Connection.
3424 GCT_remove_connection (struct CadetTunnel *t,
3425 struct CadetConnection *c)
3427 struct CadetTConnection *aux;
3428 struct CadetTConnection *next;
3431 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3432 GCC_2s (c), GCT_2s (t));
3433 for (aux = t->connection_head; aux != NULL; aux = next)
3438 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3443 conns = GCT_count_connections (t);
3445 && NULL == t->destroy_task
3446 && CADET_TUNNEL_SHUTDOWN != t->cstate
3447 && GNUNET_NO == shutting_down)
3449 if (0 == GCT_count_any_connections (t))
3450 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3452 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3455 /* Start new connections if needed */
3456 if (CONNECTIONS_PER_TUNNEL > conns
3457 && NULL == t->destroy_task
3458 && CADET_TUNNEL_SHUTDOWN != t->cstate
3459 && GNUNET_NO == shutting_down)
3461 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3462 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3466 /* If not marked as ready, no change is needed */
3467 if (CADET_TUNNEL_READY != t->cstate)
3470 /* Check if any connection is ready to maintain cstate */
3471 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3472 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3478 * Add a channel to a tunnel.
3481 * @param ch Channel.
3484 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3486 struct CadetTChannel *aux;
3488 GNUNET_assert (NULL != ch);
3490 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3492 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3494 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3499 aux = GNUNET_new (struct CadetTChannel);
3501 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3502 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3504 if (NULL != t->destroy_task)
3506 GNUNET_SCHEDULER_cancel (t->destroy_task);
3507 t->destroy_task = NULL;
3508 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3514 * Remove a channel from a tunnel.
3517 * @param ch Channel.
3520 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3522 struct CadetTChannel *aux;
3524 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3525 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3529 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3530 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3539 * Search for a channel by global ID.
3541 * @param t Tunnel containing the channel.
3542 * @param chid Public channel number.
3544 * @return channel handler, NULL if doesn't exist
3546 struct CadetChannel *
3547 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3549 struct CadetTChannel *iter;
3554 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3556 if (GCCH_get_id (iter->ch) == chid)
3560 return NULL == iter ? NULL : iter->ch;
3565 * @brief Destroy a tunnel and free all resources.
3567 * Should only be called a while after the tunnel has been marked as destroyed,
3568 * in case there is a new channel added to the same peer shortly after marking
3569 * the tunnel. This way we avoid a new public key handshake.
3571 * @param cls Closure (tunnel to destroy).
3572 * @param tc Task context.
3575 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3577 struct CadetTunnel *t = cls;
3578 struct CadetTConnection *iter;
3580 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3581 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3583 LOG (GNUNET_ERROR_TYPE_WARNING,
3584 "Not destroying tunnel, due to shutdown. "
3585 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3588 t->destroy_task = NULL;
3589 t->cstate = CADET_TUNNEL_SHUTDOWN;
3591 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3593 GCC_send_destroy (iter->c);
3600 * Tunnel is empty: destroy it.
3602 * Notifies all connections about the destruction.
3604 * @param t Tunnel to destroy.
3607 GCT_destroy_empty (struct CadetTunnel *t)
3609 if (GNUNET_YES == shutting_down)
3610 return; /* Will be destroyed immediately anyway */
3612 if (NULL != t->destroy_task)
3614 LOG (GNUNET_ERROR_TYPE_WARNING,
3615 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3617 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3619 /* should never happen, tunnel can only become empty once, and the
3620 * task identifier should be NO_TASK (cleaned when the tunnel was created
3621 * or became un-empty)
3626 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3629 // FIXME make delay a config option
3630 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3631 &delayed_destroy, t);
3632 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3633 t, t->destroy_task);
3638 * Destroy tunnel if empty (no more channels).
3640 * @param t Tunnel to destroy if empty.
3643 GCT_destroy_if_empty (struct CadetTunnel *t)
3645 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3646 if (0 < GCT_count_channels (t))
3649 GCT_destroy_empty (t);
3654 * Destroy the tunnel.
3656 * This function does not generate any warning traffic to clients or peers.
3659 * Cancel messages belonging to this tunnel queued to neighbors.
3660 * Free any allocated resources linked to the tunnel.
3662 * @param t The tunnel to destroy.
3665 GCT_destroy (struct CadetTunnel *t)
3667 struct CadetTConnection *iter_c;
3668 struct CadetTConnection *next_c;
3669 struct CadetTChannel *iter_ch;
3670 struct CadetTChannel *next_ch;
3675 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3677 GNUNET_break (GNUNET_YES ==
3678 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3679 GCP_get_id (t->peer), t));
3681 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3683 next_c = iter_c->next;
3684 GCC_destroy (iter_c->c);
3686 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3688 next_ch = iter_ch->next;
3689 GCCH_destroy (iter_ch->ch);
3690 /* Should only happen on shutdown, but it's ok. */
3692 while (NULL != t->tq_head)
3694 /* Should have been cleaned by destuction of channel. */
3696 unqueue_data (t->tq_head);
3700 if (NULL != t->destroy_task)
3702 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3703 GNUNET_SCHEDULER_cancel (t->destroy_task);
3704 t->destroy_task = NULL;
3707 if (NULL != t->trim_connections_task)
3709 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3710 t->trim_connections_task);
3711 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3712 t->trim_connections_task = NULL;
3715 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3716 GCP_set_tunnel (t->peer, NULL);
3718 if (NULL != t->rekey_task)
3720 GNUNET_SCHEDULER_cancel (t->rekey_task);
3721 t->rekey_task = NULL;
3723 if (NULL != t->kx_ctx)
3725 if (NULL != t->kx_ctx->finish_task)
3726 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3727 GNUNET_free (t->kx_ctx);
3738 * @brief Use the given path for the tunnel.
3739 * Update the next and prev hops (and RCs).
3740 * (Re)start the path refresh in case the tunnel is locally owned.
3742 * @param t Tunnel to update.
3743 * @param p Path to use.
3745 * @return Connection created.
3747 struct CadetConnection *
3748 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3750 struct CadetConnection *c;
3751 struct GNUNET_CADET_Hash cid;
3752 unsigned int own_pos;
3754 if (NULL == t || NULL == p)
3760 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3766 for (own_pos = 0; own_pos < p->length; own_pos++)
3768 if (p->peers[own_pos] == myid)
3771 if (own_pos >= p->length)
3773 GNUNET_break_op (0);
3777 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3778 c = GCC_new (&cid, t, p, own_pos);
3781 /* Path was flawed */
3784 GCT_add_connection (t, c);
3790 * Count all created connections of a tunnel. Not necessarily ready connections!
3792 * @param t Tunnel on which to count.
3794 * @return Number of connections created, either being established or ready.
3797 GCT_count_any_connections (struct CadetTunnel *t)
3799 struct CadetTConnection *iter;
3805 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3813 * Count established (ready) connections of a tunnel.
3815 * @param t Tunnel on which to count.
3817 * @return Number of connections.
3820 GCT_count_connections (struct CadetTunnel *t)
3822 struct CadetTConnection *iter;
3828 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3829 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3837 * Count channels of a tunnel.
3839 * @param t Tunnel on which to count.
3841 * @return Number of channels.
3844 GCT_count_channels (struct CadetTunnel *t)
3846 struct CadetTChannel *iter;
3849 for (count = 0, iter = t->channel_head;
3851 iter = iter->next, count++) /* skip */;
3858 * Get the connectivity state of a tunnel.
3862 * @return Tunnel's connectivity state.
3864 enum CadetTunnelCState
3865 GCT_get_cstate (struct CadetTunnel *t)
3870 return (enum CadetTunnelCState) -1;
3877 * Get the encryption state of a tunnel.
3881 * @return Tunnel's encryption state.
3883 enum CadetTunnelEState
3884 GCT_get_estate (struct CadetTunnel *t)
3889 return (enum CadetTunnelEState) -1;
3895 * Get the maximum buffer space for a tunnel towards a local client.
3899 * @return Biggest buffer space offered by any channel in the tunnel.
3902 GCT_get_channels_buffer (struct CadetTunnel *t)
3904 struct CadetTChannel *iter;
3905 unsigned int buffer;
3906 unsigned int ch_buf;
3908 if (NULL == t->channel_head)
3910 /* Probably getting buffer for a channel create/handshake. */
3911 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3912 return MIN_TUNNEL_BUFFER;
3916 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3918 ch_buf = get_channel_buffer (iter);
3919 if (ch_buf > buffer)
3922 if (MIN_TUNNEL_BUFFER > buffer)
3923 return MIN_TUNNEL_BUFFER;
3925 if (MAX_TUNNEL_BUFFER < buffer)
3928 return MAX_TUNNEL_BUFFER;
3935 * Get the total buffer space for a tunnel for P2P traffic.
3939 * @return Buffer space offered by all connections in the tunnel.
3942 GCT_get_connections_buffer (struct CadetTunnel *t)
3944 struct CadetTConnection *iter;
3945 unsigned int buffer;
3947 if (GNUNET_NO == is_ready (t))
3949 if (count_queued_data (t) >= 3)
3956 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3958 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3962 buffer += get_connection_buffer (iter);
3970 * Get the tunnel's destination.
3974 * @return ID of the destination peer.
3976 const struct GNUNET_PeerIdentity *
3977 GCT_get_destination (struct CadetTunnel *t)
3979 return GCP_get_id (t->peer);
3984 * Get the tunnel's next free global channel ID.
3988 * @return GID of a channel free to use.
3991 GCT_get_next_chid (struct CadetTunnel *t)
3993 CADET_ChannelNumber chid;
3994 CADET_ChannelNumber mask;
3997 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3998 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3999 * If peer's ID is bigger, start at 0x4... bit 30 = 1
4001 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4006 t->next_chid |= mask;
4008 while (NULL != GCT_get_channel (t, t->next_chid))
4010 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4011 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4012 t->next_chid |= mask;
4014 chid = t->next_chid;
4015 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4016 t->next_chid |= mask;
4023 * Send ACK on one or more channels due to buffer in connections.
4025 * @param t Channel which has some free buffer space.
4028 GCT_unchoke_channels (struct CadetTunnel *t)
4030 struct CadetTChannel *iter;
4031 unsigned int buffer;
4032 unsigned int channels = GCT_count_channels (t);
4033 unsigned int choked_n;
4034 struct CadetChannel *choked[channels];
4036 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4037 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4038 if (NULL != t->channel_head)
4039 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4041 if (NULL != t->tq_head)
4042 send_queued_data (t);
4044 /* Get buffer space */
4045 buffer = GCT_get_connections_buffer (t);
4051 /* Count and remember choked channels */
4053 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4055 if (GNUNET_NO == get_channel_allowed (iter))
4057 choked[choked_n++] = iter->ch;
4061 /* Unchoke random channels */
4062 while (0 < buffer && 0 < choked_n)
4064 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4066 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4069 choked[r] = choked[choked_n];
4075 * Send ACK on one or more connections due to buffer space to the client.
4077 * Iterates all connections of the tunnel and sends ACKs appropriately.
4082 GCT_send_connection_acks (struct CadetTunnel *t)
4084 struct CadetTConnection *iter;
4087 uint32_t allow_per_connection;
4089 unsigned int buffer;
4091 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4100 if (CADET_TUNNEL_READY != t->cstate)
4103 buffer = GCT_get_channels_buffer (t);
4104 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4106 /* Count connections, how many messages are already allowed */
4107 cs = GCT_count_connections (t);
4108 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4110 allowed += get_connection_allowed (iter);
4112 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4114 /* Make sure there is no overflow */
4115 if (allowed > buffer)
4118 /* Authorize connections to send more data */
4119 to_allow = buffer - allowed;
4121 for (iter = t->connection_head;
4122 NULL != iter && to_allow > 0;
4125 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4126 || get_connection_allowed (iter) > 64 / 3)
4130 allow_per_connection = to_allow/cs;
4131 to_allow -= allow_per_connection;
4133 GCC_allow (iter->c, allow_per_connection,
4134 GCC_is_origin (iter->c, GNUNET_NO));
4139 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4140 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4146 * Cancel a previously sent message while it's in the queue.
4148 * ONLY can be called before the continuation given to the send function
4149 * is called. Once the continuation is called, the message is no longer in the
4152 * @param q Handle to the queue.
4155 GCT_cancel (struct CadetTunnelQueue *q)
4159 GNUNET_assert (NULL == q->tqd);
4161 /* tun_message_sent() will be called and free q */
4163 else if (NULL != q->tqd)
4165 unqueue_data (q->tqd);
4167 if (NULL != q->cont)
4168 q->cont (q->cont_cls, NULL, q, 0, 0);
4179 * Sends an already built message on a tunnel, encrypting it and
4180 * choosing the best connection if not provided.
4182 * @param message Message to send. Function modifies it.
4183 * @param t Tunnel on which this message is transmitted.
4184 * @param c Connection to use (autoselect if NULL).
4185 * @param force Force the tunnel to take the message (buffer overfill).
4186 * @param cont Continuation to call once message is really sent.
4187 * @param cont_cls Closure for @c cont.
4189 * @return Handle to cancel message. NULL if @c cont is NULL.
4191 struct CadetTunnelQueue *
4192 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4193 struct CadetTunnel *t, struct CadetConnection *c,
4194 int force, GCT_sent cont, void *cont_cls)
4196 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4201 * Send an Axolotl KX message.
4203 * @param t Tunnel on which to send it.
4204 * @param force_reply Force the other peer to reply with a KX message.
4207 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4209 struct GNUNET_CADET_AX_KX msg;
4210 enum GNUNET_CADET_AX_KX_Flags flags;
4212 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4213 if (NULL != t->ephm_h)
4215 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4219 msg.header.size = htons (sizeof (msg));
4220 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4221 flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4223 flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4224 msg.flags = htonl (flags);
4225 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4226 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4228 t->ephm_h = send_kx (t, &msg.header);
4229 if (CADET_TUNNEL_KEY_OK != t->estate)
4230 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4235 * Sends an already built and encrypted message on a tunnel, choosing the best
4236 * connection. Useful for re-queueing messages queued on a destroyed connection.
4238 * @param message Message to send. Function modifies it.
4239 * @param t Tunnel on which this message is transmitted.
4242 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4243 struct CadetTunnel *t)
4245 struct CadetConnection *c;
4248 c = tunnel_get_connection (t);
4251 /* TODO queue in tunnel, marked as encrypted */
4252 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4255 fwd = GCC_is_origin (c, GNUNET_YES);
4256 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4257 GNUNET_YES, NULL, NULL));
4262 * Is the tunnel directed towards the local peer?
4266 * @return #GNUNET_YES if it is loopback.
4269 GCT_is_loopback (const struct CadetTunnel *t)
4271 return (myid == GCP_get_short_id (t->peer));
4276 * Is the tunnel this path already?
4281 * @return #GNUNET_YES a connection uses this path.
4284 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4286 struct CadetTConnection *iter;
4288 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4289 if (path_equivalent (GCC_get_path (iter->c), p))
4297 * Get a cost of a path for a tunnel considering existing connections.
4300 * @param path Candidate path.
4302 * @return Cost of the path (path length + number of overlapping nodes)
4305 GCT_get_path_cost (const struct CadetTunnel *t,
4306 const struct CadetPeerPath *path)
4308 struct CadetTConnection *iter;
4309 const struct CadetPeerPath *aux;
4310 unsigned int overlap;
4318 GNUNET_assert (NULL != t);
4320 for (i = 0; i < path->length; i++)
4322 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4324 aux = GCC_get_path (iter->c);
4328 for (j = 0; j < aux->length; j++)
4330 if (path->peers[i] == aux->peers[j])
4338 return path->length + overlap;
4343 * Get the static string for the peer this tunnel is directed.
4347 * @return Static string the destination peer's ID.
4350 GCT_2s (const struct CadetTunnel *t)
4355 return GCP_2s (t->peer);
4359 /******************************************************************************/
4360 /***************************** INFO/DEBUG *******************************/
4361 /******************************************************************************/
4364 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4366 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4367 struct CadetTunnelSkippedKey *iter;
4370 LOG2 (level, "TTT RK \t %s\n",
4371 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4373 LOG2 (level, "TTT HKs \t %s\n",
4374 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4375 LOG2 (level, "TTT HKr \t %s\n",
4376 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4377 LOG2 (level, "TTT NHKs\t %s\n",
4378 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4379 LOG2 (level, "TTT NHKr\t %s\n",
4380 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4382 LOG2 (level, "TTT CKs \t %s\n",
4383 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4384 LOG2 (level, "TTT CKr \t %s\n",
4385 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4387 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4388 LOG2 (level, "TTT DHRs\t %s\n",
4389 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4390 LOG2 (level, "TTT DHRr\t %s\n",
4391 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4393 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4394 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4395 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4397 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4399 LOG2 (level, "TTT HK\t %s\n",
4400 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4401 LOG2 (level, "TTT MK\t %s\n",
4402 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4407 * Log all possible info about the tunnel state.
4409 * @param t Tunnel to debug.
4410 * @param level Debug level to use.
4413 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4415 struct CadetTChannel *iterch;
4416 struct CadetTConnection *iterc;
4419 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4421 __FILE__, __FUNCTION__, __LINE__);
4425 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4426 LOG2 (level, "TTT cstate %s, estate %s\n",
4427 cstate2s (t->cstate), estate2s (t->estate));
4428 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4429 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4430 #if DUMP_KEYS_TO_STDERR
4431 if (CADET_Axolotl == t->enc_type)
4433 ax_debug (t->ax, level);
4437 LOG2 (level, "TTT my EPHM\t %s\n",
4438 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4439 LOG2 (level, "TTT peers EPHM:\t %s\n",
4440 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4441 LOG2 (level, "TTT ENC key:\t %s\n",
4442 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4443 LOG2 (level, "TTT DEC key:\t %s\n",
4444 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4447 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4448 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4449 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4450 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4454 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4455 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4457 LOG2 (level, "TTT channels:\n");
4458 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4460 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4463 LOG2 (level, "TTT connections:\n");
4464 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4466 GCC_debug (iterc->c, level);
4469 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4474 * Iterate all tunnels.
4476 * @param iter Iterator.
4477 * @param cls Closure for @c iter.
4480 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4482 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4487 * Count all tunnels.
4489 * @return Number of tunnels to remote peers kept by this peer.
4492 GCT_count_all (void)
4494 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4499 * Iterate all connections of a tunnel.
4501 * @param t Tunnel whose connections to iterate.
4502 * @param iter Iterator.
4503 * @param cls Closure for @c iter.
4506 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4508 struct CadetTConnection *ct;
4510 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4516 * Iterate all channels of a tunnel.
4518 * @param t Tunnel whose channels to iterate.
4519 * @param iter Iterator.
4520 * @param cls Closure for @c iter.
4523 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4525 struct CadetTChannel *cht;
4527 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4528 iter (cls, cht->ch);