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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, 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)
630 conn_ok = CADET_TUNNEL_READY == t->cstate;
631 enc_ok = CADET_TUNNEL_KEY_OK == t->estate
632 || CADET_TUNNEL_KEY_REKEY == t->estate
633 || (CADET_TUNNEL_KEY_PING == t->estate
634 && CADET_Axolotl == t->enc_type);
635 ready = conn_ok && enc_ok;
636 ready = ready || GCT_is_loopback (t);
642 * Check if a key is invalid (NULL pointer or all 0)
644 * @param key Key to check.
646 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
649 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
651 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
656 memset (&null_key, 0, sizeof (null_key));
657 if (0 == memcmp (key, &null_key, sizeof (null_key)))
664 * Ephemeral key message purpose size.
666 * @return Size of the part of the ephemeral key message that must be signed.
669 ephemeral_purpose_size (void)
671 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
672 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
673 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
674 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
675 sizeof (struct GNUNET_PeerIdentity);
680 * Size of the encrypted part of a ping message.
682 * @return Size of the encrypted part of a ping message.
685 ping_encryption_size (void)
687 return sizeof (uint32_t);
692 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
694 * @param tch Tunnel's channel handle.
696 * @return Amount of messages the channel can still buffer towards the client.
699 get_channel_buffer (const struct CadetTChannel *tch)
703 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
704 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
706 return GCCH_get_buffer (tch->ch, fwd);
711 * Get the channel's allowance status.
713 * @param tch Tunnel's channel handle.
715 * @return #GNUNET_YES if we allowed the client to send data to us.
718 get_channel_allowed (const struct CadetTChannel *tch)
722 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
723 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
725 return GCCH_get_allowed (tch->ch, fwd);
730 * Get the connection's buffer.
732 * @param tc Tunnel's connection handle.
734 * @return Amount of messages the connection can still buffer.
737 get_connection_buffer (const struct CadetTConnection *tc)
741 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
742 fwd = GCC_is_origin (tc->c, GNUNET_YES);
744 return GCC_get_buffer (tc->c, fwd);
749 * Get the connection's allowance.
751 * @param tc Tunnel's connection handle.
753 * @return Amount of messages we have allowed the next peer to send us.
756 get_connection_allowed (const struct CadetTConnection *tc)
760 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
761 fwd = GCC_is_origin (tc->c, GNUNET_YES);
763 return GCC_get_allowed (tc->c, fwd);
768 * Check that a ephemeral key message s well formed and correctly signed.
770 * @param t Tunnel on which the message came.
771 * @param msg The ephemeral key message.
773 * @return #GNUNET_OK if message is fine, #GNUNET_SYSERR otherwise.
776 check_ephemeral (struct CadetTunnel *t,
777 const struct GNUNET_CADET_KX_Ephemeral *msg)
779 /* Check message size */
780 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
782 /* This is probably an old "MESH" version. */
783 LOG (GNUNET_ERROR_TYPE_INFO,
784 "Expected ephemeral of size %u, got %u\n",
785 sizeof (struct GNUNET_CADET_KX_Ephemeral),
786 ntohs (msg->header.size));
787 return GNUNET_SYSERR;
790 /* Check signature size */
791 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
793 LOG (GNUNET_ERROR_TYPE_WARNING,
794 "Expected signature purpose of size %u, got %u\n",
795 ephemeral_purpose_size (),
796 ntohs (msg->purpose.size));
797 return GNUNET_SYSERR;
801 if (0 != memcmp (&msg->origin_identity,
802 GCP_get_id (t->peer),
803 sizeof (struct GNUNET_PeerIdentity)))
805 LOG (GNUNET_ERROR_TYPE_WARNING,
806 "Unexpected origin, got %s\n",
807 GNUNET_i2s (&msg->origin_identity));
808 return GNUNET_SYSERR;
811 /* Check signature */
813 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
816 &msg->origin_identity.public_key))
818 LOG (GNUNET_ERROR_TYPE_WARNING, "Signature invalid\n");
819 return GNUNET_SYSERR;
827 * Select the best key to use for encryption (send), based on KX status.
829 * Normally, return the current key. If there is a KX in progress and the old
830 * key is fresh enough, return the old key.
832 * @param t Tunnel to choose the key from.
834 * @return The optimal key to encrypt/hmac outgoing traffic.
836 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
837 select_key (const struct CadetTunnel *t)
839 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
841 if (NULL != t->kx_ctx
842 && NULL == t->kx_ctx->finish_task)
844 struct GNUNET_TIME_Relative age;
846 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
847 LOG (GNUNET_ERROR_TYPE_DEBUG,
848 " key exchange in progress, started %s ago\n",
849 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
850 // FIXME make duration of old keys configurable
851 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
853 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
854 key = &t->kx_ctx->e_key_old;
858 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
864 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
872 * Create a new Axolotl ephemeral (ratchet) key.
877 new_ephemeral (struct CadetTunnel *t)
879 GNUNET_free_non_null (t->ax->DHRs);
880 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
887 * @param plaintext Content to HMAC.
888 * @param size Size of @c plaintext.
889 * @param iv Initialization vector for the message.
890 * @param key Key to use.
891 * @param hmac[out] Destination to store the HMAC.
894 t_hmac (const void *plaintext, size_t size,
895 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
896 struct GNUNET_CADET_Hash *hmac)
898 static const char ctx[] = "cadet authentication key";
899 struct GNUNET_CRYPTO_AuthKey auth_key;
900 struct GNUNET_HashCode hash;
902 #if DUMP_KEYS_TO_STDERR
903 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
904 GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
906 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
911 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
912 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
913 memcpy (hmac, &hash, sizeof (*hmac));
918 * Encrypt daforce_newest_keyta with the tunnel key.
920 * @param t Tunnel whose key to use.
921 * @param dst Destination for the encrypted data.
922 * @param src Source of the plaintext. Can overlap with @c dst.
923 * @param size Size of the plaintext.
924 * @param iv Initialization Vector to use.
925 * @param force_newest_key Force the use of the newest key, otherwise
926 * CADET will use the old key when allowed.
927 * This can happen in the case when a KX is going on
928 * and the old one hasn't expired.
931 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
932 size_t size, uint32_t iv, int force_newest_key)
934 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
935 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
938 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
940 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
941 #if DUMP_KEYS_TO_STDERR
942 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
943 GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
945 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
946 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
947 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
948 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
957 * @param key Key to use.
958 * @param hash[out] Resulting HMAC.
959 * @param source Source key material (data to HMAC).
960 * @param len Length of @a source.
963 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
964 struct GNUNET_HashCode *hash,
965 void *source, unsigned int len)
967 static const char ctx[] = "axolotl HMAC-HASH";
968 struct GNUNET_CRYPTO_AuthKey auth_key;
970 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
973 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
978 * Derive a key from a HMAC-HASH.
980 * @param key Key to use for the HMAC.
981 * @param out Key to generate.
982 * @param source Source key material (data to HMAC).
983 * @param len Length of @a source.
986 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
987 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
988 void *source, unsigned int len)
990 static const char ctx[] = "axolotl derive key";
991 struct GNUNET_HashCode h;
993 t_ax_hmac_hash (key, &h, source, len);
994 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
995 &h, sizeof (h), NULL);
1000 * Encrypt data with the axolotl tunnel key.
1002 * @param t Tunnel whose key to use.
1003 * @param dst Destination for the encrypted data.
1004 * @param src Source of the plaintext. Can overlap with @c dst.
1005 * @param size Size of the plaintext.
1007 * @return Size of the encrypted data.
1010 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1012 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1013 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1014 struct CadetTunnelAxolotl *ax;
1017 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
1021 ax->ratchet_counter++;
1022 if (GNUNET_YES == ax->ratchet_allowed
1023 && (ratchet_messages <= ax->ratchet_counter
1024 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
1026 ax->ratchet_flag = GNUNET_YES;
1029 if (GNUNET_YES == ax->ratchet_flag)
1031 /* Advance ratchet */
1032 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1033 struct GNUNET_HashCode dh;
1034 struct GNUNET_HashCode hmac;
1035 static const char ctx[] = "axolotl ratchet";
1040 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1041 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1042 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1043 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1044 &hmac, sizeof (hmac), NULL);
1051 ax->ratchet_flag = GNUNET_NO;
1052 ax->ratchet_allowed = GNUNET_NO;
1053 ax->ratchet_counter = 0;
1054 ax->ratchet_expiration =
1055 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1058 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1059 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1061 #if DUMP_KEYS_TO_STDERR
1062 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1063 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
1064 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1065 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
1068 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1070 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1072 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1079 * Decrypt data with the axolotl tunnel key.
1081 * @param t Tunnel whose key to use.
1082 * @param dst Destination for the decrypted data.
1083 * @param src Source of the ciphertext. Can overlap with @c dst.
1084 * @param size Size of the ciphertext.
1086 * @return Size of the decrypted data.
1089 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1091 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1092 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1093 struct CadetTunnelAxolotl *ax;
1096 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1100 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1101 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1103 #if DUMP_KEYS_TO_STDERR
1104 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1105 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
1106 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1107 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
1110 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1111 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1112 GNUNET_assert (out_size == size);
1114 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1116 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1123 * Encrypt header with the axolotl header key.
1125 * @param t Tunnel whose key to use.
1126 * @param msg Message whose header to encrypt.
1129 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1131 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1132 struct CadetTunnelAxolotl *ax;
1135 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1138 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1140 #if DUMP_KEYS_TO_STDERR
1141 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1142 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
1145 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1146 &ax->HKs, &iv, &msg->Ns);
1148 GNUNET_assert (AX_HEADER_SIZE == out_size);
1150 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1155 * Decrypt header with the current axolotl header key.
1157 * @param t Tunnel whose current ax HK to use.
1158 * @param src Message whose header to decrypt.
1159 * @param dst Where to decrypt header to.
1162 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1163 struct GNUNET_CADET_AX *dst)
1165 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1166 struct CadetTunnelAxolotl *ax;
1169 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1172 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1174 #if DUMP_KEYS_TO_STDERR
1175 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1176 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
1179 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1180 &ax->HKr, &iv, &dst->Ns);
1182 GNUNET_assert (AX_HEADER_SIZE == out_size);
1184 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1189 * Decrypt and verify data with the appropriate tunnel key.
1191 * @param key Key to use.
1192 * @param dst Destination for the plaintext.
1193 * @param src Source of the encrypted data. Can overlap with @c dst.
1194 * @param size Size of the encrypted data.
1195 * @param iv Initialization Vector to use.
1197 * @return Size of the decrypted data, -1 if an error was encountered.
1200 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1201 void *dst, const void *src, size_t size, uint32_t iv)
1203 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1206 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1207 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1208 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1209 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1210 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1211 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1218 * Decrypt and verify data with the most recent tunnel key.
1220 * @param t Tunnel whose key to use.
1221 * @param dst Destination for the plaintext.
1222 * @param src Source of the encrypted data. Can overlap with @c dst.
1223 * @param size Size of the encrypted data.
1224 * @param iv Initialization Vector to use.
1226 * @return Size of the decrypted data, -1 if an error was encountered.
1229 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1230 size_t size, uint32_t iv)
1234 #if DUMP_KEYS_TO_STDERR
1235 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1236 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
1238 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1240 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1241 LOG (GNUNET_ERROR_TYPE_WARNING,
1242 "got data on %s without a valid key\n",
1244 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1248 out_size = decrypt (&t->d_key, dst, src, size, iv);
1255 * Decrypt and verify data with the appropriate tunnel key and verify that the
1256 * data has not been altered since it was sent by the remote peer.
1258 * @param t Tunnel whose key to use.
1259 * @param dst Destination for the plaintext.
1260 * @param src Source of the encrypted data. Can overlap with @c dst.
1261 * @param size Size of the encrypted data.
1262 * @param iv Initialization Vector to use.
1263 * @param msg_hmac HMAC of the message, cannot be NULL.
1265 * @return Size of the decrypted data, -1 if an error was encountered.
1268 t_decrypt_and_validate (struct CadetTunnel *t,
1269 void *dst, const void *src,
1270 size_t size, uint32_t iv,
1271 const struct GNUNET_CADET_Hash *msg_hmac)
1273 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1274 struct GNUNET_CADET_Hash hmac;
1277 /* Try primary (newest) key */
1279 decrypted_size = decrypt (key, dst, src, size, iv);
1280 t_hmac (src, size, iv, key, &hmac);
1281 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1282 return decrypted_size;
1284 /* If no key exchange is going on, we just failed. */
1285 if (NULL == t->kx_ctx)
1287 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1288 "Failed checksum validation on tunnel %s with no KX\n",
1290 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1294 /* Try secondary key, from previous KX period. */
1295 key = &t->kx_ctx->d_key_old;
1296 decrypted_size = decrypt (key, dst, src, size, iv);
1297 t_hmac (src, size, iv, key, &hmac);
1298 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1299 return decrypted_size;
1301 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1302 key = &t->kx_ctx->d_key_old2;
1303 decrypted_size = decrypt (key, dst, src, size, iv);
1304 t_hmac (src, size, iv, key, &hmac);
1305 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1306 return decrypted_size;
1308 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1309 "Failed checksum validation on tunnel %s with KX\n",
1311 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1317 * Decrypt and verify data with the appropriate tunnel key and verify that the
1318 * data has not been altered since it was sent by the remote peer.
1320 * @param t Tunnel whose key to use.
1321 * @param dst Destination for the plaintext.
1322 * @param src Source of the message. Can overlap with @c dst.
1323 * @param size Size of the message.
1325 * @return Size of the decrypted data, -1 if an error was encountered.
1328 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1329 const struct GNUNET_CADET_AX *src, size_t size)
1331 struct CadetTunnelSkippedKey *key;
1332 struct GNUNET_CADET_Hash hmac;
1333 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1338 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1340 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1341 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1347 #if DUMP_KEYS_TO_STDERR
1348 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1349 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1352 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1353 len = size - sizeof (struct GNUNET_CADET_AX);
1354 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1355 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1357 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1366 * Delete a key from the list of skipped keys.
1368 * @param t Tunnel to delete from.
1369 * @param HKr Header Key to use.
1372 store_skipped_key (struct CadetTunnel *t,
1373 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1375 struct CadetTunnelSkippedKey *key;
1377 key = GNUNET_new (struct CadetTunnelSkippedKey);
1378 key->timestamp = GNUNET_TIME_absolute_get ();
1379 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1380 #if DUMP_KEYS_TO_STDERR
1381 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1382 t->ax->Nr, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1383 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1384 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->ax->CKr));
1386 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1387 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1394 * Delete a key from the list of skipped keys.
1396 * @param t Tunnel to delete from.
1397 * @param key Key to delete.
1400 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1402 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1409 * Stage skipped AX keys and calculate the message key.
1411 * Stores each HK and MK for skipped messages.
1413 * @param t Tunnel where to stage the keys.
1414 * @param HKr Header key.
1415 * @param Np Received meesage number.
1418 store_ax_keys (struct CadetTunnel *t,
1419 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1424 gap = Np - t->ax->Nr;
1425 if (MAX_KEY_GAP < gap || 0 > gap)
1427 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1428 /* TODO: start new key exchange on return */
1429 GNUNET_break_op (0);
1430 LOG (GNUNET_ERROR_TYPE_WARNING, "Got message %u, expected %u+\n",
1435 while (t->ax->Nr < Np)
1436 store_skipped_key (t, HKr);
1438 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1439 delete_skipped_key (t, t->ax->skipped_tail);
1444 * Decrypt and verify data with the appropriate tunnel key and verify that the
1445 * data has not been altered since it was sent by the remote peer.
1447 * @param t Tunnel whose key to use.
1448 * @param dst Destination for the plaintext.
1449 * @param src Source of the message. Can overlap with @c dst.
1450 * @param size Size of the message.
1452 * @return Size of the decrypted data, -1 if an error was encountered.
1455 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1456 const struct GNUNET_CADET_AX *src, size_t size)
1458 struct CadetTunnelAxolotl *ax;
1459 struct GNUNET_CADET_Hash msg_hmac;
1460 struct GNUNET_HashCode hmac;
1461 struct GNUNET_CADET_AX *dstmsg;
1469 esize = size - sizeof (struct GNUNET_CADET_AX);
1474 /* Try current HK */
1475 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1476 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1478 static const char ctx[] = "axolotl ratchet";
1479 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1480 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1481 struct GNUNET_HashCode dh;
1482 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1485 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1486 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1488 /* Try the skipped keys, if that fails, we're out of luck. */
1489 return try_old_ax_keys (t, dst, src, size);
1491 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1495 t_h_decrypt (t, src, dstmsg);
1496 Np = ntohl (dstmsg->Ns);
1497 PNp = ntohl (dstmsg->PNs);
1498 DHRp = &dstmsg->DHRs;
1499 store_ax_keys (t, &HK, PNp);
1501 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1502 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1503 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1504 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1505 &hmac, sizeof (hmac), NULL);
1507 /* Commit "purported" keys */
1513 ax->ratchet_allowed = GNUNET_YES;
1517 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1518 t_h_decrypt (t, src, dstmsg);
1519 Np = ntohl (dstmsg->Ns);
1520 PNp = ntohl (dstmsg->PNs);
1524 store_ax_keys (t, &ax->HKr, Np);
1528 osize = t_ax_decrypt (t, dst, &src[1], esize);
1531 GNUNET_break_op (0);
1540 * Create key material by doing ECDH on the local and remote ephemeral keys.
1542 * @param key_material Where to store the key material.
1543 * @param ephemeral Peer's public ephemeral key.
1545 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1548 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1549 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1552 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1555 return GNUNET_SYSERR;
1562 * Create a symmetic key from the identities of both ends and the key material
1565 * @param key Destination for the generated key.
1566 * @param sender ID of the peer that will encrypt with @c key.
1567 * @param receiver ID of the peer that will decrypt with @c key.
1568 * @param key_material Hash created with ECDH with the ephemeral keys.
1571 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1572 const struct GNUNET_PeerIdentity *sender,
1573 const struct GNUNET_PeerIdentity *receiver,
1574 const struct GNUNET_HashCode *key_material)
1576 const char salt[] = "CADET kx salt";
1578 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1579 salt, sizeof (salt),
1580 key_material, sizeof (struct GNUNET_HashCode),
1581 sender, sizeof (struct GNUNET_PeerIdentity),
1582 receiver, sizeof (struct GNUNET_PeerIdentity),
1588 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1590 * @param t Tunnel for which to create the keys.
1592 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1595 create_otr_keys (struct CadetTunnel *t)
1597 struct GNUNET_HashCode km;
1599 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1600 return GNUNET_SYSERR;
1601 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1602 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1603 #if DUMP_KEYS_TO_STDERR
1604 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1605 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
1606 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1607 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
1608 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1609 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1610 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
1611 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1612 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
1619 * Create a new Key eXchange context for the tunnel.
1621 * If the old keys were verified, keep them for old traffic. Create a new KX
1622 * timestamp and a new nonce.
1624 * @param t Tunnel for which to create the KX ctx.
1626 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1629 create_kx_ctx (struct CadetTunnel *t)
1631 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1633 if (NULL != t->kx_ctx)
1635 if (NULL != t->kx_ctx->finish_task)
1637 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1638 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1639 t->kx_ctx->finish_task = NULL;
1644 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1645 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1649 if (CADET_TUNNEL_KEY_OK == t->estate)
1651 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1652 t->kx_ctx->d_key_old = t->d_key;
1653 t->kx_ctx->e_key_old = t->e_key;
1656 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1657 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1658 return create_otr_keys (t);
1663 * @brief Finish the Key eXchange and destroy the old keys.
1665 * @param cls Closure (Tunnel for which to finish the KX).
1666 * @param tc Task context.
1669 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1671 struct CadetTunnel *t = cls;
1673 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1675 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1677 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1681 GNUNET_free (t->kx_ctx);
1687 * Destroy a Key eXchange context for the tunnel. This function only schedules
1688 * the destruction, the freeing of the memory (and clearing of old key material)
1689 * happens after a delay!
1691 * @param t Tunnel whose KX ctx to destroy.
1694 destroy_kx_ctx (struct CadetTunnel *t)
1696 struct GNUNET_TIME_Relative delay;
1698 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1701 if (is_key_null (&t->kx_ctx->e_key_old))
1703 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1707 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1708 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1710 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1716 * Pick a connection on which send the next data message.
1718 * @param t Tunnel on which to send the message.
1720 * @return The connection on which to send the next message.
1722 static struct CadetConnection *
1723 tunnel_get_connection (struct CadetTunnel *t)
1725 struct CadetTConnection *iter;
1726 struct CadetConnection *best;
1728 unsigned int lowest_q;
1730 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1732 lowest_q = UINT_MAX;
1733 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1735 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1736 GCC_2s (iter->c), GCC_get_state (iter->c));
1737 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1739 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1740 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1748 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1754 * Callback called when a queued message is sent.
1756 * Calculates the average time and connection packet tracking.
1758 * @param cls Closure (TunnelQueue handle).
1759 * @param c Connection this message was on.
1760 * @param q Connection queue handle (unused).
1761 * @param type Type of message sent.
1762 * @param fwd Was this a FWD going message?
1763 * @param size Size of the message.
1766 tun_message_sent (void *cls,
1767 struct CadetConnection *c,
1768 struct CadetConnectionQueue *q,
1769 uint16_t type, int fwd, size_t size)
1771 struct CadetTunnelQueue *qt = cls;
1772 struct CadetTunnel *t;
1774 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1776 GNUNET_assert (NULL != qt->cont);
1777 t = NULL == c ? NULL : GCC_get_tunnel (c);
1778 qt->cont (qt->cont_cls, t, qt, type, size);
1784 count_queued_data (const struct CadetTunnel *t)
1786 struct CadetTunnelDelayed *iter;
1789 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1796 * Delete a queued message: either was sent or the channel was destroyed
1797 * before the tunnel's key exchange had a chance to finish.
1799 * @param tqd Delayed queue handle.
1802 unqueue_data (struct CadetTunnelDelayed *tqd)
1804 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1810 * Cache a message to be sent once tunnel is online.
1812 * @param t Tunnel to hold the message.
1813 * @param msg Message itself (copy will be made).
1815 static struct CadetTunnelDelayed *
1816 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1818 struct CadetTunnelDelayed *tqd;
1819 uint16_t size = ntohs (msg->size);
1821 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1823 GNUNET_assert (GNUNET_NO == is_ready (t));
1825 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1828 memcpy (&tqd[1], msg, size);
1829 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1835 * Sends an already built message on a tunnel, encrypting it and
1836 * choosing the best connection.
1838 * @param message Message to send. Function modifies it.
1839 * @param t Tunnel on which this message is transmitted.
1840 * @param c Connection to use (autoselect if NULL).
1841 * @param force Force the tunnel to take the message (buffer overfill).
1842 * @param cont Continuation to call once message is really sent.
1843 * @param cont_cls Closure for @c cont.
1844 * @param existing_q In case this a transmission of previously queued data,
1845 * this should be TunnelQueue given to the client.
1848 * @return Handle to cancel message.
1849 * NULL if @c cont is NULL or an error happens and message is dropped.
1851 static struct CadetTunnelQueue *
1852 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1853 struct CadetTunnel *t, struct CadetConnection *c,
1854 int force, GCT_sent cont, void *cont_cls,
1855 struct CadetTunnelQueue *existing_q)
1857 struct GNUNET_MessageHeader *msg;
1858 struct GNUNET_CADET_Encrypted *otr_msg;
1859 struct GNUNET_CADET_AX *ax_msg;
1860 struct CadetTunnelQueue *tq;
1861 size_t size = ntohs (message->size);
1862 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1863 + sizeof (struct GNUNET_CADET_AX);
1864 char cbuf[max_overhead + size];
1871 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1873 if (GNUNET_NO == is_ready (t))
1875 struct CadetTunnelDelayed *tqd;
1876 /* A non null existing_q indicates sending of queued data.
1877 * Should only happen after tunnel becomes ready.
1879 GNUNET_assert (NULL == existing_q);
1880 tqd = queue_data (t, message);
1883 tq = GNUNET_new (struct CadetTunnelQueue);
1887 tq->cont_cls = cont_cls;
1891 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1893 if (CADET_Axolotl == t->enc_type)
1895 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1896 msg = &ax_msg->header;
1897 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1898 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1899 ax_msg->reserved = 0;
1900 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1901 ax_msg->Ns = htonl (t->ax->Ns++);
1902 ax_msg->PNs = htonl (t->ax->PNs);
1903 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1904 t_h_encrypt (t, ax_msg);
1905 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1909 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1910 msg = &otr_msg->header;
1911 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1913 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1914 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1915 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1916 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1917 otr_msg->ttl = htonl (default_ttl);
1919 GNUNET_assert (esize == size);
1922 c = tunnel_get_connection (t);
1925 /* Why is tunnel 'ready'? Should have been queued! */
1926 if (NULL != t->destroy_task)
1929 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1931 return NULL; /* Drop... */
1935 type = ntohs (message->type);
1938 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1939 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1940 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1941 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1943 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1945 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1946 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1947 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1948 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1949 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1953 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1955 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1957 fwd = GCC_is_origin (c, GNUNET_YES);
1961 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1962 mid, c, fwd, force, NULL, NULL));
1965 if (NULL == existing_q)
1967 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1974 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1975 &tun_message_sent, tq);
1976 GNUNET_assert (NULL != tq->cq);
1978 tq->cont_cls = cont_cls;
1985 * Send all cached messages that we can, tunnel is online.
1987 * @param t Tunnel that holds the messages. Cannot be loopback.
1990 send_queued_data (struct CadetTunnel *t)
1992 struct CadetTunnelDelayed *tqd;
1993 struct CadetTunnelDelayed *next;
1996 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1998 if (GCT_is_loopback (t))
2004 if (GNUNET_NO == is_ready (t))
2006 LOG (GNUNET_ERROR_TYPE_WARNING, " not ready yet: %s/%s\n",
2007 estate2s (t->estate), cstate2s (t->cstate));
2011 room = GCT_get_connections_buffer (t);
2012 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2013 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
2014 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
2016 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
2019 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2020 tqd->t, NULL, GNUNET_YES,
2021 NULL != tqd->tq ? tqd->tq->cont : NULL,
2022 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2026 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2031 * @brief Resend the AX KX until we complete the handshake.
2033 * @param cls Closure (tunnel).
2034 * @param tc Task context.
2037 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2039 struct CadetTunnel *t = cls;
2041 t->rekey_task = NULL;
2043 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2046 if (CADET_TUNNEL_KEY_OK == t->estate)
2048 /* Should have been canceled on estate change */
2053 GCT_send_ax_kx (t, GNUNET_YES);
2058 * Callback called when a queued message is sent.
2060 * @param cls Closure.
2061 * @param c Connection this message was on.
2062 * @param type Type of message sent.
2063 * @param fwd Was this a FWD going message?
2064 * @param size Size of the message.
2067 ephm_sent (void *cls,
2068 struct CadetConnection *c,
2069 struct CadetConnectionQueue *q,
2070 uint16_t type, int fwd, size_t size)
2072 struct CadetTunnel *t = cls;
2073 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2077 if (CADET_TUNNEL_KEY_OK == t->estate)
2080 if (CADET_Axolotl == t->enc_type)
2082 if (NULL != t->rekey_task)
2085 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2086 GNUNET_SCHEDULER_cancel (t->rekey_task);
2088 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2095 * Callback called when a queued message is sent.
2097 * @param cls Closure.
2098 * @param c Connection this message was on.
2099 * @param type Type of message sent.
2100 * @param fwd Was this a FWD going message?
2101 * @param size Size of the message.
2104 pong_sent (void *cls,
2105 struct CadetConnection *c,
2106 struct CadetConnectionQueue *q,
2107 uint16_t type, int fwd, size_t size)
2109 struct CadetTunnel *t = cls;
2110 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2117 * Sends key exchange message on a tunnel, choosing the best connection.
2118 * Should not be called on loopback tunnels.
2120 * @param t Tunnel on which this message is transmitted.
2121 * @param message Message to send. Function modifies it.
2123 * @return Handle to the message in the connection queue.
2125 static struct CadetConnectionQueue *
2126 send_kx (struct CadetTunnel *t,
2127 const struct GNUNET_MessageHeader *message)
2129 struct CadetConnection *c;
2130 struct GNUNET_CADET_KX *msg;
2131 size_t size = ntohs (message->size);
2132 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2137 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2139 /* Avoid loopback. */
2140 if (GCT_is_loopback (t))
2145 type = ntohs (message->type);
2147 /* Even if tunnel is "being destroyed", send anyway.
2148 * Could be a response to a rekey initiated by remote peer,
2149 * who is trying to create a new channel!
2152 /* Must have a connection, or be looking for one. */
2153 if (NULL == t->connection_head)
2155 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2156 if (CADET_TUNNEL_SEARCHING != t->cstate)
2159 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2160 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2165 msg = (struct GNUNET_CADET_KX *) cbuf;
2166 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2167 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2168 c = tunnel_get_connection (t);
2171 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2174 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2180 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2181 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2182 GNUNET_assert (NULL == t->ephm_h);
2185 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2186 GNUNET_assert (NULL == t->pong_h);
2191 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2194 memcpy (&msg[1], message, size);
2196 fwd = GCC_is_origin (c, GNUNET_YES);
2198 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2205 * Send the ephemeral key on a tunnel.
2207 * @param t Tunnel on which to send the key.
2210 send_ephemeral (struct CadetTunnel *t)
2212 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2213 if (NULL != t->ephm_h)
2215 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2219 otr_kx_msg.sender_status = htonl (t->estate);
2220 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2221 otr_kx_msg.nonce = t->kx_ctx->challenge;
2222 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2223 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2224 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2225 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2226 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2231 * Send a pong message on a tunnel.
2233 * @param t Tunnel on which to send the pong.
2234 * @param challenge Value sent in the ping that we have to send back.
2237 send_pong (struct CadetTunnel *t, uint32_t challenge)
2239 struct GNUNET_CADET_KX_Pong msg;
2241 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2242 if (NULL != t->pong_h)
2244 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2247 msg.header.size = htons (sizeof (msg));
2248 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2249 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2250 msg.nonce = challenge;
2251 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2252 t_encrypt (t, &msg.nonce, &msg.nonce,
2253 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2254 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2256 t->pong_h = send_kx (t, &msg.header);
2261 * Initiate a rekey with the remote peer.
2263 * @param cls Closure (tunnel).
2264 * @param tc TaskContext.
2267 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2269 struct CadetTunnel *t = cls;
2271 t->rekey_task = NULL;
2273 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2274 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2277 GNUNET_assert (NULL != t->kx_ctx);
2278 struct GNUNET_TIME_Relative duration;
2280 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2281 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2282 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2284 // FIXME make duration of old keys configurable
2285 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2287 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2288 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2289 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2296 case CADET_TUNNEL_KEY_UNINITIALIZED:
2297 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2300 case CADET_TUNNEL_KEY_SENT:
2303 case CADET_TUNNEL_KEY_OK:
2305 * - state should have changed during rekey_iterator
2306 * - task should have been canceled at pong_handle
2309 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2312 case CADET_TUNNEL_KEY_PING:
2313 case CADET_TUNNEL_KEY_REKEY:
2317 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2320 // FIXME exponential backoff
2321 struct GNUNET_TIME_Relative delay;
2323 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2324 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2325 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2326 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2327 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2332 * Our ephemeral key has changed, create new session key on all tunnels.
2334 * Each tunnel will start the Key Exchange with a random delay between
2335 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2336 * per second, on average.
2338 * @param cls Closure (size of the hashmap).
2339 * @param key Current public key.
2340 * @param value Value in the hash map (tunnel).
2342 * @return #GNUNET_YES, so we should continue to iterate,
2345 rekey_iterator (void *cls,
2346 const struct GNUNET_PeerIdentity *key,
2349 struct CadetTunnel *t = value;
2350 struct GNUNET_TIME_Relative delay;
2351 long n = (long) cls;
2354 if (NULL != t->rekey_task)
2357 if (GNUNET_YES == GCT_is_loopback (t))
2360 if (CADET_OTR != t->enc_type)
2363 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2364 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2365 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2366 if (GNUNET_OK == create_kx_ctx (t))
2367 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2379 * Create a new ephemeral key and key message, schedule next rekeying.
2381 * @param cls Closure (unused).
2382 * @param tc TaskContext.
2385 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2387 struct GNUNET_TIME_Absolute time;
2392 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2395 GNUNET_free_non_null (otr_ephemeral_key);
2396 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2398 time = GNUNET_TIME_absolute_get ();
2399 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2400 time = GNUNET_TIME_absolute_add (time, rekey_period);
2401 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2402 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2403 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2404 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2405 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
2407 GNUNET_assert (GNUNET_OK ==
2408 GNUNET_CRYPTO_eddsa_sign (id_key,
2409 &otr_kx_msg.purpose,
2410 &otr_kx_msg.signature));
2412 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2413 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2415 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2416 &global_otr_rekey, NULL);
2421 * Called only on shutdown, destroy every tunnel.
2423 * @param cls Closure (unused).
2424 * @param key Current public key.
2425 * @param value Value in the hash map (tunnel).
2427 * @return #GNUNET_YES, so we should continue to iterate,
2430 destroy_iterator (void *cls,
2431 const struct GNUNET_PeerIdentity *key,
2434 struct CadetTunnel *t = value;
2436 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2443 * Notify remote peer that we don't know a channel he is talking about,
2444 * probably CHANNEL_DESTROY was missed.
2446 * @param t Tunnel on which to notify.
2447 * @param gid ID of the channel.
2450 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2452 struct GNUNET_CADET_ChannelManage msg;
2454 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2455 msg.header.size = htons (sizeof (msg));
2456 msg.chid = htonl (gid);
2458 LOG (GNUNET_ERROR_TYPE_DEBUG,
2459 "WARNING destroying unknown channel %u on tunnel %s\n",
2461 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2466 * Demultiplex data per channel and call appropriate channel handler.
2468 * @param t Tunnel on which the data came.
2469 * @param msg Data message.
2470 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2471 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2472 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2473 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2476 handle_data (struct CadetTunnel *t,
2477 const struct GNUNET_CADET_Data *msg,
2480 struct CadetChannel *ch;
2486 size = ntohs (msg->header.size);
2488 sizeof (struct GNUNET_CADET_Data) +
2489 sizeof (struct GNUNET_MessageHeader))
2494 type = ntohs (msg[1].header.type);
2495 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n", GC_m2s (type));
2496 sprintf (buf, "# received payload of type %hu", type);
2497 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
2501 ch = GCT_get_channel (t, ntohl (msg->chid));
2504 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2506 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2508 send_channel_destroy (t, ntohl (msg->chid));
2512 GCCH_handle_data (ch, msg, fwd);
2517 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2519 * @param t Tunnel on which the DATA ACK came.
2520 * @param msg DATA ACK message.
2521 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2522 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2523 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2524 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2527 handle_data_ack (struct CadetTunnel *t,
2528 const struct GNUNET_CADET_DataACK *msg,
2531 struct CadetChannel *ch;
2535 size = ntohs (msg->header.size);
2536 if (size != sizeof (struct GNUNET_CADET_DataACK))
2543 ch = GCT_get_channel (t, ntohl (msg->chid));
2546 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2548 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2553 GCCH_handle_data_ack (ch, msg, fwd);
2558 * Handle channel create.
2560 * @param t Tunnel on which the data came.
2561 * @param msg Data message.
2564 handle_ch_create (struct CadetTunnel *t,
2565 const struct GNUNET_CADET_ChannelCreate *msg)
2567 struct CadetChannel *ch;
2571 size = ntohs (msg->header.size);
2572 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2579 ch = GCT_get_channel (t, ntohl (msg->chid));
2580 if (NULL != ch && ! GCT_is_loopback (t))
2582 /* Probably a retransmission, safe to ignore */
2583 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2585 ch = GCCH_handle_create (t, msg);
2587 GCT_add_channel (t, ch);
2593 * Handle channel NACK: check correctness and call channel handler for NACKs.
2595 * @param t Tunnel on which the NACK came.
2596 * @param msg NACK message.
2599 handle_ch_nack (struct CadetTunnel *t,
2600 const struct GNUNET_CADET_ChannelManage *msg)
2602 struct CadetChannel *ch;
2606 size = ntohs (msg->header.size);
2607 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2614 ch = GCT_get_channel (t, ntohl (msg->chid));
2617 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2619 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2624 GCCH_handle_nack (ch);
2629 * Handle a CHANNEL ACK (SYNACK/ACK).
2631 * @param t Tunnel on which the CHANNEL ACK came.
2632 * @param msg CHANNEL ACK message.
2633 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2634 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2635 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2636 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2639 handle_ch_ack (struct CadetTunnel *t,
2640 const struct GNUNET_CADET_ChannelManage *msg,
2643 struct CadetChannel *ch;
2647 size = ntohs (msg->header.size);
2648 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2655 ch = GCT_get_channel (t, ntohl (msg->chid));
2658 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2660 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2665 GCCH_handle_ack (ch, msg, fwd);
2670 * Handle a channel destruction message.
2672 * @param t Tunnel on which the message came.
2673 * @param msg Channel destroy message.
2674 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2675 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2676 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2677 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2680 handle_ch_destroy (struct CadetTunnel *t,
2681 const struct GNUNET_CADET_ChannelManage *msg,
2684 struct CadetChannel *ch;
2688 size = ntohs (msg->header.size);
2689 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2696 ch = GCT_get_channel (t, ntohl (msg->chid));
2699 /* Probably a retransmission, safe to ignore */
2703 GCCH_handle_destroy (ch, msg, fwd);
2708 * Free Axolotl data.
2713 destroy_ax (struct CadetTunnel *t)
2718 GNUNET_free_non_null (t->ax->DHRs);
2719 GNUNET_free_non_null (t->ax->kx_0);
2720 while (NULL != t->ax->skipped_head)
2721 delete_skipped_key (t, t->ax->skipped_head);
2722 GNUNET_assert (0 == t->ax->skipped);
2724 GNUNET_free (t->ax);
2727 if (NULL != t->rekey_task)
2729 GNUNET_SCHEDULER_cancel (t->rekey_task);
2730 t->rekey_task = NULL;
2732 if (NULL != t->ephm_h)
2734 GCC_cancel (t->ephm_h);
2741 * The peer's ephemeral key has changed: update the symmetrical keys.
2743 * @param t Tunnel this message came on.
2744 * @param msg Key eXchange message.
2747 handle_ephemeral (struct CadetTunnel *t,
2748 const struct GNUNET_CADET_KX_Ephemeral *msg)
2750 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2752 /* Some old versions are still around, don't log as error. */
2753 if (GNUNET_OK != check_ephemeral (t, msg))
2756 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2760 t->enc_type = CADET_OTR;
2761 if (NULL != t->rekey_task)
2762 GNUNET_SCHEDULER_cancel (t->rekey_task);
2763 if (GNUNET_OK != create_kx_ctx (t))
2769 rekey_tunnel (t, NULL);
2770 GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2774 * If the key is different from what we know, derive the new E/D keys.
2775 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2777 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2778 sizeof (msg->ephemeral_key)))
2780 #if DUMP_KEYS_TO_STDERR
2781 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2782 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
2783 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2784 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &msg->ephemeral_key));
2786 t->peers_ephemeral_key = msg->ephemeral_key;
2788 if (GNUNET_OK != create_kx_ctx (t))
2795 if (CADET_TUNNEL_KEY_OK == t->estate)
2797 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2799 if (NULL != t->rekey_task)
2800 GNUNET_SCHEDULER_cancel (t->rekey_task);
2801 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2803 if (CADET_TUNNEL_KEY_SENT == t->estate)
2805 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2807 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2810 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2814 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2815 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2816 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2817 send_pong (t, nonce);
2823 * Peer has answer to our challenge.
2824 * If answer is successful, consider the key exchange finished and clean
2825 * up all related state.
2827 * @param t Tunnel this message came on.
2828 * @param msg Key eXchange Pong message.
2831 handle_pong (struct CadetTunnel *t,
2832 const struct GNUNET_CADET_KX_Pong *msg)
2836 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2837 if (NULL == t->rekey_task)
2839 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2842 if (NULL == t->kx_ctx)
2844 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2848 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2849 if (challenge != t->kx_ctx->challenge)
2851 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2852 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2853 challenge, msg->nonce, t->kx_ctx->challenge);
2857 GNUNET_SCHEDULER_cancel (t->rekey_task);
2858 t->rekey_task = NULL;
2860 /* Don't free the old keys right away, but after a delay.
2861 * Rationale: the KX could have happened over a very fast connection,
2862 * with payload traffic still signed with the old key stuck in a slower
2864 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2868 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2873 * Handle Axolotl handshake.
2875 * @param t Tunnel this message came on.
2876 * @param msg Key eXchange Pong message.
2879 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2881 struct CadetTunnelAxolotl *ax;
2882 struct GNUNET_HashCode key_material[3];
2883 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2884 const char salt[] = "CADET Axolotl salt";
2885 const struct GNUNET_PeerIdentity *pid;
2888 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2892 /* Something is wrong if ax is NULL. Whose fault it is? */
2893 GNUNET_break_op (CADET_OTR == t->enc_type);
2894 GNUNET_break (CADET_Axolotl == t->enc_type);
2899 pid = GCT_get_destination (t);
2900 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2901 am_I_alice = GNUNET_YES;
2902 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2903 am_I_alice = GNUNET_NO;
2906 GNUNET_break_op (0);
2910 if (0 != (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2912 if (NULL != t->rekey_task)
2914 GNUNET_SCHEDULER_cancel (t->rekey_task);
2915 t->rekey_task = NULL;
2917 GCT_send_ax_kx (t, GNUNET_NO);
2920 if (0 == memcmp (&ax->DHRr, &msg->ratchet_key, sizeof(msg->ratchet_key)))
2922 LOG (GNUNET_ERROR_TYPE_INFO, " known ratchet key, exit\n");
2926 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2928 ax->DHRr = msg->ratchet_key;
2931 if (GNUNET_YES == am_I_alice)
2933 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2934 &msg->ephemeral_key, /* B0 */
2939 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
2940 &pid->public_key, /* A */
2945 if (GNUNET_YES == am_I_alice)
2947 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
2948 &pid->public_key, /* B */
2953 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
2954 &msg->ephemeral_key, /* B0 */
2961 /* (This is the triple-DH, we could probably safely skip this,
2962 as A0/B0 are already in the key material.) */
2963 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
2964 &msg->ephemeral_key, /* B0 or A0 */
2967 #if DUMP_KEYS_TO_STDERR
2970 for (i = 0; i < 3; i++)
2971 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2972 i, GNUNET_h2s (&key_material[i]));
2977 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2978 salt, sizeof (salt),
2979 &key_material, sizeof (key_material), NULL);
2982 if (GNUNET_YES == am_I_alice)
2988 ax->ratchet_flag = GNUNET_YES;
2996 ax->ratchet_flag = GNUNET_NO;
2997 ax->ratchet_allowed = GNUNET_NO;
2998 ax->ratchet_counter = 0;
2999 ax->ratchet_expiration =
3000 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
3005 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
3006 send_queued_data (t);
3011 * Demultiplex by message type and call appropriate handler for a message
3012 * towards a channel of a local tunnel.
3014 * @param t Tunnel this message came on.
3015 * @param msgh Message header.
3016 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
3017 * #GNUNET_YES if message is FWD on the respective channel (loopback)
3018 * #GNUNET_NO if message is BCK on the respective channel (loopback)
3019 * #GNUNET_SYSERR if message on a one-ended channel (remote)
3022 handle_decrypted (struct CadetTunnel *t,
3023 const struct GNUNET_MessageHeader *msgh,
3029 type = ntohs (msgh->type);
3030 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
3031 sprintf (buf, "# received encrypted of type %hu (%s)", type, GC_m2s (type));
3032 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
3037 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3038 /* Do nothing, connection aleady got updated. */
3039 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3042 case GNUNET_MESSAGE_TYPE_CADET_DATA:
3043 /* Don't send hop ACK, wait for client to ACK */
3044 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3047 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3048 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3051 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3052 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3055 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3056 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3059 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3060 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3063 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3064 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3068 GNUNET_break_op (0);
3069 LOG (GNUNET_ERROR_TYPE_WARNING,
3070 "end-to-end message not known (%u)\n",
3071 ntohs (msgh->type));
3072 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3077 /******************************************************************************/
3078 /******************************** API ***********************************/
3079 /******************************************************************************/
3081 * Decrypt old format and demultiplex by message type. Call appropriate handler
3082 * for a message towards a channel of a local tunnel.
3084 * @param t Tunnel this message came on.
3085 * @param msg Message header.
3088 GCT_handle_encrypted (struct CadetTunnel *t,
3089 const struct GNUNET_MessageHeader *msg)
3091 uint16_t size = ntohs (msg->size);
3095 const struct GNUNET_MessageHeader *msgh;
3098 type = ntohs (msg->type);
3101 case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3103 const struct GNUNET_CADET_Encrypted *emsg;
3104 size_t payload_size;
3106 GNUNET_STATISTICS_update (stats, "# received OTR", 1, GNUNET_NO);
3107 emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3108 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3109 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3110 emsg->iv, &emsg->hmac);
3113 case GNUNET_MESSAGE_TYPE_CADET_AX:
3115 const struct GNUNET_CADET_AX *emsg;
3117 GNUNET_STATISTICS_update (stats, "# received Axolotl", 1, GNUNET_NO);
3118 emsg = (const struct GNUNET_CADET_AX *) msg;
3119 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3123 GNUNET_break_op (0);
3127 if (-1 == decrypted_size)
3129 GNUNET_break_op (0);
3130 GNUNET_STATISTICS_update (stats, "# unable to decrypt", 1, GNUNET_NO);
3131 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto on tunnel %s\n", GCT_2s (t));
3132 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3135 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
3137 /* FIXME: this is bad, as the structs returned from
3138 this loop may be unaligned, see util's MST for
3139 how to do this right. */
3141 while (off + sizeof (struct GNUNET_MessageHeader) < decrypted_size)
3145 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3146 msize = ntohs (msgh->size);
3147 if (msize < sizeof (struct GNUNET_MessageHeader))
3149 GNUNET_break_op (0);
3152 if (off + msize < decrypted_size)
3154 GNUNET_break_op (0);
3157 handle_decrypted (t, msgh, GNUNET_SYSERR);
3164 * Demultiplex an encapsulated KX message by message type.
3166 * @param t Tunnel on which the message came.
3167 * @param message Payload of KX message.
3170 GCT_handle_kx (struct CadetTunnel *t,
3171 const struct GNUNET_MessageHeader *message)
3176 type = ntohs (message->type);
3177 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3178 sprintf (buf, "# received KX of type %hu (%s)", type, GC_m2s (type));
3179 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
3182 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3183 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3186 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3187 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3190 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3191 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3195 GNUNET_break_op (0);
3196 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3201 * Initialize the tunnel subsystem.
3203 * @param c Configuration handle.
3204 * @param key ECC private key, to derive all other keys and do crypto.
3207 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3208 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3210 int expected_overhead;
3212 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3214 expected_overhead = 0;
3215 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3216 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3217 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3218 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3221 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3224 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3225 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3229 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3232 rekey_period = GNUNET_TIME_UNIT_DAYS;
3235 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3238 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3239 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3240 ratchet_messages = 64;
3243 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3246 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3247 "CADET", "RATCHET_TIME", "USING DEFAULT");
3248 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3254 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3255 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3256 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3257 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3258 otr_kx_msg.origin_identity = my_full_id;
3259 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3260 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3265 * Shut down the tunnel subsystem.
3270 if (NULL != rekey_task)
3272 GNUNET_SCHEDULER_cancel (rekey_task);
3275 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3276 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3283 * @param destination Peer this tunnel is towards.
3285 struct CadetTunnel *
3286 GCT_new (struct CadetPeer *destination)
3288 struct CadetTunnel *t;
3290 t = GNUNET_new (struct CadetTunnel);
3292 t->peer = destination;
3295 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3296 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3302 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3304 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3310 * Change the tunnel's connection state.
3312 * @param t Tunnel whose connection state to change.
3313 * @param cstate New connection state.
3316 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3320 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3321 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3322 if (myid != GCP_get_short_id (t->peer) &&
3323 CADET_TUNNEL_READY != t->cstate &&
3324 CADET_TUNNEL_READY == cstate)
3327 if (CADET_TUNNEL_KEY_OK == t->estate)
3329 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3330 send_queued_data (t);
3332 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3334 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3335 GCT_send_ax_kx (t, GNUNET_NO);
3339 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3344 if (CADET_TUNNEL_READY == cstate
3345 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3347 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3348 GCP_stop_search (t->peer);
3354 * Change the tunnel encryption state.
3356 * If the encryption state changes to OK, stop the rekey task.
3358 * @param t Tunnel whose encryption state to change, or NULL.
3359 * @param state New encryption state.
3362 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3364 enum CadetTunnelEState old;
3371 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3372 GCP_2s (t->peer), estate2s (old));
3373 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3374 GCP_2s (t->peer), estate2s (t->estate));
3376 if (CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3378 if (NULL != t->rekey_task)
3380 GNUNET_SCHEDULER_cancel (t->rekey_task);
3381 t->rekey_task = NULL;
3383 /* Send queued data if tunnel is not loopback */
3384 if (myid != GCP_get_short_id (t->peer))
3385 send_queued_data (t);
3391 * @brief Check if tunnel has too many connections, and remove one if necessary.
3393 * Currently this means the newest connection, unless it is a direct one.
3394 * Implemented as a task to avoid freeing a connection that is in the middle
3395 * of being created/processed.
3397 * @param cls Closure (Tunnel to check).
3398 * @param tc Task context.
3401 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3403 struct CadetTunnel *t = cls;
3405 t->trim_connections_task = NULL;
3407 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3410 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3412 struct CadetTConnection *iter;
3413 struct CadetTConnection *c;
3415 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3417 if ((iter->created.abs_value_us > c->created.abs_value_us)
3418 && GNUNET_NO == GCC_is_direct (iter->c))
3425 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3427 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3440 * Add a connection to a tunnel.
3443 * @param c Connection.
3446 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3448 struct CadetTConnection *aux;
3450 GNUNET_assert (NULL != c);
3452 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3453 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3454 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3458 aux = GNUNET_new (struct CadetTConnection);
3460 aux->created = GNUNET_TIME_absolute_get ();
3462 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3464 if (CADET_TUNNEL_SEARCHING == t->cstate)
3465 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3467 if (NULL != t->trim_connections_task)
3468 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3473 * Remove a connection from a tunnel.
3476 * @param c Connection.
3479 GCT_remove_connection (struct CadetTunnel *t,
3480 struct CadetConnection *c)
3482 struct CadetTConnection *aux;
3483 struct CadetTConnection *next;
3486 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3487 GCC_2s (c), GCT_2s (t));
3488 for (aux = t->connection_head; aux != NULL; aux = next)
3493 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3498 conns = GCT_count_connections (t);
3500 && NULL == t->destroy_task
3501 && CADET_TUNNEL_SHUTDOWN != t->cstate
3502 && GNUNET_NO == shutting_down)
3504 if (0 == GCT_count_any_connections (t))
3505 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3507 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3510 /* Start new connections if needed */
3511 if (CONNECTIONS_PER_TUNNEL > conns
3512 && NULL == t->destroy_task
3513 && CADET_TUNNEL_SHUTDOWN != t->cstate
3514 && GNUNET_NO == shutting_down)
3516 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3517 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3521 /* If not marked as ready, no change is needed */
3522 if (CADET_TUNNEL_READY != t->cstate)
3525 /* Check if any connection is ready to maintain cstate */
3526 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3527 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3533 * Add a channel to a tunnel.
3536 * @param ch Channel.
3539 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3541 struct CadetTChannel *aux;
3543 GNUNET_assert (NULL != ch);
3545 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3547 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3549 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3554 aux = GNUNET_new (struct CadetTChannel);
3556 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3557 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3559 if (NULL != t->destroy_task)
3561 GNUNET_SCHEDULER_cancel (t->destroy_task);
3562 t->destroy_task = NULL;
3563 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3569 * Remove a channel from a tunnel.
3572 * @param ch Channel.
3575 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3577 struct CadetTChannel *aux;
3579 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3580 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3584 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3585 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3594 * Search for a channel by global ID.
3596 * @param t Tunnel containing the channel.
3597 * @param chid Public channel number.
3599 * @return channel handler, NULL if doesn't exist
3601 struct CadetChannel *
3602 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3604 struct CadetTChannel *iter;
3609 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3611 if (GCCH_get_id (iter->ch) == chid)
3615 return NULL == iter ? NULL : iter->ch;
3620 * @brief Destroy a tunnel and free all resources.
3622 * Should only be called a while after the tunnel has been marked as destroyed,
3623 * in case there is a new channel added to the same peer shortly after marking
3624 * the tunnel. This way we avoid a new public key handshake.
3626 * @param cls Closure (tunnel to destroy).
3627 * @param tc Task context.
3630 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3632 struct CadetTunnel *t = cls;
3633 struct CadetTConnection *iter;
3635 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3636 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3638 LOG (GNUNET_ERROR_TYPE_WARNING,
3639 "Not destroying tunnel, due to shutdown. "
3640 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3643 t->destroy_task = NULL;
3644 t->cstate = CADET_TUNNEL_SHUTDOWN;
3646 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3648 GCC_send_destroy (iter->c);
3655 * Tunnel is empty: destroy it.
3657 * Notifies all connections about the destruction.
3659 * @param t Tunnel to destroy.
3662 GCT_destroy_empty (struct CadetTunnel *t)
3664 if (GNUNET_YES == shutting_down)
3665 return; /* Will be destroyed immediately anyway */
3667 if (NULL != t->destroy_task)
3669 LOG (GNUNET_ERROR_TYPE_WARNING,
3670 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3672 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3674 /* should never happen, tunnel can only become empty once, and the
3675 * task identifier should be NO_TASK (cleaned when the tunnel was created
3676 * or became un-empty)
3681 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3684 // FIXME make delay a config option
3685 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3686 &delayed_destroy, t);
3687 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %p\n",
3688 t, t->destroy_task);
3693 * Destroy tunnel if empty (no more channels).
3695 * @param t Tunnel to destroy if empty.
3698 GCT_destroy_if_empty (struct CadetTunnel *t)
3700 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3701 if (0 < GCT_count_channels (t))
3704 GCT_destroy_empty (t);
3709 * Destroy the tunnel.
3711 * This function does not generate any warning traffic to clients or peers.
3714 * Cancel messages belonging to this tunnel queued to neighbors.
3715 * Free any allocated resources linked to the tunnel.
3717 * @param t The tunnel to destroy.
3720 GCT_destroy (struct CadetTunnel *t)
3722 struct CadetTConnection *iter_c;
3723 struct CadetTConnection *next_c;
3724 struct CadetTChannel *iter_ch;
3725 struct CadetTChannel *next_ch;
3726 unsigned int keepalives_queued;
3731 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3733 GNUNET_break (GNUNET_YES ==
3734 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3735 GCP_get_id (t->peer), t));
3737 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3739 next_c = iter_c->next;
3740 GCC_destroy (iter_c->c);
3742 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3744 next_ch = iter_ch->next;
3745 GCCH_destroy (iter_ch->ch);
3746 /* Should only happen on shutdown, but it's ok. */
3748 keepalives_queued = 0;
3749 while (NULL != t->tq_head)
3751 /* Should have been cleaned by destuction of channel. */
3752 struct GNUNET_MessageHeader *mh;
3755 mh = (struct GNUNET_MessageHeader *) &t->tq_head[1];
3756 type = ntohs (mh->type);
3757 if (0 == keepalives_queued && GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE == type)
3759 keepalives_queued = 1;
3760 LOG (GNUNET_ERROR_TYPE_DEBUG,
3761 "one keepalive left behind on tunnel shutdown\n");
3763 else if (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY == type)
3765 LOG (GNUNET_ERROR_TYPE_WARNING,
3766 "tunnel destroyed before a CHANNEL_DESTROY was sent to peer\n");
3771 LOG (GNUNET_ERROR_TYPE_ERROR,
3772 "message left behind on tunnel shutdown: %s\n",
3775 unqueue_data (t->tq_head);
3779 if (NULL != t->destroy_task)
3781 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %p\n", t->destroy_task);
3782 GNUNET_SCHEDULER_cancel (t->destroy_task);
3783 t->destroy_task = NULL;
3786 if (NULL != t->trim_connections_task)
3788 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %p\n",
3789 t->trim_connections_task);
3790 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3791 t->trim_connections_task = NULL;
3794 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3795 GCP_set_tunnel (t->peer, NULL);
3797 if (NULL != t->rekey_task)
3799 GNUNET_SCHEDULER_cancel (t->rekey_task);
3800 t->rekey_task = NULL;
3802 if (NULL != t->kx_ctx)
3804 if (NULL != t->kx_ctx->finish_task)
3805 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3806 GNUNET_free (t->kx_ctx);
3817 * @brief Use the given path for the tunnel.
3818 * Update the next and prev hops (and RCs).
3819 * (Re)start the path refresh in case the tunnel is locally owned.
3821 * @param t Tunnel to update.
3822 * @param p Path to use.
3824 * @return Connection created.
3826 struct CadetConnection *
3827 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3829 struct CadetConnection *c;
3830 struct GNUNET_CADET_Hash cid;
3831 unsigned int own_pos;
3833 if (NULL == t || NULL == p)
3839 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3845 for (own_pos = 0; own_pos < p->length; own_pos++)
3847 if (p->peers[own_pos] == myid)
3850 if (own_pos >= p->length)
3852 GNUNET_break_op (0);
3856 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3857 c = GCC_new (&cid, t, p, own_pos);
3860 /* Path was flawed */
3863 GCT_add_connection (t, c);
3869 * Count all created connections of a tunnel. Not necessarily ready connections!
3871 * @param t Tunnel on which to count.
3873 * @return Number of connections created, either being established or ready.
3876 GCT_count_any_connections (struct CadetTunnel *t)
3878 struct CadetTConnection *iter;
3884 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3892 * Count established (ready) connections of a tunnel.
3894 * @param t Tunnel on which to count.
3896 * @return Number of connections.
3899 GCT_count_connections (struct CadetTunnel *t)
3901 struct CadetTConnection *iter;
3907 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3908 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3916 * Count channels of a tunnel.
3918 * @param t Tunnel on which to count.
3920 * @return Number of channels.
3923 GCT_count_channels (struct CadetTunnel *t)
3925 struct CadetTChannel *iter;
3928 for (count = 0, iter = t->channel_head;
3930 iter = iter->next, count++) /* skip */;
3937 * Get the connectivity state of a tunnel.
3941 * @return Tunnel's connectivity state.
3943 enum CadetTunnelCState
3944 GCT_get_cstate (struct CadetTunnel *t)
3949 return (enum CadetTunnelCState) -1;
3956 * Get the encryption state of a tunnel.
3960 * @return Tunnel's encryption state.
3962 enum CadetTunnelEState
3963 GCT_get_estate (struct CadetTunnel *t)
3968 return (enum CadetTunnelEState) -1;
3974 * Get the maximum buffer space for a tunnel towards a local client.
3978 * @return Biggest buffer space offered by any channel in the tunnel.
3981 GCT_get_channels_buffer (struct CadetTunnel *t)
3983 struct CadetTChannel *iter;
3984 unsigned int buffer;
3985 unsigned int ch_buf;
3987 if (NULL == t->channel_head)
3989 /* Probably getting buffer for a channel create/handshake. */
3990 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3991 return MIN_TUNNEL_BUFFER;
3995 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3997 ch_buf = get_channel_buffer (iter);
3998 if (ch_buf > buffer)
4001 if (MIN_TUNNEL_BUFFER > buffer)
4002 return MIN_TUNNEL_BUFFER;
4004 if (MAX_TUNNEL_BUFFER < buffer)
4007 return MAX_TUNNEL_BUFFER;
4014 * Get the total buffer space for a tunnel for P2P traffic.
4018 * @return Buffer space offered by all connections in the tunnel.
4021 GCT_get_connections_buffer (struct CadetTunnel *t)
4023 struct CadetTConnection *iter;
4024 unsigned int buffer;
4026 if (GNUNET_NO == is_ready (t))
4028 if (count_queued_data (t) >= 3)
4035 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4037 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
4041 buffer += get_connection_buffer (iter);
4049 * Get the tunnel's destination.
4053 * @return ID of the destination peer.
4055 const struct GNUNET_PeerIdentity *
4056 GCT_get_destination (struct CadetTunnel *t)
4058 return GCP_get_id (t->peer);
4063 * Get the tunnel's next free global channel ID.
4067 * @return GID of a channel free to use.
4070 GCT_get_next_chid (struct CadetTunnel *t)
4072 CADET_ChannelNumber chid;
4073 CADET_ChannelNumber mask;
4076 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
4077 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
4078 * If peer's ID is bigger, start at 0x4... bit 30 = 1
4080 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4085 t->next_chid |= mask;
4087 while (NULL != GCT_get_channel (t, t->next_chid))
4089 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4090 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4091 t->next_chid |= mask;
4093 chid = t->next_chid;
4094 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4095 t->next_chid |= mask;
4102 * Send ACK on one or more channels due to buffer in connections.
4104 * @param t Channel which has some free buffer space.
4107 GCT_unchoke_channels (struct CadetTunnel *t)
4109 struct CadetTChannel *iter;
4110 unsigned int buffer;
4111 unsigned int channels = GCT_count_channels (t);
4112 unsigned int choked_n;
4113 struct CadetChannel *choked[channels];
4115 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4116 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4117 if (NULL != t->channel_head)
4118 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4120 if (NULL != t->tq_head)
4121 send_queued_data (t);
4123 /* Get buffer space */
4124 buffer = GCT_get_connections_buffer (t);
4130 /* Count and remember choked channels */
4132 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4134 if (GNUNET_NO == get_channel_allowed (iter))
4136 choked[choked_n++] = iter->ch;
4140 /* Unchoke random channels */
4141 while (0 < buffer && 0 < choked_n)
4143 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4145 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4148 choked[r] = choked[choked_n];
4154 * Send ACK on one or more connections due to buffer space to the client.
4156 * Iterates all connections of the tunnel and sends ACKs appropriately.
4161 GCT_send_connection_acks (struct CadetTunnel *t)
4163 struct CadetTConnection *iter;
4166 uint32_t allow_per_connection;
4168 unsigned int buffer;
4170 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4179 if (CADET_TUNNEL_READY != t->cstate)
4182 buffer = GCT_get_channels_buffer (t);
4183 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4185 /* Count connections, how many messages are already allowed */
4186 cs = GCT_count_connections (t);
4187 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4189 allowed += get_connection_allowed (iter);
4191 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4193 /* Make sure there is no overflow */
4194 if (allowed > buffer)
4197 /* Authorize connections to send more data */
4198 to_allow = buffer - allowed;
4200 for (iter = t->connection_head;
4201 NULL != iter && to_allow > 0;
4204 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4205 || get_connection_allowed (iter) > 64 / 3)
4209 allow_per_connection = to_allow/cs;
4210 to_allow -= allow_per_connection;
4212 GCC_allow (iter->c, allow_per_connection,
4213 GCC_is_origin (iter->c, GNUNET_NO));
4218 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4219 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4225 * Cancel a previously sent message while it's in the queue.
4227 * ONLY can be called before the continuation given to the send function
4228 * is called. Once the continuation is called, the message is no longer in the
4231 * @param q Handle to the queue.
4234 GCT_cancel (struct CadetTunnelQueue *q)
4238 GNUNET_assert (NULL == q->tqd);
4240 /* tun_message_sent() will be called and free q */
4242 else if (NULL != q->tqd)
4244 unqueue_data (q->tqd);
4246 if (NULL != q->cont)
4247 q->cont (q->cont_cls, NULL, q, 0, 0);
4258 * Check if the tunnel has queued traffic.
4260 * @param t Tunnel to check.
4262 * @return #GNUNET_YES if there is queued traffic
4263 * #GNUNET_NO otherwise
4266 GCT_has_queued_traffic (struct CadetTunnel *t)
4268 return (NULL != t->tq_head) ? GNUNET_YES : GNUNET_NO;
4273 * Sends an already built message on a tunnel, encrypting it and
4274 * choosing the best connection if not provided.
4276 * @param message Message to send. Function modifies it.
4277 * @param t Tunnel on which this message is transmitted.
4278 * @param c Connection to use (autoselect if NULL).
4279 * @param force Force the tunnel to take the message (buffer overfill).
4280 * @param cont Continuation to call once message is really sent.
4281 * @param cont_cls Closure for @c cont.
4283 * @return Handle to cancel message. NULL if @c cont is NULL.
4285 struct CadetTunnelQueue *
4286 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4287 struct CadetTunnel *t, struct CadetConnection *c,
4288 int force, GCT_sent cont, void *cont_cls)
4290 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4295 * Send an Axolotl KX message.
4297 * @param t Tunnel on which to send it.
4298 * @param force_reply Force the other peer to reply with a KX message.
4301 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4303 struct GNUNET_CADET_AX_KX msg;
4304 enum GNUNET_CADET_AX_KX_Flags flags;
4306 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4307 if (NULL != t->ephm_h)
4309 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4313 msg.header.size = htons (sizeof (msg));
4314 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4315 flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4317 flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4318 msg.flags = htonl (flags);
4319 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4320 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4322 t->ephm_h = send_kx (t, &msg.header);
4323 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
4324 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4329 * Sends an already built and encrypted message on a tunnel, choosing the best
4330 * connection. Useful for re-queueing messages queued on a destroyed connection.
4332 * @param message Message to send. Function modifies it.
4333 * @param t Tunnel on which this message is transmitted.
4336 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4337 struct CadetTunnel *t)
4339 struct CadetConnection *c;
4342 c = tunnel_get_connection (t);
4345 /* TODO queue in tunnel, marked as encrypted */
4346 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4349 fwd = GCC_is_origin (c, GNUNET_YES);
4350 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4351 GNUNET_YES, NULL, NULL));
4356 * Is the tunnel directed towards the local peer?
4360 * @return #GNUNET_YES if it is loopback.
4363 GCT_is_loopback (const struct CadetTunnel *t)
4365 return (myid == GCP_get_short_id (t->peer));
4370 * Is the tunnel this path already?
4375 * @return #GNUNET_YES a connection uses this path.
4378 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4380 struct CadetTConnection *iter;
4382 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4383 if (path_equivalent (GCC_get_path (iter->c), p))
4391 * Get a cost of a path for a tunnel considering existing connections.
4394 * @param path Candidate path.
4396 * @return Cost of the path (path length + number of overlapping nodes)
4399 GCT_get_path_cost (const struct CadetTunnel *t,
4400 const struct CadetPeerPath *path)
4402 struct CadetTConnection *iter;
4403 const struct CadetPeerPath *aux;
4404 unsigned int overlap;
4412 GNUNET_assert (NULL != t);
4414 for (i = 0; i < path->length; i++)
4416 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4418 aux = GCC_get_path (iter->c);
4422 for (j = 0; j < aux->length; j++)
4424 if (path->peers[i] == aux->peers[j])
4432 return path->length + overlap;
4437 * Get the static string for the peer this tunnel is directed.
4441 * @return Static string the destination peer's ID.
4444 GCT_2s (const struct CadetTunnel *t)
4449 return GCP_2s (t->peer);
4453 /******************************************************************************/
4454 /***************************** INFO/DEBUG *******************************/
4455 /******************************************************************************/
4458 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4460 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4461 struct CadetTunnelSkippedKey *iter;
4463 LOG2 (level, "TTT RK \t %s\n",
4464 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
4466 LOG2 (level, "TTT HKs \t %s\n",
4467 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
4468 LOG2 (level, "TTT HKr \t %s\n",
4469 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
4470 LOG2 (level, "TTT NHKs\t %s\n",
4471 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
4472 LOG2 (level, "TTT NHKr\t %s\n",
4473 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
4475 LOG2 (level, "TTT CKs \t %s\n",
4476 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
4477 LOG2 (level, "TTT CKr \t %s\n",
4478 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
4480 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4481 LOG2 (level, "TTT DHRs\t %s\n",
4482 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
4483 LOG2 (level, "TTT DHRr\t %s\n",
4484 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
4486 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4487 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4488 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4490 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4492 LOG2 (level, "TTT HK\t %s\n",
4493 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
4494 LOG2 (level, "TTT MK\t %s\n",
4495 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
4500 * Log all possible info about the tunnel state.
4502 * @param t Tunnel to debug.
4503 * @param level Debug level to use.
4506 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4508 struct CadetTChannel *iterch;
4509 struct CadetTConnection *iterc;
4512 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4514 __FILE__, __FUNCTION__, __LINE__);
4518 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4519 LOG2 (level, "TTT cstate %s, estate %s\n",
4520 cstate2s (t->cstate), estate2s (t->estate));
4521 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4522 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4523 #if DUMP_KEYS_TO_STDERR
4524 if (CADET_Axolotl == t->enc_type)
4526 ax_debug (t->ax, level);
4530 LOG2 (level, "TTT my EPHM\t %s\n",
4531 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
4532 LOG2 (level, "TTT peers EPHM:\t %s\n",
4533 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
4534 LOG2 (level, "TTT ENC key:\t %s\n",
4535 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
4536 LOG2 (level, "TTT DEC key:\t %s\n",
4537 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
4540 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4541 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->e_key_old));
4542 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4543 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->d_key_old));
4547 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4548 LOG2 (level, "TTT destroy %p\n", t->destroy_task);
4550 LOG2 (level, "TTT channels:\n");
4551 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4553 GCCH_debug (iterch->ch, level);
4556 LOG2 (level, "TTT connections:\n");
4557 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4559 GCC_debug (iterc->c, level);
4562 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4567 * Iterate all tunnels.
4569 * @param iter Iterator.
4570 * @param cls Closure for @c iter.
4573 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4575 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4580 * Count all tunnels.
4582 * @return Number of tunnels to remote peers kept by this peer.
4585 GCT_count_all (void)
4587 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4592 * Iterate all connections of a tunnel.
4594 * @param t Tunnel whose connections to iterate.
4595 * @param iter Iterator.
4596 * @param cls Closure for @c iter.
4599 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4601 struct CadetTConnection *ct;
4603 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4609 * Iterate all channels of a tunnel.
4611 * @param t Tunnel whose channels to iterate.
4612 * @param iter Iterator.
4613 * @param cls Closure for @c iter.
4616 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4618 struct CadetTChannel *cht;
4620 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4621 iter (cls, cht->ch);