2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 #define MAX_SKIPPED_KEYS 64
47 #define MAX_KEY_GAP 256
48 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
49 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
52 /******************************************************************************/
53 /******************************** STRUCTS **********************************/
54 /******************************************************************************/
58 struct CadetTChannel *next;
59 struct CadetTChannel *prev;
60 struct CadetChannel *ch;
65 * Connection list and metadata.
67 struct CadetTConnection
72 struct CadetTConnection *next;
77 struct CadetTConnection *prev;
82 struct CadetConnection *c;
85 * Creation time, to keep oldest connection alive.
87 struct GNUNET_TIME_Absolute created;
90 * Connection throughput, to keep fastest connection alive.
96 * Structure used during a Key eXchange.
98 struct CadetTunnelKXCtx
101 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
102 * end before the key exchange is finished or times out.
104 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
107 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
108 * the other end before the key exchange started.
110 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
113 * Same as @c e_key_old, for the case of two simultaneous KX.
114 * This can happen if cadet decides to start a re-key while the peer has also
115 * started its re-key (due to network delay this is impossible to avoid).
116 * In this case, the key material generated with the peer's old ephemeral
117 * *might* (but doesn't have to) be incorrect.
118 * Since no more than two re-keys can happen simultaneously, this is enough.
120 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
123 * Same as @c d_key_old, for the case described in @c e_key_old2.
125 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
128 * Challenge to send and expect in the PONG.
133 * When the rekey started. One minute after this the new key will be used.
135 struct GNUNET_TIME_Absolute rekey_start_time;
138 * Task for delayed destruction of the Key eXchange context, to allow delayed
139 * messages with the old key to be decrypted successfully.
141 struct GNUNET_SCHEDULER_Task *finish_task;
145 * Encryption systems possible.
147 enum CadetTunnelEncryption
150 * Default Axolotl system.
155 * Fallback OTR-style encryption.
161 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
163 struct CadetTunnelSkippedKey
168 struct CadetTunnelSkippedKey *next;
173 struct CadetTunnelSkippedKey *prev;
176 * When was this key stored (for timeout).
178 struct GNUNET_TIME_Absolute timestamp;
183 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
188 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
193 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
195 struct CadetTunnelAxolotl
198 * A (double linked) list of stored message keys and associated header keys
199 * for "skipped" messages, i.e. messages that have not been
200 * received despite the reception of more recent messages, (head).
202 struct CadetTunnelSkippedKey *skipped_head;
205 * Skipped messages' keys DLL, tail.
207 struct CadetTunnelSkippedKey *skipped_tail;
210 * Elements in @a skipped_head <-> @a skipped_tail.
212 unsigned int skipped;
215 * 32-byte root key which gets updated by DH ratchet.
217 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
220 * 32-byte header key (send).
222 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
225 * 32-byte header key (recv)
227 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
230 * 32-byte next header key (send).
232 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
235 * 32-byte next header key (recv).
237 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
240 * 32-byte chain keys (used for forward-secrecy updating, send).
242 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
245 * 32-byte chain keys (used for forward-secrecy updating, recv).
247 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
250 * ECDH for key exchange (A0 / B0).
252 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
255 * ECDH Identity key (recv).
257 struct GNUNET_CRYPTO_EcdhePublicKey DHIr;
260 * ECDH Ratchet key (send).
262 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
265 * ECDH Ratchet key (recv).
267 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
270 * Message number (reset to 0 with each new ratchet, next message to send).
275 * Message number (reset to 0 with each new ratchet, next message to recv).
280 * Previous message numbers (# of msgs sent under prev ratchet)
285 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
290 * Number of messages recieved since our last ratchet advance.
291 * - If this counter = 0, we cannot send a new ratchet key in next msg.
292 * - If this counter > 0, we can (but don't yet have to) send a new key.
294 unsigned int ratchet_allowed;
297 * Number of messages recieved since our last ratchet advance.
298 * - If this counter = 0, we cannot send a new ratchet key in next msg.
299 * - If this counter > 0, we can (but don't yet have to) send a new key.
301 unsigned int ratchet_counter;
304 * When does this ratchet expire and a new one is triggered.
306 struct GNUNET_TIME_Absolute ratchet_expiration;
310 * Struct containing all information regarding a tunnel to a peer.
315 * Endpoint of the tunnel.
317 struct CadetPeer *peer;
320 * Type of encryption used in the tunnel.
322 enum CadetTunnelEncryption enc_type;
327 struct CadetTunnelAxolotl *ax;
330 * State of the tunnel connectivity.
332 enum CadetTunnelCState cstate;
335 * State of the tunnel encryption.
337 enum CadetTunnelEState estate;
340 * Key eXchange context.
342 struct CadetTunnelKXCtx *kx_ctx;
345 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
348 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
351 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
353 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
356 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
358 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
361 * Task to start the rekey process.
363 struct GNUNET_SCHEDULER_Task * rekey_task;
366 * Paths that are actively used to reach the destination peer.
368 struct CadetTConnection *connection_head;
369 struct CadetTConnection *connection_tail;
372 * Next connection number.
377 * Channels inside this tunnel.
379 struct CadetTChannel *channel_head;
380 struct CadetTChannel *channel_tail;
383 * Channel ID for the next created channel.
385 CADET_ChannelNumber next_chid;
388 * Destroy flag: if true, destroy on last message.
390 struct GNUNET_SCHEDULER_Task * destroy_task;
393 * Queued messages, to transmit once tunnel gets connected.
395 struct CadetTunnelDelayed *tq_head;
396 struct CadetTunnelDelayed *tq_tail;
399 * Task to trim connections if too many are present.
401 struct GNUNET_SCHEDULER_Task * trim_connections_task;
404 * Ephemeral message in the queue (to avoid queueing more than one).
406 struct CadetConnectionQueue *ephm_h;
409 * Pong message in the queue.
411 struct CadetConnectionQueue *pong_h;
416 * Struct used to save messages in a non-ready tunnel to send once connected.
418 struct CadetTunnelDelayed
423 struct CadetTunnelDelayed *next;
424 struct CadetTunnelDelayed *prev;
429 struct CadetTunnel *t;
432 * Tunnel queue given to the channel to cancel request. Update on send_queued.
434 struct CadetTunnelQueue *tq;
439 /* struct GNUNET_MessageHeader *msg; */
444 * Handle for messages queued but not yet sent.
446 struct CadetTunnelQueue
449 * Connection queue handle, to cancel if necessary.
451 struct CadetConnectionQueue *cq;
454 * Handle in case message hasn't been given to a connection yet.
456 struct CadetTunnelDelayed *tqd;
459 * Continuation to call once sent.
464 * Closure for @c cont.
471 * Cached Axolotl key with signature.
473 struct CadetAxolotlSignedKey
476 * Information about what is being signed (@a permanent_key).
478 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
481 * Permanent public ECDH key.
483 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
486 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
488 struct GNUNET_CRYPTO_EddsaSignature signature;
492 /******************************************************************************/
493 /******************************* GLOBALS ***********************************/
494 /******************************************************************************/
497 * Global handle to the statistics service.
499 extern struct GNUNET_STATISTICS_Handle *stats;
502 * Local peer own ID (memory efficient handle).
504 extern GNUNET_PEER_Id myid;
507 * Local peer own ID (full value).
509 extern struct GNUNET_PeerIdentity my_full_id;
513 * Don't try to recover tunnels if shutting down.
515 extern int shutting_down;
519 * Set of all tunnels, in order to trigger a new exchange on rekey.
520 * Indexed by peer's ID.
522 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
525 * Default TTL for payload packets.
527 static unsigned long long default_ttl;
530 * Own Peer ID private key.
532 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
535 /******************************** AXOLOTL ************************************/
537 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
540 * Own Axolotl permanent public key (cache).
542 static struct CadetAxolotlSignedKey ax_identity;
545 * How many messages are needed to trigger a ratchet advance.
547 static unsigned long long ratchet_messages;
550 * How long until we trigger a ratched advance.
552 static struct GNUNET_TIME_Relative ratchet_time;
555 /******************************** OTR ***********************************/
558 * Own global OTR ephemeral private key.
560 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
563 * Cached message used to perform a OTR key exchange.
565 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
568 * Task to generate a new OTR ephemeral key.
570 static struct GNUNET_SCHEDULER_Task *rekey_task;
575 static struct GNUNET_TIME_Relative rekey_period;
578 /******************************************************************************/
579 /******************************** STATIC ***********************************/
580 /******************************************************************************/
583 * Get string description for tunnel connectivity state.
585 * @param cs Tunnel state.
587 * @return String representation.
590 cstate2s (enum CadetTunnelCState cs)
596 case CADET_TUNNEL_NEW:
597 return "CADET_TUNNEL_NEW";
598 case CADET_TUNNEL_SEARCHING:
599 return "CADET_TUNNEL_SEARCHING";
600 case CADET_TUNNEL_WAITING:
601 return "CADET_TUNNEL_WAITING";
602 case CADET_TUNNEL_READY:
603 return "CADET_TUNNEL_READY";
604 case CADET_TUNNEL_SHUTDOWN:
605 return "CADET_TUNNEL_SHUTDOWN";
607 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
615 * Get string description for tunnel encryption state.
617 * @param es Tunnel state.
619 * @return String representation.
622 estate2s (enum CadetTunnelEState es)
628 case CADET_TUNNEL_KEY_UNINITIALIZED:
629 return "CADET_TUNNEL_KEY_UNINITIALIZED";
630 case CADET_TUNNEL_KEY_SENT:
631 return "CADET_TUNNEL_KEY_SENT";
632 case CADET_TUNNEL_KEY_PING:
633 return "CADET_TUNNEL_KEY_PING";
634 case CADET_TUNNEL_KEY_OK:
635 return "CADET_TUNNEL_KEY_OK";
636 case CADET_TUNNEL_KEY_REKEY:
637 return "CADET_TUNNEL_KEY_REKEY";
639 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
647 * @brief Check if tunnel is ready to send traffic.
649 * Tunnel must be connected and with encryption correctly set up.
651 * @param t Tunnel to check.
653 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
656 is_ready (struct CadetTunnel *t)
660 ready = CADET_TUNNEL_READY == t->cstate
661 && (CADET_TUNNEL_KEY_OK == t->estate
662 || CADET_TUNNEL_KEY_REKEY == t->estate);
663 ready = ready || GCT_is_loopback (t);
669 * Check if a key is invalid (NULL pointer or all 0)
671 * @param key Key to check.
673 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
676 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
678 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
683 memset (&null_key, 0, sizeof (null_key));
684 if (0 == memcmp (key, &null_key, sizeof (null_key)))
691 * Ephemeral key message purpose size.
693 * @return Size of the part of the ephemeral key message that must be signed.
696 ephemeral_purpose_size (void)
698 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
699 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
700 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
701 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
702 sizeof (struct GNUNET_PeerIdentity);
707 * Ephemeral key message purpose size.
709 * @return Size of the part of the ephemeral key message that must be signed.
712 ax_purpose_size (void)
714 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
715 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
720 * Size of the encrypted part of a ping message.
722 * @return Size of the encrypted part of a ping message.
725 ping_encryption_size (void)
727 return sizeof (uint32_t);
732 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
734 * @param tch Tunnel's channel handle.
736 * @return Amount of messages the channel can still buffer towards the client.
739 get_channel_buffer (const struct CadetTChannel *tch)
743 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
744 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
746 return GCCH_get_buffer (tch->ch, fwd);
751 * Get the channel's allowance status.
753 * @param tch Tunnel's channel handle.
755 * @return #GNUNET_YES if we allowed the client to send data to us.
758 get_channel_allowed (const struct CadetTChannel *tch)
762 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
763 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
765 return GCCH_get_allowed (tch->ch, fwd);
770 * Get the connection's buffer.
772 * @param tc Tunnel's connection handle.
774 * @return Amount of messages the connection can still buffer.
777 get_connection_buffer (const struct CadetTConnection *tc)
781 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
782 fwd = GCC_is_origin (tc->c, GNUNET_YES);
784 return GCC_get_buffer (tc->c, fwd);
789 * Get the connection's allowance.
791 * @param tc Tunnel's connection handle.
793 * @return Amount of messages we have allowed the next peer to send us.
796 get_connection_allowed (const struct CadetTConnection *tc)
800 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
801 fwd = GCC_is_origin (tc->c, GNUNET_YES);
803 return GCC_get_allowed (tc->c, fwd);
808 * Check that a ephemeral key message s well formed and correctly signed.
810 * @param t Tunnel on which the message came.
811 * @param msg The ephemeral key message.
813 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
816 check_ephemeral (struct CadetTunnel *t,
817 const struct GNUNET_CADET_KX_Ephemeral *msg)
819 /* Check message size */
820 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
821 return GNUNET_SYSERR;
823 /* Check signature size */
824 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
825 return GNUNET_SYSERR;
828 if (0 != memcmp (&msg->origin_identity,
829 GCP_get_id (t->peer),
830 sizeof (struct GNUNET_PeerIdentity)))
831 return GNUNET_SYSERR;
833 /* Check signature */
835 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
838 &msg->origin_identity.public_key))
839 return GNUNET_SYSERR;
846 * Select the best key to use for encryption (send), based on KX status.
848 * Normally, return the current key. If there is a KX in progress and the old
849 * key is fresh enough, return the old key.
851 * @param t Tunnel to choose the key from.
853 * @return The optimal key to encrypt/hmac outgoing traffic.
855 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
856 select_key (const struct CadetTunnel *t)
858 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
860 if (NULL != t->kx_ctx
861 && NULL == t->kx_ctx->finish_task)
863 struct GNUNET_TIME_Relative age;
865 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
866 LOG (GNUNET_ERROR_TYPE_DEBUG,
867 " key exchange in progress, started %s ago\n",
868 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
869 // FIXME make duration of old keys configurable
870 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
872 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
873 key = &t->kx_ctx->e_key_old;
877 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
883 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
893 * @param plaintext Content to HMAC.
894 * @param size Size of @c plaintext.
895 * @param iv Initialization vector for the message.
896 * @param key Key to use.
897 * @param hmac[out] Destination to store the HMAC.
900 t_hmac (const void *plaintext, size_t size,
901 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
902 struct GNUNET_CADET_Hash *hmac)
904 static const char ctx[] = "cadet authentication key";
905 struct GNUNET_CRYPTO_AuthKey auth_key;
906 struct GNUNET_HashCode hash;
908 #if DUMP_KEYS_TO_STDERR
909 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
910 GNUNET_h2s ((struct GNUNET_HashCode *) key));
912 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
917 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
918 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
919 memcpy (hmac, &hash, sizeof (*hmac));
924 * Encrypt daforce_newest_keyta with the tunnel key.
926 * @param t Tunnel whose key to use.
927 * @param dst Destination for the encrypted data.
928 * @param src Source of the plaintext. Can overlap with @c dst.
929 * @param size Size of the plaintext.
930 * @param iv Initialization Vector to use.
931 * @param force_newest_key Force the use of the newest key, otherwise
932 * CADET will use the old key when allowed.
933 * This can happen in the case when a KX is going on
934 * and the old one hasn't expired.
937 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
938 size_t size, uint32_t iv, int force_newest_key)
940 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
941 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
944 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
946 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
947 #if DUMP_KEYS_TO_STDERR
948 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
949 GNUNET_h2s ((struct GNUNET_HashCode *) key));
951 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
952 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
953 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
954 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
963 * @param key Key to use.
964 * @param hash[out] Resulting HMAC.
965 * @param source Source key material (data to HMAC).
966 * @param len Length of @a source.
969 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
970 struct GNUNET_HashCode *hash,
971 void *source, unsigned int len)
973 static const char ctx[] = "axolotl HMAC-HASH";
974 struct GNUNET_CRYPTO_AuthKey auth_key;
976 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
979 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
984 * Derive a key from a HMAC-HASH.
986 * @param key Key to use for the HMAC.
987 * @param out Key to generate.
988 * @param source Source key material (data to HMAC).
989 * @param len Length of @a source.
992 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
993 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
994 void *source, unsigned int len)
996 static const char ctx[] = "axolotl derive key";
997 struct GNUNET_HashCode h;
999 t_ax_hmac_hash (key, &h, source, len);
1000 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
1001 &h, sizeof (h), NULL);
1006 * Encrypt data with the axolotl tunnel key.
1008 * @param t Tunnel whose key to use.
1009 * @param dst Destination for the encrypted data.
1010 * @param src Source of the plaintext. Can overlap with @c dst.
1011 * @param size Size of the plaintext.
1013 * @return Size of the encrypted data.
1016 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1018 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1019 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1020 struct CadetTunnelAxolotl *ax;
1023 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
1027 ax->ratchet_counter++;
1028 if (GNUNET_YES == ax->ratchet_allowed
1029 && (ratchet_messages <= ax->ratchet_counter
1030 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
1032 ax->ratchet_flag = GNUNET_YES;
1035 if (GNUNET_YES == ax->ratchet_flag)
1037 /* Advance ratchet */
1038 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1039 struct GNUNET_HashCode dh;
1040 struct GNUNET_HashCode hmac;
1041 static const char ctx[] = "axolotl ratchet";
1043 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1046 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1047 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1048 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1049 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1050 &hmac, sizeof (hmac), NULL);
1057 ax->ratchet_flag = GNUNET_NO;
1058 ax->ratchet_allowed = GNUNET_NO;
1059 ax->ratchet_counter = 0;
1060 ax->ratchet_expiration =
1061 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1064 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1065 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1067 #if DUMP_KEYS_TO_STDERR
1068 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1069 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1070 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1071 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1074 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1076 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1078 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1085 * Decrypt data with the axolotl tunnel key.
1087 * @param t Tunnel whose key to use.
1088 * @param dst Destination for the decrypted data.
1089 * @param src Source of the ciphertext. Can overlap with @c dst.
1090 * @param size Size of the ciphertext.
1092 * @return Size of the decrypted data.
1095 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1097 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1098 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1099 struct CadetTunnelAxolotl *ax;
1102 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1106 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1107 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1109 #if DUMP_KEYS_TO_STDERR
1110 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1111 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1112 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1113 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1116 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1117 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1118 GNUNET_assert (out_size == size);
1120 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1122 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1129 * Encrypt header with the axolotl header key.
1131 * @param t Tunnel whose key to use.
1132 * @param msg Message whose header to encrypt.
1135 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1137 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1138 struct CadetTunnelAxolotl *ax;
1141 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1144 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1146 #if DUMP_KEYS_TO_STDERR
1147 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1148 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1151 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1152 &ax->HKs, &iv, &msg->Ns);
1154 GNUNET_assert (AX_HEADER_SIZE == out_size);
1156 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1161 * Decrypt header with the current axolotl header key.
1163 * @param t Tunnel whose current ax HK to use.
1164 * @param src Message whose header to decrypt.
1165 * @param dst Where to decrypt header to.
1168 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1169 struct GNUNET_CADET_AX *dst)
1171 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1172 struct CadetTunnelAxolotl *ax;
1175 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1178 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1180 #if DUMP_KEYS_TO_STDERR
1181 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1182 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1185 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1186 &ax->HKr, &iv, &dst->Ns);
1188 GNUNET_assert (AX_HEADER_SIZE == out_size);
1190 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1195 * Decrypt and verify data with the appropriate tunnel key.
1197 * @param key Key to use.
1198 * @param dst Destination for the plaintext.
1199 * @param src Source of the encrypted data. Can overlap with @c dst.
1200 * @param size Size of the encrypted data.
1201 * @param iv Initialization Vector to use.
1203 * @return Size of the decrypted data, -1 if an error was encountered.
1206 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1207 void *dst, const void *src, size_t size, uint32_t iv)
1209 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1212 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1213 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1214 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1215 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1216 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1217 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1224 * Decrypt and verify data with the most recent tunnel key.
1226 * @param t Tunnel whose key to use.
1227 * @param dst Destination for the plaintext.
1228 * @param src Source of the encrypted data. Can overlap with @c dst.
1229 * @param size Size of the encrypted data.
1230 * @param iv Initialization Vector to use.
1232 * @return Size of the decrypted data, -1 if an error was encountered.
1235 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1236 size_t size, uint32_t iv)
1240 #if DUMP_KEYS_TO_STDERR
1241 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1242 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1244 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1246 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1247 LOG (GNUNET_ERROR_TYPE_WARNING,
1248 "got data on %s without a valid key\n",
1250 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1254 out_size = decrypt (&t->d_key, dst, src, size, iv);
1261 * Decrypt and verify data with the appropriate tunnel key and verify that the
1262 * data has not been altered since it was sent by the remote peer.
1264 * @param t Tunnel whose key to use.
1265 * @param dst Destination for the plaintext.
1266 * @param src Source of the encrypted data. Can overlap with @c dst.
1267 * @param size Size of the encrypted data.
1268 * @param iv Initialization Vector to use.
1269 * @param msg_hmac HMAC of the message, cannot be NULL.
1271 * @return Size of the decrypted data, -1 if an error was encountered.
1274 t_decrypt_and_validate (struct CadetTunnel *t,
1275 void *dst, const void *src,
1276 size_t size, uint32_t iv,
1277 const struct GNUNET_CADET_Hash *msg_hmac)
1279 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1280 struct GNUNET_CADET_Hash hmac;
1283 /* Try primary (newest) key */
1285 decrypted_size = decrypt (key, dst, src, size, iv);
1286 t_hmac (src, size, iv, key, &hmac);
1287 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1288 return decrypted_size;
1290 /* If no key exchange is going on, we just failed. */
1291 if (NULL == t->kx_ctx)
1293 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1294 "Failed checksum validation on tunnel %s with no KX\n",
1296 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1300 /* Try secondary key, from previous KX period. */
1301 key = &t->kx_ctx->d_key_old;
1302 decrypted_size = decrypt (key, dst, src, size, iv);
1303 t_hmac (src, size, iv, key, &hmac);
1304 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1305 return decrypted_size;
1307 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1308 key = &t->kx_ctx->d_key_old2;
1309 decrypted_size = decrypt (key, dst, src, size, iv);
1310 t_hmac (src, size, iv, key, &hmac);
1311 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1312 return decrypted_size;
1314 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1315 "Failed checksum validation on tunnel %s with KX\n",
1317 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1323 * Decrypt and verify data with the appropriate tunnel key and verify that the
1324 * data has not been altered since it was sent by the remote peer.
1326 * @param t Tunnel whose key to use.
1327 * @param dst Destination for the plaintext.
1328 * @param src Source of the message. Can overlap with @c dst.
1329 * @param size Size of the message.
1331 * @return Size of the decrypted data, -1 if an error was encountered.
1334 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1335 const struct GNUNET_CADET_AX *src, size_t size)
1337 struct CadetTunnelSkippedKey *key;
1338 struct GNUNET_CADET_Hash hmac;
1339 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1344 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1346 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1347 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1353 #if DUMP_KEYS_TO_STDERR
1354 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1355 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1358 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1359 len = size - sizeof (struct GNUNET_CADET_AX);
1360 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1361 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1363 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1372 * Delete a key from the list of skipped keys.
1374 * @param t Tunnel to delete from.
1375 * @param HKr Header Key to use.
1378 store_skipped_key (struct CadetTunnel *t,
1379 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1381 struct CadetTunnelSkippedKey *key;
1383 key = GNUNET_new (struct CadetTunnelSkippedKey);
1384 key->timestamp = GNUNET_TIME_absolute_get ();
1385 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1386 #if DUMP_KEYS_TO_STDERR
1387 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1388 t->ax->Nr, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1389 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1390 GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1392 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1393 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1400 * Delete a key from the list of skipped keys.
1402 * @param t Tunnel to delete from.
1403 * @param key Key to delete.
1406 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1408 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1415 * Stage skipped AX keys and calculate the message key.
1417 * Stores each HK and MK for skipped messages.
1419 * @param t Tunnel where to stage the keys.
1420 * @param HKr Header key.
1421 * @param Np Received meesage number.
1424 store_ax_keys (struct CadetTunnel *t,
1425 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1430 gap = Np - t->ax->Nr;
1431 if (MAX_KEY_GAP < gap || 0 > gap)
1433 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1434 /* TODO: start new key exchange on return */
1435 GNUNET_break_op (0);
1439 while (t->ax->Nr < Np)
1440 store_skipped_key (t, HKr);
1442 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1443 delete_skipped_key (t, t->ax->skipped_tail);
1448 * Decrypt and verify data with the appropriate tunnel key and verify that the
1449 * data has not been altered since it was sent by the remote peer.
1451 * @param t Tunnel whose key to use.
1452 * @param dst Destination for the plaintext.
1453 * @param src Source of the message. Can overlap with @c dst.
1454 * @param size Size of the message.
1456 * @return Size of the decrypted data, -1 if an error was encountered.
1459 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1460 const struct GNUNET_CADET_AX *src, size_t size)
1462 struct CadetTunnelAxolotl *ax;
1463 struct GNUNET_CADET_Hash msg_hmac;
1464 struct GNUNET_HashCode hmac;
1465 struct GNUNET_CADET_AX *dstmsg;
1473 esize = size - sizeof (struct GNUNET_CADET_AX);
1478 /* Try current HK */
1479 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1480 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1482 static const char ctx[] = "axolotl ratchet";
1483 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1484 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1485 struct GNUNET_HashCode dh;
1486 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1489 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1490 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1492 /* Try the skipped keys, if that fails, we're out of luck. */
1493 return try_old_ax_keys (t, dst, src, size);
1495 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1499 t_h_decrypt (t, src, dstmsg);
1500 Np = ntohl (dstmsg->Ns);
1501 PNp = ntohl (dstmsg->PNs);
1502 DHRp = &dstmsg->DHRs;
1503 store_ax_keys (t, &HK, PNp);
1505 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1506 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1507 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1508 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1509 &hmac, sizeof (hmac), NULL);
1511 /* Commit "purported" keys */
1517 ax->ratchet_allowed = GNUNET_YES;
1521 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1522 t_h_decrypt (t, src, dstmsg);
1523 Np = ntohl (dstmsg->Ns);
1524 PNp = ntohl (dstmsg->PNs);
1528 store_ax_keys (t, &ax->HKr, Np);
1532 osize = t_ax_decrypt (t, dst, &src[1], esize);
1535 GNUNET_break_op (0);
1544 * Create key material by doing ECDH on the local and remote ephemeral keys.
1546 * @param key_material Where to store the key material.
1547 * @param ephemeral Peer's public ephemeral key.
1549 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1552 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1553 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1556 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1559 return GNUNET_SYSERR;
1566 * Create a symmetic key from the identities of both ends and the key material
1569 * @param key Destination for the generated key.
1570 * @param sender ID of the peer that will encrypt with @c key.
1571 * @param receiver ID of the peer that will decrypt with @c key.
1572 * @param key_material Hash created with ECDH with the ephemeral keys.
1575 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1576 const struct GNUNET_PeerIdentity *sender,
1577 const struct GNUNET_PeerIdentity *receiver,
1578 const struct GNUNET_HashCode *key_material)
1580 const char salt[] = "CADET kx salt";
1582 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1583 salt, sizeof (salt),
1584 key_material, sizeof (struct GNUNET_HashCode),
1585 sender, sizeof (struct GNUNET_PeerIdentity),
1586 receiver, sizeof (struct GNUNET_PeerIdentity),
1592 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1594 * @param t Tunnel for which to create the keys.
1596 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1599 create_otr_keys (struct CadetTunnel *t)
1601 struct GNUNET_HashCode km;
1603 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1604 return GNUNET_SYSERR;
1605 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1606 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1607 #if DUMP_KEYS_TO_STDERR
1608 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1609 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1610 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1611 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1612 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1613 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1614 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1615 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1616 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1623 * Create a new Key eXchange context for the tunnel.
1625 * If the old keys were verified, keep them for old traffic. Create a new KX
1626 * timestamp and a new nonce.
1628 * @param t Tunnel for which to create the KX ctx.
1630 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1633 create_kx_ctx (struct CadetTunnel *t)
1635 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1637 if (NULL != t->kx_ctx)
1639 if (NULL != t->kx_ctx->finish_task)
1641 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1642 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1643 t->kx_ctx->finish_task = NULL;
1648 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1649 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1653 if (CADET_TUNNEL_KEY_OK == t->estate)
1655 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1656 t->kx_ctx->d_key_old = t->d_key;
1657 t->kx_ctx->e_key_old = t->e_key;
1660 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1661 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1662 return create_otr_keys (t);
1667 * @brief Finish the Key eXchange and destroy the old keys.
1669 * @param cls Closure (Tunnel for which to finish the KX).
1670 * @param tc Task context.
1673 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1675 struct CadetTunnel *t = cls;
1677 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1679 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1681 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1685 GNUNET_free (t->kx_ctx);
1691 * Destroy a Key eXchange context for the tunnel. This function only schedules
1692 * the destruction, the freeing of the memory (and clearing of old key material)
1693 * happens after a delay!
1695 * @param t Tunnel whose KX ctx to destroy.
1698 destroy_kx_ctx (struct CadetTunnel *t)
1700 struct GNUNET_TIME_Relative delay;
1702 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1705 if (is_key_null (&t->kx_ctx->e_key_old))
1707 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1711 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1712 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1714 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1720 * Pick a connection on which send the next data message.
1722 * @param t Tunnel on which to send the message.
1724 * @return The connection on which to send the next message.
1726 static struct CadetConnection *
1727 tunnel_get_connection (struct CadetTunnel *t)
1729 struct CadetTConnection *iter;
1730 struct CadetConnection *best;
1732 unsigned int lowest_q;
1734 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1736 lowest_q = UINT_MAX;
1737 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1739 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1740 GCC_2s (iter->c), GCC_get_state (iter->c));
1741 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1743 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1744 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1752 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1758 * Callback called when a queued message is sent.
1760 * Calculates the average time and connection packet tracking.
1762 * @param cls Closure (TunnelQueue handle).
1763 * @param c Connection this message was on.
1764 * @param q Connection queue handle (unused).
1765 * @param type Type of message sent.
1766 * @param fwd Was this a FWD going message?
1767 * @param size Size of the message.
1770 tun_message_sent (void *cls,
1771 struct CadetConnection *c,
1772 struct CadetConnectionQueue *q,
1773 uint16_t type, int fwd, size_t size)
1775 struct CadetTunnelQueue *qt = cls;
1776 struct CadetTunnel *t;
1778 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1780 GNUNET_assert (NULL != qt->cont);
1781 t = NULL == c ? NULL : GCC_get_tunnel (c);
1782 qt->cont (qt->cont_cls, t, qt, type, size);
1788 count_queued_data (const struct CadetTunnel *t)
1790 struct CadetTunnelDelayed *iter;
1793 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1800 * Delete a queued message: either was sent or the channel was destroyed
1801 * before the tunnel's key exchange had a chance to finish.
1803 * @param tqd Delayed queue handle.
1806 unqueue_data (struct CadetTunnelDelayed *tqd)
1808 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1814 * Cache a message to be sent once tunnel is online.
1816 * @param t Tunnel to hold the message.
1817 * @param msg Message itself (copy will be made).
1819 static struct CadetTunnelDelayed *
1820 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1822 struct CadetTunnelDelayed *tqd;
1823 uint16_t size = ntohs (msg->size);
1825 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1827 GNUNET_assert (GNUNET_NO == is_ready (t));
1829 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1832 memcpy (&tqd[1], msg, size);
1833 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1839 * Sends an already built message on a tunnel, encrypting it and
1840 * choosing the best connection.
1842 * @param message Message to send. Function modifies it.
1843 * @param t Tunnel on which this message is transmitted.
1844 * @param c Connection to use (autoselect if NULL).
1845 * @param force Force the tunnel to take the message (buffer overfill).
1846 * @param cont Continuation to call once message is really sent.
1847 * @param cont_cls Closure for @c cont.
1848 * @param existing_q In case this a transmission of previously queued data,
1849 * this should be TunnelQueue given to the client.
1852 * @return Handle to cancel message.
1853 * NULL if @c cont is NULL or an error happens and message is dropped.
1855 static struct CadetTunnelQueue *
1856 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1857 struct CadetTunnel *t, struct CadetConnection *c,
1858 int force, GCT_sent cont, void *cont_cls,
1859 struct CadetTunnelQueue *existing_q)
1861 struct GNUNET_MessageHeader *msg;
1862 struct GNUNET_CADET_Encrypted *otr_msg;
1863 struct GNUNET_CADET_AX *ax_msg;
1864 struct CadetTunnelQueue *tq;
1865 size_t size = ntohs (message->size);
1866 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1867 + sizeof (struct GNUNET_CADET_AX);
1868 char cbuf[max_overhead + size];
1875 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1877 if (GNUNET_NO == is_ready (t))
1879 struct CadetTunnelDelayed *tqd;
1880 /* A non null existing_q indicates sending of queued data.
1881 * Should only happen after tunnel becomes ready.
1883 GNUNET_assert (NULL == existing_q);
1884 tqd = queue_data (t, message);
1887 tq = GNUNET_new (struct CadetTunnelQueue);
1891 tq->cont_cls = cont_cls;
1895 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1897 if (CADET_Axolotl == t->enc_type)
1899 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1900 msg = &ax_msg->header;
1901 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1902 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1903 ax_msg->reserved = 0;
1904 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1905 ax_msg->Ns = htonl (t->ax->Ns++);
1906 ax_msg->PNs = htonl (t->ax->PNs);
1907 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1908 t_h_encrypt (t, ax_msg);
1909 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1913 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1914 msg = &otr_msg->header;
1915 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1917 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1918 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1919 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1920 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1921 otr_msg->ttl = htonl (default_ttl);
1923 GNUNET_assert (esize == size);
1926 c = tunnel_get_connection (t);
1929 /* Why is tunnel 'ready'? Should have been queued! */
1930 if (NULL != t->destroy_task)
1933 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1935 return NULL; /* Drop... */
1939 type = ntohs (message->type);
1942 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1943 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1944 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1945 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1947 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1949 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1950 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1951 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1952 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1953 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1957 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1959 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1961 fwd = GCC_is_origin (c, GNUNET_YES);
1965 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1966 mid, c, fwd, force, NULL, NULL));
1969 if (NULL == existing_q)
1971 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1978 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1979 &tun_message_sent, tq);
1980 GNUNET_assert (NULL != tq->cq);
1982 tq->cont_cls = cont_cls;
1989 * Send all cached messages that we can, tunnel is online.
1991 * @param t Tunnel that holds the messages. Cannot be loopback.
1994 send_queued_data (struct CadetTunnel *t)
1996 struct CadetTunnelDelayed *tqd;
1997 struct CadetTunnelDelayed *next;
2000 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
2002 if (GCT_is_loopback (t))
2008 if (GNUNET_NO == is_ready (t))
2010 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
2011 estate2s (t->estate), cstate2s (t->cstate));
2015 room = GCT_get_connections_buffer (t);
2016 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2017 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
2018 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
2020 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
2023 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2024 tqd->t, NULL, GNUNET_YES,
2025 NULL != tqd->tq ? tqd->tq->cont : NULL,
2026 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2030 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2035 * @brief Resend the AX KX until we complete the handshake.
2037 * @param cls Closure (tunnel).
2038 * @param tc Task context.
2041 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2043 struct CadetTunnel *t = cls;
2045 t->rekey_task = NULL;
2047 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2050 if (CADET_TUNNEL_KEY_OK == t->estate)
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 && CADET_TUNNEL_KEY_OK != t->estate)
2082 if (NULL != t->rekey_task)
2085 GNUNET_SCHEDULER_cancel (t->rekey_task);
2087 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2094 * Callback called when a queued message is sent.
2096 * @param cls Closure.
2097 * @param c Connection this message was on.
2098 * @param type Type of message sent.
2099 * @param fwd Was this a FWD going message?
2100 * @param size Size of the message.
2103 pong_sent (void *cls,
2104 struct CadetConnection *c,
2105 struct CadetConnectionQueue *q,
2106 uint16_t type, int fwd, size_t size)
2108 struct CadetTunnel *t = cls;
2109 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2116 * Sends key exchange message on a tunnel, choosing the best connection.
2117 * Should not be called on loopback tunnels.
2119 * @param t Tunnel on which this message is transmitted.
2120 * @param message Message to send. Function modifies it.
2122 * @return Handle to the message in the connection queue.
2124 static struct CadetConnectionQueue *
2125 send_kx (struct CadetTunnel *t,
2126 const struct GNUNET_MessageHeader *message)
2128 struct CadetConnection *c;
2129 struct GNUNET_CADET_KX *msg;
2130 size_t size = ntohs (message->size);
2131 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2136 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2138 /* Avoid loopback. */
2139 if (GCT_is_loopback (t))
2144 type = ntohs (message->type);
2146 /* Even if tunnel is "being destroyed", send anyway.
2147 * Could be a response to a rekey initiated by remote peer,
2148 * who is trying to create a new channel!
2151 /* Must have a connection, or be looking for one. */
2152 if (NULL == t->connection_head)
2154 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2155 if (CADET_TUNNEL_SEARCHING != t->cstate)
2158 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2159 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2164 msg = (struct GNUNET_CADET_KX *) cbuf;
2165 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2166 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2167 c = tunnel_get_connection (t);
2170 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2173 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2179 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2180 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2181 GNUNET_assert (NULL == t->ephm_h);
2184 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2185 GNUNET_assert (NULL == t->pong_h);
2190 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2193 memcpy (&msg[1], message, size);
2195 fwd = GCC_is_origin (c, GNUNET_YES);
2197 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2204 * Send the ephemeral key on a tunnel.
2206 * @param t Tunnel on which to send the key.
2209 send_ephemeral (struct CadetTunnel *t)
2211 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2212 if (NULL != t->ephm_h)
2214 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2218 otr_kx_msg.sender_status = htonl (t->estate);
2219 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2220 otr_kx_msg.nonce = t->kx_ctx->challenge;
2221 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2222 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2223 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2224 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2225 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2230 * Send a pong message on a tunnel.
2232 * @param t Tunnel on which to send the pong.
2233 * @param challenge Value sent in the ping that we have to send back.
2236 send_pong (struct CadetTunnel *t, uint32_t challenge)
2238 struct GNUNET_CADET_KX_Pong msg;
2240 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2241 if (NULL != t->pong_h)
2243 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2246 msg.header.size = htons (sizeof (msg));
2247 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2248 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2249 msg.nonce = challenge;
2250 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2251 t_encrypt (t, &msg.nonce, &msg.nonce,
2252 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2253 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2255 t->pong_h = send_kx (t, &msg.header);
2260 * Initiate a rekey with the remote peer.
2262 * @param cls Closure (tunnel).
2263 * @param tc TaskContext.
2266 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2268 struct CadetTunnel *t = cls;
2270 t->rekey_task = NULL;
2272 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2273 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2276 GNUNET_assert (NULL != t->kx_ctx);
2277 struct GNUNET_TIME_Relative duration;
2279 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2280 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2281 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2283 // FIXME make duration of old keys configurable
2284 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2286 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2287 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2288 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2295 case CADET_TUNNEL_KEY_UNINITIALIZED:
2296 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2299 case CADET_TUNNEL_KEY_SENT:
2302 case CADET_TUNNEL_KEY_OK:
2304 * - state should have changed during rekey_iterator
2305 * - task should have been canceled at pong_handle
2308 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2311 case CADET_TUNNEL_KEY_PING:
2312 case CADET_TUNNEL_KEY_REKEY:
2316 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2319 // FIXME exponential backoff
2320 struct GNUNET_TIME_Relative delay;
2322 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2323 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2324 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2325 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2326 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2331 * Our ephemeral key has changed, create new session key on all tunnels.
2333 * Each tunnel will start the Key Exchange with a random delay between
2334 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2335 * per second, on average.
2337 * @param cls Closure (size of the hashmap).
2338 * @param key Current public key.
2339 * @param value Value in the hash map (tunnel).
2341 * @return #GNUNET_YES, so we should continue to iterate,
2344 rekey_iterator (void *cls,
2345 const struct GNUNET_PeerIdentity *key,
2348 struct CadetTunnel *t = value;
2349 struct GNUNET_TIME_Relative delay;
2350 long n = (long) cls;
2353 if (NULL != t->rekey_task)
2356 if (GNUNET_YES == GCT_is_loopback (t))
2359 if (CADET_OTR != t->enc_type)
2362 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2363 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2364 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2365 if (GNUNET_OK == create_kx_ctx (t))
2366 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2378 * Create a new ephemeral key and key message, schedule next rekeying.
2380 * @param cls Closure (unused).
2381 * @param tc TaskContext.
2384 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2386 struct GNUNET_TIME_Absolute time;
2391 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2394 GNUNET_free_non_null (otr_ephemeral_key);
2395 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2397 time = GNUNET_TIME_absolute_get ();
2398 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2399 time = GNUNET_TIME_absolute_add (time, rekey_period);
2400 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2401 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2402 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2403 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2404 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2406 GNUNET_assert (GNUNET_OK ==
2407 GNUNET_CRYPTO_eddsa_sign (id_key,
2408 &otr_kx_msg.purpose,
2409 &otr_kx_msg.signature));
2411 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2412 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2414 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2415 &global_otr_rekey, NULL);
2420 * Called only on shutdown, destroy every tunnel.
2422 * @param cls Closure (unused).
2423 * @param key Current public key.
2424 * @param value Value in the hash map (tunnel).
2426 * @return #GNUNET_YES, so we should continue to iterate,
2429 destroy_iterator (void *cls,
2430 const struct GNUNET_PeerIdentity *key,
2433 struct CadetTunnel *t = value;
2435 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2442 * Notify remote peer that we don't know a channel he is talking about,
2443 * probably CHANNEL_DESTROY was missed.
2445 * @param t Tunnel on which to notify.
2446 * @param gid ID of the channel.
2449 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2451 struct GNUNET_CADET_ChannelManage msg;
2453 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2454 msg.header.size = htons (sizeof (msg));
2455 msg.chid = htonl (gid);
2457 LOG (GNUNET_ERROR_TYPE_DEBUG,
2458 "WARNING destroying unknown channel %u on tunnel %s\n",
2460 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2465 * Demultiplex data per channel and call appropriate channel handler.
2467 * @param t Tunnel on which the data came.
2468 * @param msg Data message.
2469 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2470 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2471 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2472 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2475 handle_data (struct CadetTunnel *t,
2476 const struct GNUNET_CADET_Data *msg,
2479 struct CadetChannel *ch;
2483 size = ntohs (msg->header.size);
2485 sizeof (struct GNUNET_CADET_Data) +
2486 sizeof (struct GNUNET_MessageHeader))
2491 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2492 GC_m2s (ntohs (msg[1].header.type)));
2495 ch = GCT_get_channel (t, ntohl (msg->chid));
2498 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2500 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2502 send_channel_destroy (t, ntohl (msg->chid));
2506 GCCH_handle_data (ch, msg, fwd);
2511 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2513 * @param t Tunnel on which the DATA ACK came.
2514 * @param msg DATA ACK message.
2515 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2516 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2517 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2518 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2521 handle_data_ack (struct CadetTunnel *t,
2522 const struct GNUNET_CADET_DataACK *msg,
2525 struct CadetChannel *ch;
2529 size = ntohs (msg->header.size);
2530 if (size != sizeof (struct GNUNET_CADET_DataACK))
2537 ch = GCT_get_channel (t, ntohl (msg->chid));
2540 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2542 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2547 GCCH_handle_data_ack (ch, msg, fwd);
2552 * Handle channel create.
2554 * @param t Tunnel on which the data came.
2555 * @param msg Data message.
2558 handle_ch_create (struct CadetTunnel *t,
2559 const struct GNUNET_CADET_ChannelCreate *msg)
2561 struct CadetChannel *ch;
2565 size = ntohs (msg->header.size);
2566 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2573 ch = GCT_get_channel (t, ntohl (msg->chid));
2574 if (NULL != ch && ! GCT_is_loopback (t))
2576 /* Probably a retransmission, safe to ignore */
2577 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2579 ch = GCCH_handle_create (t, msg);
2581 GCT_add_channel (t, ch);
2587 * Handle channel NACK: check correctness and call channel handler for NACKs.
2589 * @param t Tunnel on which the NACK came.
2590 * @param msg NACK message.
2593 handle_ch_nack (struct CadetTunnel *t,
2594 const struct GNUNET_CADET_ChannelManage *msg)
2596 struct CadetChannel *ch;
2600 size = ntohs (msg->header.size);
2601 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2608 ch = GCT_get_channel (t, ntohl (msg->chid));
2611 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2613 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2618 GCCH_handle_nack (ch);
2623 * Handle a CHANNEL ACK (SYNACK/ACK).
2625 * @param t Tunnel on which the CHANNEL ACK came.
2626 * @param msg CHANNEL ACK message.
2627 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2628 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2629 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2630 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2633 handle_ch_ack (struct CadetTunnel *t,
2634 const struct GNUNET_CADET_ChannelManage *msg,
2637 struct CadetChannel *ch;
2641 size = ntohs (msg->header.size);
2642 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2649 ch = GCT_get_channel (t, ntohl (msg->chid));
2652 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2654 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2659 GCCH_handle_ack (ch, msg, fwd);
2664 * Handle a channel destruction message.
2666 * @param t Tunnel on which the message came.
2667 * @param msg Channel destroy message.
2668 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2669 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2670 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2671 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2674 handle_ch_destroy (struct CadetTunnel *t,
2675 const struct GNUNET_CADET_ChannelManage *msg,
2678 struct CadetChannel *ch;
2682 size = ntohs (msg->header.size);
2683 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2690 ch = GCT_get_channel (t, ntohl (msg->chid));
2693 /* Probably a retransmission, safe to ignore */
2697 GCCH_handle_destroy (ch, msg, fwd);
2702 * Create a new Axolotl ephemeral (ratchet) key.
2707 new_ephemeral (struct CadetTunnel *t)
2709 GNUNET_free_non_null (t->ax->DHRs);
2710 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2715 * Free Axolotl data.
2720 destroy_ax (struct CadetTunnel *t)
2725 GNUNET_free_non_null (t->ax->DHRs);
2726 GNUNET_free_non_null (t->ax->kx_0);
2728 GNUNET_free (t->ax);
2731 if (NULL != t->rekey_task)
2733 GNUNET_SCHEDULER_cancel (t->rekey_task);
2734 t->rekey_task = NULL;
2736 if (NULL != t->ephm_h)
2738 GCC_cancel (t->ephm_h);
2746 * The peer's ephemeral key has changed: update the symmetrical keys.
2748 * @param t Tunnel this message came on.
2749 * @param msg Key eXchange message.
2752 handle_ephemeral (struct CadetTunnel *t,
2753 const struct GNUNET_CADET_KX_Ephemeral *msg)
2755 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2757 if (GNUNET_OK != check_ephemeral (t, msg))
2759 GNUNET_break_op (0);
2763 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2767 t->enc_type = CADET_OTR;
2768 if (NULL != t->rekey_task)
2769 GNUNET_SCHEDULER_cancel (t->rekey_task);
2770 if (GNUNET_OK != create_kx_ctx (t))
2776 rekey_tunnel (t, NULL);
2777 GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2781 * If the key is different from what we know, derive the new E/D keys.
2782 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2784 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2785 sizeof (msg->ephemeral_key)))
2787 #if DUMP_KEYS_TO_STDERR
2788 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2789 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2790 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2791 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2793 t->peers_ephemeral_key = msg->ephemeral_key;
2795 if (GNUNET_OK != create_kx_ctx (t))
2802 if (CADET_TUNNEL_KEY_OK == t->estate)
2804 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2806 if (NULL != t->rekey_task)
2807 GNUNET_SCHEDULER_cancel (t->rekey_task);
2808 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2810 if (CADET_TUNNEL_KEY_SENT == t->estate)
2812 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2814 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2817 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2821 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2822 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2823 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2824 send_pong (t, nonce);
2830 * Peer has answer to our challenge.
2831 * If answer is successful, consider the key exchange finished and clean
2832 * up all related state.
2834 * @param t Tunnel this message came on.
2835 * @param msg Key eXchange Pong message.
2838 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2842 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2843 if (NULL == t->rekey_task)
2845 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2848 if (NULL == t->kx_ctx)
2850 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2854 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2855 if (challenge != t->kx_ctx->challenge)
2857 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2858 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2859 challenge, msg->nonce, t->kx_ctx->challenge);
2863 GNUNET_SCHEDULER_cancel (t->rekey_task);
2864 t->rekey_task = NULL;
2866 /* Don't free the old keys right away, but after a delay.
2867 * Rationale: the KX could have happened over a very fast connection,
2868 * with payload traffic still signed with the old key stuck in a slower
2870 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2874 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2879 * Handle Axolotl handshake.
2881 * @param t Tunnel this message came on.
2882 * @param msg Key eXchange Pong message.
2885 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2887 struct CadetTunnelAxolotl *ax;
2888 struct GNUNET_HashCode key_material[3];
2889 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2890 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2891 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2892 const char salt[] = "CADET Axolotl salt";
2893 const struct GNUNET_PeerIdentity *pid;
2896 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2900 /* Something is wrong if ax is NULL. Whose fault it is? */
2901 GNUNET_break_op (CADET_OTR == t->enc_type);
2902 GNUNET_break (CADET_Axolotl == t->enc_type);
2906 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2907 &msg->purpose, &msg->signature))
2909 GNUNET_break_op (0);
2913 pid = GCT_get_destination (t);
2914 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2915 am_I_alice = GNUNET_YES;
2916 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2917 am_I_alice = GNUNET_NO;
2920 GNUNET_break_op (0);
2924 if (GNUNET_YES == ntohl (msg->force_reply))
2925 GCT_send_ax_kx (t, GNUNET_NO);
2927 if (CADET_TUNNEL_KEY_OK == t->estate)
2930 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2933 ax->DHRr = msg->ratchet_key;
2934 ax->DHIr = msg->permanent_key;
2937 if (GNUNET_YES == am_I_alice)
2939 priv = ax_key; /* A */
2940 pub = &msg->ephemeral_key; /* B0 */
2944 priv = ax->kx_0; /* B0 */
2945 pub = &ax->DHIr; /* A */
2947 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2950 if (GNUNET_YES == am_I_alice)
2952 priv = ax->kx_0; /* A0 */
2953 pub = &ax->DHIr; /* B */
2957 priv = ax_key; /* B */
2958 pub = &msg->ephemeral_key; /* A0 */
2960 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2963 priv = ax->kx_0; /* A0 or B0 */
2964 pub = &msg->ephemeral_key; /* B0 or A0 */
2965 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
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);
3002 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
3007 * Demultiplex by message type and call appropriate handler for a message
3008 * towards a channel of a local tunnel.
3010 * @param t Tunnel this message came on.
3011 * @param msgh Message header.
3012 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
3013 * #GNUNET_YES if message is FWD on the respective channel (loopback)
3014 * #GNUNET_NO if message is BCK on the respective channel (loopback)
3015 * #GNUNET_SYSERR if message on a one-ended channel (remote)
3018 handle_decrypted (struct CadetTunnel *t,
3019 const struct GNUNET_MessageHeader *msgh,
3024 type = ntohs (msgh->type);
3025 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
3029 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3030 /* Do nothing, connection aleady got updated. */
3031 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3034 case GNUNET_MESSAGE_TYPE_CADET_DATA:
3035 /* Don't send hop ACK, wait for client to ACK */
3036 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3039 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3040 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3043 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3044 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3047 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3048 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3051 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3052 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3055 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3056 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3060 GNUNET_break_op (0);
3061 LOG (GNUNET_ERROR_TYPE_WARNING,
3062 "end-to-end message not known (%u)\n",
3063 ntohs (msgh->type));
3064 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3068 /******************************************************************************/
3069 /******************************** API ***********************************/
3070 /******************************************************************************/
3072 * Decrypt old format and demultiplex by message type. Call appropriate handler
3073 * for a message towards a channel of a local tunnel.
3075 * @param t Tunnel this message came on.
3076 * @param msg Message header.
3079 GCT_handle_encrypted (struct CadetTunnel *t,
3080 const struct GNUNET_MessageHeader *msg)
3082 uint16_t size = ntohs (msg->size);
3084 size_t payload_size;
3087 struct GNUNET_MessageHeader *msgh;
3090 type = ntohs (msg->type);
3091 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
3093 const struct GNUNET_CADET_Encrypted *emsg;
3095 emsg = (struct GNUNET_CADET_Encrypted *) msg;
3096 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3097 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3098 emsg->iv, &emsg->hmac);
3100 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
3102 const struct GNUNET_CADET_AX *emsg;
3104 emsg = (struct GNUNET_CADET_AX *) msg;
3105 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3108 if (-1 == decrypted_size)
3110 GNUNET_break_op (0);
3115 while (off < decrypted_size)
3119 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
3120 msize = ntohs (msgh->size);
3121 if (msize < sizeof (struct GNUNET_MessageHeader))
3123 GNUNET_break_op (0);
3126 handle_decrypted (t, msgh, GNUNET_SYSERR);
3133 * Demultiplex an encapsulated KX message by message type.
3135 * @param t Tunnel on which the message came.
3136 * @param message Payload of KX message.
3139 GCT_handle_kx (struct CadetTunnel *t,
3140 const struct GNUNET_MessageHeader *message)
3144 type = ntohs (message->type);
3145 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3148 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3149 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3152 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3153 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3156 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3157 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3161 GNUNET_break_op (0);
3162 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3167 * Initialize the tunnel subsystem.
3169 * @param c Configuration handle.
3170 * @param key ECC private key, to derive all other keys and do crypto.
3173 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3174 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3176 int expected_overhead;
3178 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3180 expected_overhead = 0;
3181 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3182 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3183 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3184 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3187 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3190 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3191 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3195 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3198 rekey_period = GNUNET_TIME_UNIT_DAYS;
3201 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3204 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3205 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3206 ratchet_messages = 64;
3209 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3212 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3213 "CADET", "RATCHET_TIME", "USING DEFAULT");
3214 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3220 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3221 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3222 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3223 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3224 otr_kx_msg.origin_identity = my_full_id;
3225 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3227 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
3228 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
3229 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
3230 ax_identity.purpose.size = htonl (ax_purpose_size ());
3231 GNUNET_assert (GNUNET_OK ==
3232 GNUNET_CRYPTO_eddsa_sign (id_key,
3233 &ax_identity.purpose,
3234 &ax_identity.signature));
3236 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3241 * Shut down the tunnel subsystem.
3246 if (NULL != rekey_task)
3248 GNUNET_SCHEDULER_cancel (rekey_task);
3251 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3252 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3253 GNUNET_free (ax_key);
3260 * @param destination Peer this tunnel is towards.
3262 struct CadetTunnel *
3263 GCT_new (struct CadetPeer *destination)
3265 struct CadetTunnel *t;
3267 t = GNUNET_new (struct CadetTunnel);
3269 t->peer = destination;
3272 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3273 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3279 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3281 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3287 * Change the tunnel's connection state.
3289 * @param t Tunnel whose connection state to change.
3290 * @param cstate New connection state.
3293 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3297 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3298 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3299 if (myid != GCP_get_short_id (t->peer) &&
3300 CADET_TUNNEL_READY != t->cstate &&
3301 CADET_TUNNEL_READY == cstate)
3304 if (CADET_TUNNEL_KEY_OK == t->estate)
3306 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3307 send_queued_data (t);
3309 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3311 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3312 GCT_send_ax_kx (t, GNUNET_NO);
3316 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3321 if (CADET_TUNNEL_READY == cstate
3322 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3324 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3325 GCP_stop_search (t->peer);
3331 * Change the tunnel encryption state.
3333 * @param t Tunnel whose encryption state to change, or NULL.
3334 * @param state New encryption state.
3337 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3339 enum CadetTunnelEState old;
3346 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3347 GCP_2s (t->peer), estate2s (old));
3348 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3349 GCP_2s (t->peer), estate2s (t->estate));
3351 /* Send queued data if enc state changes to OK */
3352 if (myid != GCP_get_short_id (t->peer) &&
3353 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3355 send_queued_data (t);
3361 * @brief Check if tunnel has too many connections, and remove one if necessary.
3363 * Currently this means the newest connection, unless it is a direct one.
3364 * Implemented as a task to avoid freeing a connection that is in the middle
3365 * of being created/processed.
3367 * @param cls Closure (Tunnel to check).
3368 * @param tc Task context.
3371 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3373 struct CadetTunnel *t = cls;
3375 t->trim_connections_task = NULL;
3377 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3380 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3382 struct CadetTConnection *iter;
3383 struct CadetTConnection *c;
3385 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3387 if ((iter->created.abs_value_us > c->created.abs_value_us)
3388 && GNUNET_NO == GCC_is_direct (iter->c))
3395 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3397 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3410 * Add a connection to a tunnel.
3413 * @param c Connection.
3416 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3418 struct CadetTConnection *aux;
3420 GNUNET_assert (NULL != c);
3422 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3423 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3424 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3428 aux = GNUNET_new (struct CadetTConnection);
3430 aux->created = GNUNET_TIME_absolute_get ();
3432 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3434 if (CADET_TUNNEL_SEARCHING == t->cstate)
3435 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3437 if (NULL != t->trim_connections_task)
3438 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3443 * Remove a connection from a tunnel.
3446 * @param c Connection.
3449 GCT_remove_connection (struct CadetTunnel *t,
3450 struct CadetConnection *c)
3452 struct CadetTConnection *aux;
3453 struct CadetTConnection *next;
3456 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3457 GCC_2s (c), GCT_2s (t));
3458 for (aux = t->connection_head; aux != NULL; aux = next)
3463 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3468 conns = GCT_count_connections (t);
3470 && NULL == t->destroy_task
3471 && CADET_TUNNEL_SHUTDOWN != t->cstate
3472 && GNUNET_NO == shutting_down)
3474 if (0 == GCT_count_any_connections (t))
3475 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3477 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3480 /* Start new connections if needed */
3481 if (CONNECTIONS_PER_TUNNEL > conns
3482 && NULL == t->destroy_task
3483 && CADET_TUNNEL_SHUTDOWN != t->cstate
3484 && GNUNET_NO == shutting_down)
3486 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3487 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3491 /* If not marked as ready, no change is needed */
3492 if (CADET_TUNNEL_READY != t->cstate)
3495 /* Check if any connection is ready to maintain cstate */
3496 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3497 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3503 * Add a channel to a tunnel.
3506 * @param ch Channel.
3509 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3511 struct CadetTChannel *aux;
3513 GNUNET_assert (NULL != ch);
3515 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3517 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3519 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3524 aux = GNUNET_new (struct CadetTChannel);
3526 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3527 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3529 if (NULL != t->destroy_task)
3531 GNUNET_SCHEDULER_cancel (t->destroy_task);
3532 t->destroy_task = NULL;
3533 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3539 * Remove a channel from a tunnel.
3542 * @param ch Channel.
3545 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3547 struct CadetTChannel *aux;
3549 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3550 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3554 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3555 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3564 * Search for a channel by global ID.
3566 * @param t Tunnel containing the channel.
3567 * @param chid Public channel number.
3569 * @return channel handler, NULL if doesn't exist
3571 struct CadetChannel *
3572 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3574 struct CadetTChannel *iter;
3579 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3581 if (GCCH_get_id (iter->ch) == chid)
3585 return NULL == iter ? NULL : iter->ch;
3590 * @brief Destroy a tunnel and free all resources.
3592 * Should only be called a while after the tunnel has been marked as destroyed,
3593 * in case there is a new channel added to the same peer shortly after marking
3594 * the tunnel. This way we avoid a new public key handshake.
3596 * @param cls Closure (tunnel to destroy).
3597 * @param tc Task context.
3600 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3602 struct CadetTunnel *t = cls;
3603 struct CadetTConnection *iter;
3605 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3606 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3608 LOG (GNUNET_ERROR_TYPE_WARNING,
3609 "Not destroying tunnel, due to shutdown. "
3610 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3613 t->destroy_task = NULL;
3614 t->cstate = CADET_TUNNEL_SHUTDOWN;
3616 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3618 GCC_send_destroy (iter->c);
3625 * Tunnel is empty: destroy it.
3627 * Notifies all connections about the destruction.
3629 * @param t Tunnel to destroy.
3632 GCT_destroy_empty (struct CadetTunnel *t)
3634 if (GNUNET_YES == shutting_down)
3635 return; /* Will be destroyed immediately anyway */
3637 if (NULL != t->destroy_task)
3639 LOG (GNUNET_ERROR_TYPE_WARNING,
3640 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3642 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3644 /* should never happen, tunnel can only become empty once, and the
3645 * task identifier should be NO_TASK (cleaned when the tunnel was created
3646 * or became un-empty)
3651 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3654 // FIXME make delay a config option
3655 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3656 &delayed_destroy, t);
3657 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3658 t, t->destroy_task);
3663 * Destroy tunnel if empty (no more channels).
3665 * @param t Tunnel to destroy if empty.
3668 GCT_destroy_if_empty (struct CadetTunnel *t)
3670 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3671 if (0 < GCT_count_channels (t))
3674 GCT_destroy_empty (t);
3679 * Destroy the tunnel.
3681 * This function does not generate any warning traffic to clients or peers.
3684 * Cancel messages belonging to this tunnel queued to neighbors.
3685 * Free any allocated resources linked to the tunnel.
3687 * @param t The tunnel to destroy.
3690 GCT_destroy (struct CadetTunnel *t)
3692 struct CadetTConnection *iter_c;
3693 struct CadetTConnection *next_c;
3694 struct CadetTChannel *iter_ch;
3695 struct CadetTChannel *next_ch;
3700 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3702 GNUNET_break (GNUNET_YES ==
3703 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3704 GCP_get_id (t->peer), t));
3706 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3708 next_c = iter_c->next;
3709 GCC_destroy (iter_c->c);
3711 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3713 next_ch = iter_ch->next;
3714 GCCH_destroy (iter_ch->ch);
3715 /* Should only happen on shutdown, but it's ok. */
3718 if (NULL != t->destroy_task)
3720 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3721 GNUNET_SCHEDULER_cancel (t->destroy_task);
3722 t->destroy_task = NULL;
3725 if (NULL != t->trim_connections_task)
3727 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3728 t->trim_connections_task);
3729 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3730 t->trim_connections_task = NULL;
3733 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3734 GCP_set_tunnel (t->peer, NULL);
3736 if (NULL != t->rekey_task)
3738 GNUNET_SCHEDULER_cancel (t->rekey_task);
3739 t->rekey_task = NULL;
3741 if (NULL != t->kx_ctx)
3743 if (NULL != t->kx_ctx->finish_task)
3744 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3745 GNUNET_free (t->kx_ctx);
3756 * @brief Use the given path for the tunnel.
3757 * Update the next and prev hops (and RCs).
3758 * (Re)start the path refresh in case the tunnel is locally owned.
3760 * @param t Tunnel to update.
3761 * @param p Path to use.
3763 * @return Connection created.
3765 struct CadetConnection *
3766 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3768 struct CadetConnection *c;
3769 struct GNUNET_CADET_Hash cid;
3770 unsigned int own_pos;
3772 if (NULL == t || NULL == p)
3778 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3784 for (own_pos = 0; own_pos < p->length; own_pos++)
3786 if (p->peers[own_pos] == myid)
3789 if (own_pos >= p->length)
3791 GNUNET_break_op (0);
3795 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3796 c = GCC_new (&cid, t, p, own_pos);
3799 /* Path was flawed */
3802 GCT_add_connection (t, c);
3808 * Count all created connections of a tunnel. Not necessarily ready connections!
3810 * @param t Tunnel on which to count.
3812 * @return Number of connections created, either being established or ready.
3815 GCT_count_any_connections (struct CadetTunnel *t)
3817 struct CadetTConnection *iter;
3823 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3831 * Count established (ready) connections of a tunnel.
3833 * @param t Tunnel on which to count.
3835 * @return Number of connections.
3838 GCT_count_connections (struct CadetTunnel *t)
3840 struct CadetTConnection *iter;
3846 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3847 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3855 * Count channels of a tunnel.
3857 * @param t Tunnel on which to count.
3859 * @return Number of channels.
3862 GCT_count_channels (struct CadetTunnel *t)
3864 struct CadetTChannel *iter;
3867 for (count = 0, iter = t->channel_head;
3869 iter = iter->next, count++) /* skip */;
3876 * Get the connectivity state of a tunnel.
3880 * @return Tunnel's connectivity state.
3882 enum CadetTunnelCState
3883 GCT_get_cstate (struct CadetTunnel *t)
3888 return (enum CadetTunnelCState) -1;
3895 * Get the encryption state of a tunnel.
3899 * @return Tunnel's encryption state.
3901 enum CadetTunnelEState
3902 GCT_get_estate (struct CadetTunnel *t)
3907 return (enum CadetTunnelEState) -1;
3913 * Get the maximum buffer space for a tunnel towards a local client.
3917 * @return Biggest buffer space offered by any channel in the tunnel.
3920 GCT_get_channels_buffer (struct CadetTunnel *t)
3922 struct CadetTChannel *iter;
3923 unsigned int buffer;
3924 unsigned int ch_buf;
3926 if (NULL == t->channel_head)
3928 /* Probably getting buffer for a channel create/handshake. */
3929 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3934 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3936 ch_buf = get_channel_buffer (iter);
3937 if (ch_buf > buffer)
3945 * Get the total buffer space for a tunnel for P2P traffic.
3949 * @return Buffer space offered by all connections in the tunnel.
3952 GCT_get_connections_buffer (struct CadetTunnel *t)
3954 struct CadetTConnection *iter;
3955 unsigned int buffer;
3957 if (GNUNET_NO == is_ready (t))
3959 if (count_queued_data (t) > 3)
3966 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3968 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3972 buffer += get_connection_buffer (iter);
3980 * Get the tunnel's destination.
3984 * @return ID of the destination peer.
3986 const struct GNUNET_PeerIdentity *
3987 GCT_get_destination (struct CadetTunnel *t)
3989 return GCP_get_id (t->peer);
3994 * Get the tunnel's next free global channel ID.
3998 * @return GID of a channel free to use.
4001 GCT_get_next_chid (struct CadetTunnel *t)
4003 CADET_ChannelNumber chid;
4004 CADET_ChannelNumber mask;
4007 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
4008 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
4009 * If peer's ID is bigger, start at 0x4... bit 30 = 1
4011 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4016 t->next_chid |= mask;
4018 while (NULL != GCT_get_channel (t, t->next_chid))
4020 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4021 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4022 t->next_chid |= mask;
4024 chid = t->next_chid;
4025 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4026 t->next_chid |= mask;
4033 * Send ACK on one or more channels due to buffer in connections.
4035 * @param t Channel which has some free buffer space.
4038 GCT_unchoke_channels (struct CadetTunnel *t)
4040 struct CadetTChannel *iter;
4041 unsigned int buffer;
4042 unsigned int channels = GCT_count_channels (t);
4043 unsigned int choked_n;
4044 struct CadetChannel *choked[channels];
4046 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4047 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4048 if (NULL != t->channel_head)
4049 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4051 /* Get buffer space */
4052 buffer = GCT_get_connections_buffer (t);
4058 /* Count and remember choked channels */
4060 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4062 if (GNUNET_NO == get_channel_allowed (iter))
4064 choked[choked_n++] = iter->ch;
4068 /* Unchoke random channels */
4069 while (0 < buffer && 0 < choked_n)
4071 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4073 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4076 choked[r] = choked[choked_n];
4082 * Send ACK on one or more connections due to buffer space to the client.
4084 * Iterates all connections of the tunnel and sends ACKs appropriately.
4089 GCT_send_connection_acks (struct CadetTunnel *t)
4091 struct CadetTConnection *iter;
4094 uint32_t allow_per_connection;
4096 unsigned int buffer;
4098 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4107 if (CADET_TUNNEL_READY != t->cstate)
4110 buffer = GCT_get_channels_buffer (t);
4111 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4113 /* Count connections, how many messages are already allowed */
4114 cs = GCT_count_connections (t);
4115 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4117 allowed += get_connection_allowed (iter);
4119 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4121 /* Make sure there is no overflow */
4122 if (allowed > buffer)
4125 /* Authorize connections to send more data */
4126 to_allow = buffer - allowed;
4128 for (iter = t->connection_head;
4129 NULL != iter && to_allow > 0;
4132 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4133 || get_connection_allowed (iter) > 64 / 3)
4137 allow_per_connection = to_allow/cs;
4138 to_allow -= allow_per_connection;
4140 GCC_allow (iter->c, allow_per_connection,
4141 GCC_is_origin (iter->c, GNUNET_NO));
4146 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4147 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4153 * Cancel a previously sent message while it's in the queue.
4155 * ONLY can be called before the continuation given to the send function
4156 * is called. Once the continuation is called, the message is no longer in the
4159 * @param q Handle to the queue.
4162 GCT_cancel (struct CadetTunnelQueue *q)
4167 /* tun_message_sent() will be called and free q */
4169 else if (NULL != q->tqd)
4171 unqueue_data (q->tqd);
4173 if (NULL != q->cont)
4174 q->cont (q->cont_cls, NULL, q, 0, 0);
4185 * Sends an already built message on a tunnel, encrypting it and
4186 * choosing the best connection if not provided.
4188 * @param message Message to send. Function modifies it.
4189 * @param t Tunnel on which this message is transmitted.
4190 * @param c Connection to use (autoselect if NULL).
4191 * @param force Force the tunnel to take the message (buffer overfill).
4192 * @param cont Continuation to call once message is really sent.
4193 * @param cont_cls Closure for @c cont.
4195 * @return Handle to cancel message. NULL if @c cont is NULL.
4197 struct CadetTunnelQueue *
4198 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4199 struct CadetTunnel *t, struct CadetConnection *c,
4200 int force, GCT_sent cont, void *cont_cls)
4202 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4207 * Send an Axolotl KX message.
4209 * @param t Tunnel on which to send it.
4210 * @param force_reply Force the other peer to reply with a KX message.
4213 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4215 struct GNUNET_CADET_AX_KX msg;
4217 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4218 if (NULL != t->ephm_h)
4220 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4224 msg.header.size = htons (sizeof (msg));
4225 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4226 msg.force_reply = htonl (force_reply);
4227 msg.permanent_key = ax_identity.permanent_key;
4228 msg.purpose = ax_identity.purpose;
4229 msg.signature = ax_identity.signature;
4230 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4231 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4233 t->ephm_h = send_kx (t, &msg.header);
4234 if (CADET_TUNNEL_KEY_OK != t->estate)
4235 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4240 * Sends an already built and encrypted message on a tunnel, choosing the best
4241 * connection. Useful for re-queueing messages queued on a destroyed connection.
4243 * @param message Message to send. Function modifies it.
4244 * @param t Tunnel on which this message is transmitted.
4247 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4248 struct CadetTunnel *t)
4250 struct CadetConnection *c;
4253 c = tunnel_get_connection (t);
4256 /* TODO queue in tunnel, marked as encrypted */
4257 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4260 fwd = GCC_is_origin (c, GNUNET_YES);
4261 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4262 GNUNET_YES, NULL, NULL));
4267 * Is the tunnel directed towards the local peer?
4271 * @return #GNUNET_YES if it is loopback.
4274 GCT_is_loopback (const struct CadetTunnel *t)
4276 return (myid == GCP_get_short_id (t->peer));
4281 * Is the tunnel this path already?
4286 * @return #GNUNET_YES a connection uses this path.
4289 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4291 struct CadetTConnection *iter;
4293 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4294 if (path_equivalent (GCC_get_path (iter->c), p))
4302 * Get a cost of a path for a tunnel considering existing connections.
4305 * @param path Candidate path.
4307 * @return Cost of the path (path length + number of overlapping nodes)
4310 GCT_get_path_cost (const struct CadetTunnel *t,
4311 const struct CadetPeerPath *path)
4313 struct CadetTConnection *iter;
4314 const struct CadetPeerPath *aux;
4315 unsigned int overlap;
4323 GNUNET_assert (NULL != t);
4325 for (i = 0; i < path->length; i++)
4327 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4329 aux = GCC_get_path (iter->c);
4333 for (j = 0; j < aux->length; j++)
4335 if (path->peers[i] == aux->peers[j])
4343 return path->length + overlap;
4348 * Get the static string for the peer this tunnel is directed.
4352 * @return Static string the destination peer's ID.
4355 GCT_2s (const struct CadetTunnel *t)
4360 return GCP_2s (t->peer);
4364 /******************************************************************************/
4365 /***************************** INFO/DEBUG *******************************/
4366 /******************************************************************************/
4369 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4371 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4372 struct CadetTunnelSkippedKey *iter;
4375 LOG2 (level, "TTT RK\t %s\n",
4376 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4378 LOG2 (level, "TTT HKs\t %s\n",
4379 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4380 LOG2 (level, "TTT HKr\t %s\n",
4381 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4382 LOG2 (level, "TTT NHKs\t %s\n",
4383 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4384 LOG2 (level, "TTT NHKr\t %s\n",
4385 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4387 LOG2 (level, "TTT CKs\t %s\n",
4388 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4389 LOG2 (level, "TTT CKr\t %s\n",
4390 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4392 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
4393 LOG2 (level, "TTT DHIs\t %s\n",
4394 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4395 LOG2 (level, "TTT DHIr\t %s\n",
4396 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
4397 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4398 LOG2 (level, "TTT DHRs\t %s\n",
4399 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4400 LOG2 (level, "TTT DHRr\t %s\n",
4401 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4403 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4404 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4405 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4407 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4409 LOG2 (level, "TTT HK\t %s\n",
4410 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4411 LOG2 (level, "TTT MK\t %s\n",
4412 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4417 * Log all possible info about the tunnel state.
4419 * @param t Tunnel to debug.
4420 * @param level Debug level to use.
4423 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4425 struct CadetTChannel *iterch;
4426 struct CadetTConnection *iterc;
4429 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4431 __FILE__, __FUNCTION__, __LINE__);
4435 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4436 LOG2 (level, "TTT cstate %s, estate %s\n",
4437 cstate2s (t->cstate), estate2s (t->estate));
4438 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4439 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4440 #if DUMP_KEYS_TO_STDERR
4441 if (CADET_Axolotl == t->enc_type)
4443 ax_debug (t->ax, level);
4447 LOG2 (level, "TTT my EPHM\t %s\n",
4448 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4449 LOG2 (level, "TTT peers EPHM:\t %s\n",
4450 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4451 LOG2 (level, "TTT ENC key:\t %s\n",
4452 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4453 LOG2 (level, "TTT DEC key:\t %s\n",
4454 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4457 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4458 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4459 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4460 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4464 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4465 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4467 LOG2 (level, "TTT channels:\n");
4468 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4470 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4473 LOG2 (level, "TTT connections:\n");
4474 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4476 GCC_debug (iterc->c, level);
4479 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4484 * Iterate all tunnels.
4486 * @param iter Iterator.
4487 * @param cls Closure for @c iter.
4490 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4492 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4497 * Count all tunnels.
4499 * @return Number of tunnels to remote peers kept by this peer.
4502 GCT_count_all (void)
4504 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4509 * Iterate all connections of a tunnel.
4511 * @param t Tunnel whose connections to iterate.
4512 * @param iter Iterator.
4513 * @param cls Closure for @c iter.
4516 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4518 struct CadetTConnection *ct;
4520 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4526 * Iterate all channels of a tunnel.
4528 * @param t Tunnel whose channels to iterate.
4529 * @param iter Iterator.
4530 * @param cls Closure for @c iter.
4533 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4535 struct CadetTChannel *cht;
4537 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4538 iter (cls, cht->ch);