2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 #define MIN_TUNNEL_BUFFER 8
47 #define MAX_TUNNEL_BUFFER 64
48 #define MAX_SKIPPED_KEYS 64
49 #define MAX_KEY_GAP 256
50 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
51 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
54 /******************************************************************************/
55 /******************************** STRUCTS **********************************/
56 /******************************************************************************/
60 struct CadetTChannel *next;
61 struct CadetTChannel *prev;
62 struct CadetChannel *ch;
67 * Connection list and metadata.
69 struct CadetTConnection
74 struct CadetTConnection *next;
79 struct CadetTConnection *prev;
84 struct CadetConnection *c;
87 * Creation time, to keep oldest connection alive.
89 struct GNUNET_TIME_Absolute created;
92 * Connection throughput, to keep fastest connection alive.
98 * Structure used during a Key eXchange.
100 struct CadetTunnelKXCtx
103 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
104 * end before the key exchange is finished or times out.
106 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
109 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
110 * the other end before the key exchange started.
112 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
115 * Same as @c e_key_old, for the case of two simultaneous KX.
116 * This can happen if cadet decides to start a re-key while the peer has also
117 * started its re-key (due to network delay this is impossible to avoid).
118 * In this case, the key material generated with the peer's old ephemeral
119 * *might* (but doesn't have to) be incorrect.
120 * Since no more than two re-keys can happen simultaneously, this is enough.
122 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
125 * Same as @c d_key_old, for the case described in @c e_key_old2.
127 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
130 * Challenge to send and expect in the PONG.
135 * When the rekey started. One minute after this the new key will be used.
137 struct GNUNET_TIME_Absolute rekey_start_time;
140 * Task for delayed destruction of the Key eXchange context, to allow delayed
141 * messages with the old key to be decrypted successfully.
143 struct GNUNET_SCHEDULER_Task *finish_task;
147 * Encryption systems possible.
149 enum CadetTunnelEncryption
152 * Default Axolotl system.
157 * Fallback OTR-style encryption.
163 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
165 struct CadetTunnelSkippedKey
170 struct CadetTunnelSkippedKey *next;
175 struct CadetTunnelSkippedKey *prev;
178 * When was this key stored (for timeout).
180 struct GNUNET_TIME_Absolute timestamp;
185 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
190 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
193 * Key number for a given HK.
200 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
202 struct CadetTunnelAxolotl
205 * A (double linked) list of stored message keys and associated header keys
206 * for "skipped" messages, i.e. messages that have not been
207 * received despite the reception of more recent messages, (head).
209 struct CadetTunnelSkippedKey *skipped_head;
212 * Skipped messages' keys DLL, tail.
214 struct CadetTunnelSkippedKey *skipped_tail;
217 * Elements in @a skipped_head <-> @a skipped_tail.
219 unsigned int skipped;
222 * 32-byte root key which gets updated by DH ratchet.
224 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
227 * 32-byte header key (send).
229 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
232 * 32-byte header key (recv)
234 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
237 * 32-byte next header key (send).
239 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
242 * 32-byte next header key (recv).
244 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
247 * 32-byte chain keys (used for forward-secrecy updating, send).
249 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
252 * 32-byte chain keys (used for forward-secrecy updating, recv).
254 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
257 * ECDH for key exchange (A0 / B0).
259 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
262 * ECDH Ratchet key (send).
264 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
267 * ECDH Ratchet key (recv).
269 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
272 * Message number (reset to 0 with each new ratchet, next message to send).
277 * Message number (reset to 0 with each new ratchet, next message to recv).
282 * Previous message numbers (# of msgs sent under prev ratchet)
287 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
292 * Number of messages recieved since our last ratchet advance.
293 * - If this counter = 0, we cannot send a new ratchet key in next msg.
294 * - If this counter > 0, we can (but don't yet have to) send a new key.
296 unsigned int ratchet_allowed;
299 * Number of messages recieved since our last ratchet advance.
300 * - If this counter = 0, we cannot send a new ratchet key in next msg.
301 * - If this counter > 0, we can (but don't yet have to) send a new key.
303 unsigned int ratchet_counter;
306 * When does this ratchet expire and a new one is triggered.
308 struct GNUNET_TIME_Absolute ratchet_expiration;
312 * Struct containing all information regarding a tunnel to a peer.
317 * Endpoint of the tunnel.
319 struct CadetPeer *peer;
322 * Type of encryption used in the tunnel.
324 enum CadetTunnelEncryption enc_type;
329 struct CadetTunnelAxolotl *ax;
332 * State of the tunnel connectivity.
334 enum CadetTunnelCState cstate;
337 * State of the tunnel encryption.
339 enum CadetTunnelEState estate;
342 * Key eXchange context.
344 struct CadetTunnelKXCtx *kx_ctx;
347 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
350 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
353 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
355 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
358 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
360 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
363 * Task to start the rekey process.
365 struct GNUNET_SCHEDULER_Task * rekey_task;
368 * Paths that are actively used to reach the destination peer.
370 struct CadetTConnection *connection_head;
371 struct CadetTConnection *connection_tail;
374 * Next connection number.
379 * Channels inside this tunnel.
381 struct CadetTChannel *channel_head;
382 struct CadetTChannel *channel_tail;
385 * Channel ID for the next created channel.
387 CADET_ChannelNumber next_chid;
390 * Destroy flag: if true, destroy on last message.
392 struct GNUNET_SCHEDULER_Task * destroy_task;
395 * Queued messages, to transmit once tunnel gets connected.
397 struct CadetTunnelDelayed *tq_head;
398 struct CadetTunnelDelayed *tq_tail;
401 * Task to trim connections if too many are present.
403 struct GNUNET_SCHEDULER_Task * trim_connections_task;
406 * Ephemeral message in the queue (to avoid queueing more than one).
408 struct CadetConnectionQueue *ephm_h;
411 * Pong message in the queue.
413 struct CadetConnectionQueue *pong_h;
418 * Struct used to save messages in a non-ready tunnel to send once connected.
420 struct CadetTunnelDelayed
425 struct CadetTunnelDelayed *next;
426 struct CadetTunnelDelayed *prev;
431 struct CadetTunnel *t;
434 * Tunnel queue given to the channel to cancel request. Update on send_queued.
436 struct CadetTunnelQueue *tq;
441 /* struct GNUNET_MessageHeader *msg; */
446 * Handle for messages queued but not yet sent.
448 struct CadetTunnelQueue
451 * Connection queue handle, to cancel if necessary.
453 struct CadetConnectionQueue *cq;
456 * Handle in case message hasn't been given to a connection yet.
458 struct CadetTunnelDelayed *tqd;
461 * Continuation to call once sent.
466 * Closure for @c cont.
472 /******************************************************************************/
473 /******************************* GLOBALS ***********************************/
474 /******************************************************************************/
477 * Global handle to the statistics service.
479 extern struct GNUNET_STATISTICS_Handle *stats;
482 * Local peer own ID (memory efficient handle).
484 extern GNUNET_PEER_Id myid;
487 * Local peer own ID (full value).
489 extern struct GNUNET_PeerIdentity my_full_id;
493 * Don't try to recover tunnels if shutting down.
495 extern int shutting_down;
499 * Set of all tunnels, in order to trigger a new exchange on rekey.
500 * Indexed by peer's ID.
502 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
505 * Default TTL for payload packets.
507 static unsigned long long default_ttl;
510 * Own Peer ID private key.
512 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
515 /******************************** AXOLOTL ************************************/
518 * How many messages are needed to trigger a ratchet advance.
520 static unsigned long long ratchet_messages;
523 * How long until we trigger a ratched advance.
525 static struct GNUNET_TIME_Relative ratchet_time;
528 /******************************** OTR ***********************************/
531 * Own global OTR ephemeral private key.
533 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
536 * Cached message used to perform a OTR key exchange.
538 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
541 * Task to generate a new OTR ephemeral key.
543 static struct GNUNET_SCHEDULER_Task *rekey_task;
548 static struct GNUNET_TIME_Relative rekey_period;
551 /******************************************************************************/
552 /******************************** STATIC ***********************************/
553 /******************************************************************************/
556 * Get string description for tunnel connectivity state.
558 * @param cs Tunnel state.
560 * @return String representation.
563 cstate2s (enum CadetTunnelCState cs)
569 case CADET_TUNNEL_NEW:
570 return "CADET_TUNNEL_NEW";
571 case CADET_TUNNEL_SEARCHING:
572 return "CADET_TUNNEL_SEARCHING";
573 case CADET_TUNNEL_WAITING:
574 return "CADET_TUNNEL_WAITING";
575 case CADET_TUNNEL_READY:
576 return "CADET_TUNNEL_READY";
577 case CADET_TUNNEL_SHUTDOWN:
578 return "CADET_TUNNEL_SHUTDOWN";
580 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
588 * Get string description for tunnel encryption state.
590 * @param es Tunnel state.
592 * @return String representation.
595 estate2s (enum CadetTunnelEState es)
601 case CADET_TUNNEL_KEY_UNINITIALIZED:
602 return "CADET_TUNNEL_KEY_UNINITIALIZED";
603 case CADET_TUNNEL_KEY_SENT:
604 return "CADET_TUNNEL_KEY_SENT";
605 case CADET_TUNNEL_KEY_PING:
606 return "CADET_TUNNEL_KEY_PING";
607 case CADET_TUNNEL_KEY_OK:
608 return "CADET_TUNNEL_KEY_OK";
609 case CADET_TUNNEL_KEY_REKEY:
610 return "CADET_TUNNEL_KEY_REKEY";
612 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
620 * @brief Check if tunnel is ready to send traffic.
622 * Tunnel must be connected and with encryption correctly set up.
624 * @param t Tunnel to check.
626 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
629 is_ready (struct CadetTunnel *t)
635 conn_ok = CADET_TUNNEL_READY == t->cstate;
636 enc_ok = CADET_TUNNEL_KEY_OK == t->estate
637 || CADET_TUNNEL_KEY_REKEY == t->estate
638 || (CADET_TUNNEL_KEY_PING == t->estate
639 && CADET_Axolotl == t->enc_type);
640 ready = conn_ok && enc_ok;
641 ready = ready || GCT_is_loopback (t);
647 * Check if a key is invalid (NULL pointer or all 0)
649 * @param key Key to check.
651 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
654 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
656 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
661 memset (&null_key, 0, sizeof (null_key));
662 if (0 == memcmp (key, &null_key, sizeof (null_key)))
669 * Ephemeral key message purpose size.
671 * @return Size of the part of the ephemeral key message that must be signed.
674 ephemeral_purpose_size (void)
676 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
677 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
678 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
679 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
680 sizeof (struct GNUNET_PeerIdentity);
685 * Size of the encrypted part of a ping message.
687 * @return Size of the encrypted part of a ping message.
690 ping_encryption_size (void)
692 return sizeof (uint32_t);
697 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
699 * @param tch Tunnel's channel handle.
701 * @return Amount of messages the channel can still buffer towards the client.
704 get_channel_buffer (const struct CadetTChannel *tch)
708 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
709 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
711 return GCCH_get_buffer (tch->ch, fwd);
716 * Get the channel's allowance status.
718 * @param tch Tunnel's channel handle.
720 * @return #GNUNET_YES if we allowed the client to send data to us.
723 get_channel_allowed (const struct CadetTChannel *tch)
727 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
728 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
730 return GCCH_get_allowed (tch->ch, fwd);
735 * Get the connection's buffer.
737 * @param tc Tunnel's connection handle.
739 * @return Amount of messages the connection can still buffer.
742 get_connection_buffer (const struct CadetTConnection *tc)
746 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
747 fwd = GCC_is_origin (tc->c, GNUNET_YES);
749 return GCC_get_buffer (tc->c, fwd);
754 * Get the connection's allowance.
756 * @param tc Tunnel's connection handle.
758 * @return Amount of messages we have allowed the next peer to send us.
761 get_connection_allowed (const struct CadetTConnection *tc)
765 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
766 fwd = GCC_is_origin (tc->c, GNUNET_YES);
768 return GCC_get_allowed (tc->c, fwd);
773 * Check that a ephemeral key message s well formed and correctly signed.
775 * @param t Tunnel on which the message came.
776 * @param msg The ephemeral key message.
778 * @return #GNUNET_OK if message is fine, #GNUNET_SYSERR otherwise.
781 check_ephemeral (struct CadetTunnel *t,
782 const struct GNUNET_CADET_KX_Ephemeral *msg)
784 /* Check message size */
785 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
787 /* This is probably an old "MESH" version. */
788 LOG (GNUNET_ERROR_TYPE_INFO,
789 "Expected ephemeral of size %u, got %u\n",
790 sizeof (struct GNUNET_CADET_KX_Ephemeral),
791 ntohs (msg->header.size));
792 return GNUNET_SYSERR;
795 /* Check signature size */
796 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
798 LOG (GNUNET_ERROR_TYPE_WARNING,
799 "Expected signature purpose of size %u, got %u\n",
800 ephemeral_purpose_size (),
801 ntohs (msg->purpose.size));
802 return GNUNET_SYSERR;
806 if (0 != memcmp (&msg->origin_identity,
807 GCP_get_id (t->peer),
808 sizeof (struct GNUNET_PeerIdentity)))
810 LOG (GNUNET_ERROR_TYPE_WARNING,
811 "Unexpected origin, got %s\n",
812 GNUNET_i2s (&msg->origin_identity));
813 return GNUNET_SYSERR;
816 /* Check signature */
818 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
821 &msg->origin_identity.public_key))
823 LOG (GNUNET_ERROR_TYPE_WARNING, "Signature invalid\n");
824 return GNUNET_SYSERR;
832 * Select the best key to use for encryption (send), based on KX status.
834 * Normally, return the current key. If there is a KX in progress and the old
835 * key is fresh enough, return the old key.
837 * @param t Tunnel to choose the key from.
839 * @return The optimal key to encrypt/hmac outgoing traffic.
841 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
842 select_key (const struct CadetTunnel *t)
844 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
846 if (NULL != t->kx_ctx
847 && NULL == t->kx_ctx->finish_task)
849 struct GNUNET_TIME_Relative age;
851 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
852 LOG (GNUNET_ERROR_TYPE_DEBUG,
853 " key exchange in progress, started %s ago\n",
854 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
855 // FIXME make duration of old keys configurable
856 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
858 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
859 key = &t->kx_ctx->e_key_old;
863 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
869 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
877 * Create a new Axolotl ephemeral (ratchet) key.
882 new_ephemeral (struct CadetTunnel *t)
884 GNUNET_free_non_null (t->ax->DHRs);
885 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
886 #if DUMP_KEYS_TO_STDERR
888 struct GNUNET_CRYPTO_EcdhePublicKey pub;
889 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &pub);
890 LOG (GNUNET_ERROR_TYPE_DEBUG, " new DHRs generated: pub %s\n",
891 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
900 * @param plaintext Content to HMAC.
901 * @param size Size of @c plaintext.
902 * @param iv Initialization vector for the message.
903 * @param key Key to use.
904 * @param hmac[out] Destination to store the HMAC.
907 t_hmac (const void *plaintext, size_t size,
908 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
909 struct GNUNET_CADET_Hash *hmac)
911 static const char ctx[] = "cadet authentication key";
912 struct GNUNET_CRYPTO_AuthKey auth_key;
913 struct GNUNET_HashCode hash;
915 #if DUMP_KEYS_TO_STDERR
916 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
917 GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
919 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
924 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
925 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
926 memcpy (hmac, &hash, sizeof (*hmac));
931 * Encrypt daforce_newest_keyta with the tunnel key.
933 * @param t Tunnel whose key to use.
934 * @param dst Destination for the encrypted data.
935 * @param src Source of the plaintext. Can overlap with @c dst.
936 * @param size Size of the plaintext.
937 * @param iv Initialization Vector to use.
938 * @param force_newest_key Force the use of the newest key, otherwise
939 * CADET will use the old key when allowed.
940 * This can happen in the case when a KX is going on
941 * and the old one hasn't expired.
944 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
945 size_t size, uint32_t iv, int force_newest_key)
947 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
948 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
951 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
953 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
954 #if DUMP_KEYS_TO_STDERR
955 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
956 GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
958 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
959 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
960 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
961 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
970 * @param key Key to use.
971 * @param hash[out] Resulting HMAC.
972 * @param source Source key material (data to HMAC).
973 * @param len Length of @a source.
976 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
977 struct GNUNET_HashCode *hash,
978 void *source, unsigned int len)
980 static const char ctx[] = "axolotl HMAC-HASH";
981 struct GNUNET_CRYPTO_AuthKey auth_key;
983 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
986 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
991 * Derive a key from a HMAC-HASH.
993 * @param key Key to use for the HMAC.
994 * @param out Key to generate.
995 * @param source Source key material (data to HMAC).
996 * @param len Length of @a source.
999 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1000 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
1001 void *source, unsigned int len)
1003 static const char ctx[] = "axolotl derive key";
1004 struct GNUNET_HashCode h;
1006 t_ax_hmac_hash (key, &h, source, len);
1007 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
1008 &h, sizeof (h), NULL);
1013 * Encrypt data with the axolotl tunnel key.
1015 * @param t Tunnel whose key to use.
1016 * @param dst Destination for the encrypted data.
1017 * @param src Source of the plaintext. Can overlap with @c dst.
1018 * @param size Size of the plaintext.
1020 * @return Size of the encrypted data.
1023 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1025 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1026 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1027 struct CadetTunnelAxolotl *ax;
1030 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
1034 ax->ratchet_counter++;
1035 if (GNUNET_YES == ax->ratchet_allowed
1036 && (ratchet_messages <= ax->ratchet_counter
1037 || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
1039 ax->ratchet_flag = GNUNET_YES;
1042 if (GNUNET_YES == ax->ratchet_flag)
1044 /* Advance ratchet */
1045 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1046 struct GNUNET_HashCode dh;
1047 struct GNUNET_HashCode hmac;
1048 static const char ctx[] = "axolotl ratchet";
1053 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1054 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1055 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1056 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1057 &hmac, sizeof (hmac), NULL);
1064 ax->ratchet_flag = GNUNET_NO;
1065 ax->ratchet_allowed = GNUNET_NO;
1066 ax->ratchet_counter = 0;
1067 ax->ratchet_expiration =
1068 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1071 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1072 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1074 #if DUMP_KEYS_TO_STDERR
1075 LOG (GNUNET_ERROR_TYPE_DEBUG, " CKs: %s\n",
1076 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
1077 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1078 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
1081 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1083 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1085 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1092 * Decrypt data with the axolotl tunnel key.
1094 * @param t Tunnel whose key to use.
1095 * @param dst Destination for the decrypted data.
1096 * @param src Source of the ciphertext. Can overlap with @c dst.
1097 * @param size Size of the ciphertext.
1099 * @return Size of the decrypted data.
1102 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1104 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1105 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1106 struct CadetTunnelAxolotl *ax;
1109 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1113 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1114 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1116 #if DUMP_KEYS_TO_STDERR
1117 LOG (GNUNET_ERROR_TYPE_DEBUG, " CKr: %s\n",
1118 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
1119 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1120 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
1123 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1124 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1125 GNUNET_assert (out_size == size);
1127 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1129 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1136 * Encrypt header with the axolotl header key.
1138 * @param t Tunnel whose key to use.
1139 * @param msg Message whose header to encrypt.
1142 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1144 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1145 struct CadetTunnelAxolotl *ax;
1148 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1151 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1153 #if DUMP_KEYS_TO_STDERR
1154 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1155 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
1158 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1159 &ax->HKs, &iv, &msg->Ns);
1161 GNUNET_assert (AX_HEADER_SIZE == out_size);
1163 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1168 * Decrypt header with the current axolotl header key.
1170 * @param t Tunnel whose current ax HK to use.
1171 * @param src Message whose header to decrypt.
1172 * @param dst Where to decrypt header to.
1175 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1176 struct GNUNET_CADET_AX *dst)
1178 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1179 struct CadetTunnelAxolotl *ax;
1182 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1185 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1187 #if DUMP_KEYS_TO_STDERR
1188 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1189 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
1192 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1193 &ax->HKr, &iv, &dst->Ns);
1195 GNUNET_assert (AX_HEADER_SIZE == out_size);
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt end\n");
1202 * Decrypt and verify data with the appropriate tunnel key.
1204 * @param key Key to use.
1205 * @param dst Destination for the plaintext.
1206 * @param src Source of the encrypted data. Can overlap with @c dst.
1207 * @param size Size of the encrypted data.
1208 * @param iv Initialization Vector to use.
1210 * @return Size of the decrypted data, -1 if an error was encountered.
1213 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1214 void *dst, const void *src, size_t size, uint32_t iv)
1216 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1219 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1220 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1221 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1222 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1223 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1224 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1231 * Decrypt and verify data with the most recent tunnel key.
1233 * @param t Tunnel whose key to use.
1234 * @param dst Destination for the plaintext.
1235 * @param src Source of the encrypted data. Can overlap with @c dst.
1236 * @param size Size of the encrypted data.
1237 * @param iv Initialization Vector to use.
1239 * @return Size of the decrypted data, -1 if an error was encountered.
1242 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1243 size_t size, uint32_t iv)
1247 #if DUMP_KEYS_TO_STDERR
1248 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1249 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
1251 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1253 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1254 LOG (GNUNET_ERROR_TYPE_WARNING,
1255 "got data on %s without a valid key\n",
1257 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1261 out_size = decrypt (&t->d_key, dst, src, size, iv);
1268 * Decrypt and verify data with the appropriate tunnel key and verify that the
1269 * data has not been altered since it was sent by the remote peer.
1271 * @param t Tunnel whose key to use.
1272 * @param dst Destination for the plaintext.
1273 * @param src Source of the encrypted data. Can overlap with @c dst.
1274 * @param size Size of the encrypted data.
1275 * @param iv Initialization Vector to use.
1276 * @param msg_hmac HMAC of the message, cannot be NULL.
1278 * @return Size of the decrypted data, -1 if an error was encountered.
1281 t_decrypt_and_validate (struct CadetTunnel *t,
1282 void *dst, const void *src,
1283 size_t size, uint32_t iv,
1284 const struct GNUNET_CADET_Hash *msg_hmac)
1286 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1287 struct GNUNET_CADET_Hash hmac;
1290 /* Try primary (newest) key */
1292 decrypted_size = decrypt (key, dst, src, size, iv);
1293 t_hmac (src, size, iv, key, &hmac);
1294 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1295 return decrypted_size;
1297 /* If no key exchange is going on, we just failed. */
1298 if (NULL == t->kx_ctx)
1300 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1301 "Failed checksum validation on tunnel %s with no KX\n",
1303 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1307 /* Try secondary key, from previous KX period. */
1308 key = &t->kx_ctx->d_key_old;
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 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1315 key = &t->kx_ctx->d_key_old2;
1316 decrypted_size = decrypt (key, dst, src, size, iv);
1317 t_hmac (src, size, iv, key, &hmac);
1318 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1319 return decrypted_size;
1321 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1322 "Failed checksum validation on tunnel %s with KX\n",
1324 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1330 * Decrypt and verify data with the appropriate tunnel key and verify that the
1331 * data has not been altered since it was sent by the remote peer.
1333 * @param t Tunnel whose key to use.
1334 * @param dst Destination for the plaintext.
1335 * @param src Source of the message. Can overlap with @c dst.
1336 * @param size Size of the message.
1338 * @return Size of the decrypted data, -1 if an error was encountered.
1341 try_old_ax_keys (struct CadetTunnel *t, void *dst,
1342 const struct GNUNET_CADET_AX *src, size_t size)
1344 struct CadetTunnelSkippedKey *key;
1345 struct GNUNET_CADET_Hash *hmac;
1346 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1347 struct GNUNET_CADET_AX plaintext_header;
1348 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
1354 LOG (GNUNET_ERROR_TYPE_DEBUG, "Trying old keys\n");
1355 hmac = &plaintext_header.hmac;
1356 esize = size - sizeof (struct GNUNET_CADET_AX);
1358 /* Find a correct Header Key */
1359 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1361 #if DUMP_KEYS_TO_STDERR
1362 LOG (GNUNET_ERROR_TYPE_DEBUG, " Trying hmac with key %s\n",
1363 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->HK));
1365 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &key->HK, hmac);
1366 if (0 == memcmp (hmac, &src->hmac, sizeof (*hmac)))
1368 LOG (GNUNET_ERROR_TYPE_DEBUG, " hmac correct\n");
1369 valid_HK = &key->HK;
1376 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
1377 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1378 len = size - sizeof (struct GNUNET_CADET_AX);
1379 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1381 /* Decrypt header */
1382 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->HK, NULL, 0, NULL);
1383 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1384 &key->HK, &iv, &plaintext_header.Ns);
1385 GNUNET_assert (AX_HEADER_SIZE == res);
1386 LOG (GNUNET_ERROR_TYPE_DEBUG, " Message %u, previous: %u\n",
1387 ntohl (plaintext_header.Ns), ntohl (plaintext_header.PNs));
1389 /* Find the correct Message Key */
1390 N = ntohl (plaintext_header.Ns);
1391 while (NULL != key && N != key->Kn)
1393 if (NULL == key || 0 != memcmp (&key->HK, valid_HK, sizeof (*valid_HK)))
1396 #if DUMP_KEYS_TO_STDERR
1397 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with skipped key %s\n",
1398 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->HK));
1399 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %u: %s\n",
1400 key->Kn, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1403 /* Decrypt payload */
1404 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1405 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, dst);
1408 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1410 GNUNET_free (key); /* GNUNET_free overwrites memory with 0xbaadf00d */
1417 * Delete a key from the list of skipped keys.
1419 * @param t Tunnel to delete from.
1420 * @param HKr Header Key to use.
1423 store_skipped_key (struct CadetTunnel *t,
1424 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1426 struct CadetTunnelSkippedKey *key;
1428 key = GNUNET_new (struct CadetTunnelSkippedKey);
1429 key->timestamp = GNUNET_TIME_absolute_get ();
1430 key->Kn = t->ax->Nr;
1431 key->HK = t->ax->HKr;
1432 t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1433 #if DUMP_KEYS_TO_STDERR
1434 LOG (GNUNET_ERROR_TYPE_DEBUG, " storing MK for Nr %u: %s\n",
1435 key->Kn, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1436 LOG (GNUNET_ERROR_TYPE_DEBUG, " for CKr: %s\n",
1437 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->ax->CKr));
1439 t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1440 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1447 * Delete a key from the list of skipped keys.
1449 * @param t Tunnel to delete from.
1450 * @param key Key to delete.
1453 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1455 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1462 * Stage skipped AX keys and calculate the message key.
1464 * Stores each HK and MK for skipped messages.
1466 * @param t Tunnel where to stage the keys.
1467 * @param HKr Header key.
1468 * @param Np Received meesage number.
1470 * @return GNUNET_OK if keys were stored.
1471 * GNUNET_SYSERR if an error ocurred (Np not expected).
1474 store_ax_keys (struct CadetTunnel *t,
1475 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1481 gap = Np - t->ax->Nr;
1482 LOG (GNUNET_ERROR_TYPE_INFO, "Storing keys [%u, %u)\n", t->ax->Nr, Np);
1483 if (MAX_KEY_GAP < gap)
1485 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1486 /* TODO: start new key exchange on return */
1487 GNUNET_break_op (0);
1488 LOG (GNUNET_ERROR_TYPE_WARNING, "Got message %u, expected %u+\n",
1490 return GNUNET_SYSERR;
1494 /* Delayed message: don't store keys, flag to try old keys. */
1495 return GNUNET_SYSERR;
1498 while (t->ax->Nr < Np)
1499 store_skipped_key (t, HKr);
1501 while (t->ax->skipped > MAX_SKIPPED_KEYS)
1502 delete_skipped_key (t, t->ax->skipped_tail);
1509 * Decrypt and verify data with the appropriate tunnel key and verify that the
1510 * data has not been altered since it was sent by the remote peer.
1512 * @param t Tunnel whose key to use.
1513 * @param dst Destination for the plaintext.
1514 * @param src Source of the message. Can overlap with @c dst.
1515 * @param size Size of the message.
1517 * @return Size of the decrypted data, -1 if an error was encountered.
1520 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1521 const struct GNUNET_CADET_AX *src, size_t size)
1523 struct CadetTunnelAxolotl *ax;
1524 struct GNUNET_CADET_Hash msg_hmac;
1525 struct GNUNET_HashCode hmac;
1526 struct GNUNET_CADET_AX plaintext_header;
1533 esize = size - sizeof (struct GNUNET_CADET_AX);
1538 /* Try current HK */
1539 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1540 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1542 static const char ctx[] = "axolotl ratchet";
1543 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1544 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1545 struct GNUNET_HashCode dh;
1546 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1549 LOG (GNUNET_ERROR_TYPE_DEBUG, " trying next HK\n");
1550 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1551 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1553 /* Try the skipped keys, if that fails, we're out of luck. */
1554 return try_old_ax_keys (t, dst, src, size);
1556 LOG (GNUNET_ERROR_TYPE_INFO, "next HK worked\n");
1560 t_h_decrypt (t, src, &plaintext_header);
1561 Np = ntohl (plaintext_header.Ns);
1562 PNp = ntohl (plaintext_header.PNs);
1563 DHRp = &plaintext_header.DHRs;
1564 store_ax_keys (t, &HK, PNp);
1566 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1567 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1568 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1569 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1570 &hmac, sizeof (hmac), NULL);
1572 /* Commit "purported" keys */
1578 ax->ratchet_allowed = GNUNET_YES;
1582 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1583 t_h_decrypt (t, src, &plaintext_header);
1584 Np = ntohl (plaintext_header.Ns);
1585 PNp = ntohl (plaintext_header.PNs);
1587 LOG (GNUNET_ERROR_TYPE_INFO, " got AX Nr %u\n", Np);
1589 if (GNUNET_OK != store_ax_keys (t, &ax->HKr, Np))
1590 /* Try the skipped keys, if that fails, we're out of luck. */
1591 return try_old_ax_keys (t, dst, src, size);
1593 osize = t_ax_decrypt (t, dst, &src[1], esize);
1598 GNUNET_break_op (0);
1607 * Create key material by doing ECDH on the local and remote ephemeral keys.
1609 * @param key_material Where to store the key material.
1610 * @param ephemeral Peer's public ephemeral key.
1612 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1615 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1616 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1619 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1622 return GNUNET_SYSERR;
1629 * Create a symmetic key from the identities of both ends and the key material
1632 * @param key Destination for the generated key.
1633 * @param sender ID of the peer that will encrypt with @c key.
1634 * @param receiver ID of the peer that will decrypt with @c key.
1635 * @param key_material Hash created with ECDH with the ephemeral keys.
1638 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1639 const struct GNUNET_PeerIdentity *sender,
1640 const struct GNUNET_PeerIdentity *receiver,
1641 const struct GNUNET_HashCode *key_material)
1643 const char salt[] = "CADET kx salt";
1645 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1646 salt, sizeof (salt),
1647 key_material, sizeof (struct GNUNET_HashCode),
1648 sender, sizeof (struct GNUNET_PeerIdentity),
1649 receiver, sizeof (struct GNUNET_PeerIdentity),
1655 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1657 * @param t Tunnel for which to create the keys.
1659 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1662 create_otr_keys (struct CadetTunnel *t)
1664 struct GNUNET_HashCode km;
1666 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1667 return GNUNET_SYSERR;
1668 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1669 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1670 #if DUMP_KEYS_TO_STDERR
1671 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1672 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
1673 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1674 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
1675 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1676 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1677 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
1678 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1679 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
1686 * Create a new Key eXchange context for the tunnel.
1688 * If the old keys were verified, keep them for old traffic. Create a new KX
1689 * timestamp and a new nonce.
1691 * @param t Tunnel for which to create the KX ctx.
1693 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1696 create_kx_ctx (struct CadetTunnel *t)
1698 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1700 if (NULL != t->kx_ctx)
1702 if (NULL != t->kx_ctx->finish_task)
1704 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1705 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1706 t->kx_ctx->finish_task = NULL;
1711 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1712 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1716 if (CADET_TUNNEL_KEY_OK == t->estate)
1718 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1719 t->kx_ctx->d_key_old = t->d_key;
1720 t->kx_ctx->e_key_old = t->e_key;
1723 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1724 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1725 return create_otr_keys (t);
1730 * @brief Finish the Key eXchange and destroy the old keys.
1732 * @param cls Closure (Tunnel for which to finish the KX).
1733 * @param tc Task context.
1736 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1738 struct CadetTunnel *t = cls;
1740 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1742 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1744 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1748 GNUNET_free (t->kx_ctx);
1754 * Destroy a Key eXchange context for the tunnel. This function only schedules
1755 * the destruction, the freeing of the memory (and clearing of old key material)
1756 * happens after a delay!
1758 * @param t Tunnel whose KX ctx to destroy.
1761 destroy_kx_ctx (struct CadetTunnel *t)
1763 struct GNUNET_TIME_Relative delay;
1765 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1768 if (is_key_null (&t->kx_ctx->e_key_old))
1770 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1774 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1775 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1777 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1783 * Pick a connection on which send the next data message.
1785 * @param t Tunnel on which to send the message.
1787 * @return The connection on which to send the next message.
1789 static struct CadetConnection *
1790 tunnel_get_connection (struct CadetTunnel *t)
1792 struct CadetTConnection *iter;
1793 struct CadetConnection *best;
1795 unsigned int lowest_q;
1797 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1799 lowest_q = UINT_MAX;
1800 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1802 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1803 GCC_2s (iter->c), GCC_get_state (iter->c));
1804 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1806 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1807 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1815 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1821 * Callback called when a queued message is sent.
1823 * Calculates the average time and connection packet tracking.
1825 * @param cls Closure (TunnelQueue handle).
1826 * @param c Connection this message was on.
1827 * @param q Connection queue handle (unused).
1828 * @param type Type of message sent.
1829 * @param fwd Was this a FWD going message?
1830 * @param size Size of the message.
1833 tun_message_sent (void *cls,
1834 struct CadetConnection *c,
1835 struct CadetConnectionQueue *q,
1836 uint16_t type, int fwd, size_t size)
1838 struct CadetTunnelQueue *qt = cls;
1839 struct CadetTunnel *t;
1841 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1843 GNUNET_assert (NULL != qt->cont);
1844 t = NULL == c ? NULL : GCC_get_tunnel (c);
1845 qt->cont (qt->cont_cls, t, qt, type, size);
1851 count_queued_data (const struct CadetTunnel *t)
1853 struct CadetTunnelDelayed *iter;
1856 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1863 * Delete a queued message: either was sent or the channel was destroyed
1864 * before the tunnel's key exchange had a chance to finish.
1866 * @param tqd Delayed queue handle.
1869 unqueue_data (struct CadetTunnelDelayed *tqd)
1871 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1877 * Cache a message to be sent once tunnel is online.
1879 * @param t Tunnel to hold the message.
1880 * @param msg Message itself (copy will be made).
1882 static struct CadetTunnelDelayed *
1883 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1885 struct CadetTunnelDelayed *tqd;
1886 uint16_t size = ntohs (msg->size);
1888 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1890 GNUNET_assert (GNUNET_NO == is_ready (t));
1892 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1895 memcpy (&tqd[1], msg, size);
1896 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1902 * Sends an already built message on a tunnel, encrypting it and
1903 * choosing the best connection.
1905 * @param message Message to send. Function modifies it.
1906 * @param t Tunnel on which this message is transmitted.
1907 * @param c Connection to use (autoselect if NULL).
1908 * @param force Force the tunnel to take the message (buffer overfill).
1909 * @param cont Continuation to call once message is really sent.
1910 * @param cont_cls Closure for @c cont.
1911 * @param existing_q In case this a transmission of previously queued data,
1912 * this should be TunnelQueue given to the client.
1915 * @return Handle to cancel message.
1916 * NULL if @c cont is NULL or an error happens and message is dropped.
1918 static struct CadetTunnelQueue *
1919 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1920 struct CadetTunnel *t, struct CadetConnection *c,
1921 int force, GCT_sent cont, void *cont_cls,
1922 struct CadetTunnelQueue *existing_q)
1924 struct GNUNET_MessageHeader *msg;
1925 struct GNUNET_CADET_Encrypted *otr_msg;
1926 struct GNUNET_CADET_AX *ax_msg;
1927 struct CadetTunnelQueue *tq;
1928 size_t size = ntohs (message->size);
1929 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1930 + sizeof (struct GNUNET_CADET_AX);
1931 char cbuf[max_overhead + size];
1938 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1940 if (GNUNET_NO == is_ready (t))
1942 struct CadetTunnelDelayed *tqd;
1943 /* A non null existing_q indicates sending of queued data.
1944 * Should only happen after tunnel becomes ready.
1946 GNUNET_assert (NULL == existing_q);
1947 tqd = queue_data (t, message);
1950 tq = GNUNET_new (struct CadetTunnelQueue);
1954 tq->cont_cls = cont_cls;
1958 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1960 if (CADET_Axolotl == t->enc_type)
1962 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1963 msg = &ax_msg->header;
1964 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1965 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1966 ax_msg->reserved = 0;
1967 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1968 ax_msg->Ns = htonl (t->ax->Ns++);
1969 ax_msg->PNs = htonl (t->ax->PNs);
1970 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1971 t_h_encrypt (t, ax_msg);
1972 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1976 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1977 msg = &otr_msg->header;
1978 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1980 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1981 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1982 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1983 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1984 otr_msg->ttl = htonl (default_ttl);
1986 GNUNET_assert (esize == size);
1989 c = tunnel_get_connection (t);
1992 /* Why is tunnel 'ready'? Should have been queued! */
1993 if (NULL != t->destroy_task)
1996 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1998 return NULL; /* Drop... */
2002 type = ntohs (message->type);
2005 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2006 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2007 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
2008 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
2010 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
2012 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2013 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2014 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2015 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2016 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2020 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
2022 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
2024 fwd = GCC_is_origin (c, GNUNET_YES);
2028 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type, mid, c, fwd,
2029 force, NULL, NULL));
2032 if (NULL == existing_q)
2034 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
2041 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
2042 &tun_message_sent, tq);
2043 GNUNET_assert (NULL != tq->cq);
2045 tq->cont_cls = cont_cls;
2052 * Send all cached messages that we can, tunnel is online.
2054 * @param t Tunnel that holds the messages. Cannot be loopback.
2057 send_queued_data (struct CadetTunnel *t)
2059 struct CadetTunnelDelayed *tqd;
2060 struct CadetTunnelDelayed *next;
2063 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
2065 if (GCT_is_loopback (t))
2071 if (GNUNET_NO == is_ready (t))
2073 LOG (GNUNET_ERROR_TYPE_WARNING, " not ready yet: %s/%s\n",
2074 estate2s (t->estate), cstate2s (t->cstate));
2078 room = GCT_get_connections_buffer (t);
2079 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2080 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
2081 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
2083 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
2086 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2087 tqd->t, NULL, GNUNET_YES,
2088 NULL != tqd->tq ? tqd->tq->cont : NULL,
2089 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2093 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2098 * @brief Resend the AX KX until we complete the handshake.
2100 * @param cls Closure (tunnel).
2101 * @param tc Task context.
2104 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2106 struct CadetTunnel *t = cls;
2108 t->rekey_task = NULL;
2110 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2113 if (CADET_TUNNEL_KEY_OK == t->estate)
2115 /* Should have been canceled on estate change */
2120 GCT_send_ax_kx (t, CADET_TUNNEL_KEY_SENT >= t->estate);
2125 * Callback called when a queued message is sent.
2127 * @param cls Closure.
2128 * @param c Connection this message was on.
2129 * @param type Type of message sent.
2130 * @param fwd Was this a FWD going message?
2131 * @param size Size of the message.
2134 ephm_sent (void *cls,
2135 struct CadetConnection *c,
2136 struct CadetConnectionQueue *q,
2137 uint16_t type, int fwd, size_t size)
2139 struct CadetTunnel *t = cls;
2140 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2144 if (CADET_TUNNEL_KEY_OK == t->estate)
2147 if (CADET_Axolotl == t->enc_type)
2149 if (NULL != t->rekey_task)
2152 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2153 GNUNET_SCHEDULER_cancel (t->rekey_task);
2155 t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2162 * Callback called when a queued message is sent.
2164 * @param cls Closure.
2165 * @param c Connection this message was on.
2166 * @param type Type of message sent.
2167 * @param fwd Was this a FWD going message?
2168 * @param size Size of the message.
2171 pong_sent (void *cls,
2172 struct CadetConnection *c,
2173 struct CadetConnectionQueue *q,
2174 uint16_t type, int fwd, size_t size)
2176 struct CadetTunnel *t = cls;
2177 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2184 * Sends key exchange message on a tunnel, choosing the best connection.
2185 * Should not be called on loopback tunnels.
2187 * @param t Tunnel on which this message is transmitted.
2188 * @param message Message to send. Function modifies it.
2190 * @return Handle to the message in the connection queue.
2192 static struct CadetConnectionQueue *
2193 send_kx (struct CadetTunnel *t,
2194 const struct GNUNET_MessageHeader *message)
2196 struct CadetConnection *c;
2197 struct GNUNET_CADET_KX *msg;
2198 size_t size = ntohs (message->size);
2199 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2204 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2206 /* Avoid loopback. */
2207 if (GCT_is_loopback (t))
2212 type = ntohs (message->type);
2214 /* Even if tunnel is "being destroyed", send anyway.
2215 * Could be a response to a rekey initiated by remote peer,
2216 * who is trying to create a new channel!
2219 /* Must have a connection, or be looking for one. */
2220 if (NULL == t->connection_head)
2222 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2223 if (CADET_TUNNEL_SEARCHING != t->cstate)
2226 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2227 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2232 msg = (struct GNUNET_CADET_KX *) cbuf;
2233 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2234 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2235 c = tunnel_get_connection (t);
2238 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2241 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2247 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2248 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2249 GNUNET_assert (NULL == t->ephm_h);
2252 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2253 GNUNET_assert (NULL == t->pong_h);
2258 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2261 memcpy (&msg[1], message, size);
2263 fwd = GCC_is_origin (c, GNUNET_YES);
2265 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2272 * Send the ephemeral key on a tunnel.
2274 * @param t Tunnel on which to send the key.
2277 send_ephemeral (struct CadetTunnel *t)
2279 LOG (GNUNET_ERROR_TYPE_INFO, "==> EPHM for %s\n", GCT_2s (t));
2280 if (NULL != t->ephm_h)
2282 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2286 otr_kx_msg.sender_status = htonl (t->estate);
2287 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2288 otr_kx_msg.nonce = t->kx_ctx->challenge;
2289 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2290 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2291 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2292 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2293 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2298 * Send a pong message on a tunnel.
2300 * @param t Tunnel on which to send the pong.
2301 * @param challenge Value sent in the ping that we have to send back.
2304 send_pong (struct CadetTunnel *t, uint32_t challenge)
2306 struct GNUNET_CADET_KX_Pong msg;
2308 LOG (GNUNET_ERROR_TYPE_INFO, "==> PONG for %s\n", GCT_2s (t));
2309 if (NULL != t->pong_h)
2311 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2314 msg.header.size = htons (sizeof (msg));
2315 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2316 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2317 msg.nonce = challenge;
2318 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2319 t_encrypt (t, &msg.nonce, &msg.nonce,
2320 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2321 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2323 t->pong_h = send_kx (t, &msg.header);
2328 * Initiate a rekey with the remote peer.
2330 * @param cls Closure (tunnel).
2331 * @param tc TaskContext.
2334 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2336 struct CadetTunnel *t = cls;
2338 t->rekey_task = NULL;
2340 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2341 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2344 GNUNET_assert (NULL != t->kx_ctx);
2345 struct GNUNET_TIME_Relative duration;
2347 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2348 LOG (GNUNET_ERROR_TYPE_DEBUG,
2349 " kx started %s ago\n",
2350 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2352 // FIXME make duration of old keys configurable
2353 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2355 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2356 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2357 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2364 case CADET_TUNNEL_KEY_UNINITIALIZED:
2365 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2368 case CADET_TUNNEL_KEY_SENT:
2371 case CADET_TUNNEL_KEY_OK:
2373 * - state should have changed during rekey_iterator
2374 * - task should have been canceled at pong_handle
2377 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2380 case CADET_TUNNEL_KEY_PING:
2381 case CADET_TUNNEL_KEY_REKEY:
2385 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2388 // FIXME exponential backoff
2389 struct GNUNET_TIME_Relative delay;
2391 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2392 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2393 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2394 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2395 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2400 * Our ephemeral key has changed, create new session key on all tunnels.
2402 * Each tunnel will start the Key Exchange with a random delay between
2403 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2404 * per second, on average.
2406 * @param cls Closure (size of the hashmap).
2407 * @param key Current public key.
2408 * @param value Value in the hash map (tunnel).
2410 * @return #GNUNET_YES, so we should continue to iterate,
2413 rekey_iterator (void *cls,
2414 const struct GNUNET_PeerIdentity *key,
2417 struct CadetTunnel *t = value;
2418 struct GNUNET_TIME_Relative delay;
2419 long n = (long) cls;
2422 if (NULL != t->rekey_task)
2425 if (GNUNET_YES == GCT_is_loopback (t))
2428 if (CADET_OTR != t->enc_type)
2431 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2432 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2433 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2434 if (GNUNET_OK == create_kx_ctx (t))
2435 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2447 * Create a new ephemeral key and key message, schedule next rekeying.
2449 * @param cls Closure (unused).
2450 * @param tc TaskContext.
2453 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2455 struct GNUNET_TIME_Absolute time;
2460 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2463 GNUNET_free_non_null (otr_ephemeral_key);
2464 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2466 time = GNUNET_TIME_absolute_get ();
2467 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2468 time = GNUNET_TIME_absolute_add (time, rekey_period);
2469 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2470 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2471 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2472 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2473 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
2475 GNUNET_assert (GNUNET_OK ==
2476 GNUNET_CRYPTO_eddsa_sign (id_key,
2477 &otr_kx_msg.purpose,
2478 &otr_kx_msg.signature));
2480 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2481 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2483 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2484 &global_otr_rekey, NULL);
2489 * Called only on shutdown, destroy every tunnel.
2491 * @param cls Closure (unused).
2492 * @param key Current public key.
2493 * @param value Value in the hash map (tunnel).
2495 * @return #GNUNET_YES, so we should continue to iterate,
2498 destroy_iterator (void *cls,
2499 const struct GNUNET_PeerIdentity *key,
2502 struct CadetTunnel *t = value;
2504 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2511 * Notify remote peer that we don't know a channel he is talking about,
2512 * probably CHANNEL_DESTROY was missed.
2514 * @param t Tunnel on which to notify.
2515 * @param gid ID of the channel.
2518 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2520 struct GNUNET_CADET_ChannelManage msg;
2522 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2523 msg.header.size = htons (sizeof (msg));
2524 msg.chid = htonl (gid);
2526 LOG (GNUNET_ERROR_TYPE_DEBUG,
2527 "WARNING destroying unknown channel %u on tunnel %s\n",
2529 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2534 * Demultiplex data per channel and call appropriate channel handler.
2536 * @param t Tunnel on which the data came.
2537 * @param msg Data message.
2538 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2539 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2540 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2541 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2544 handle_data (struct CadetTunnel *t,
2545 const struct GNUNET_CADET_Data *msg,
2548 struct CadetChannel *ch;
2554 size = ntohs (msg->header.size);
2556 sizeof (struct GNUNET_CADET_Data) +
2557 sizeof (struct GNUNET_MessageHeader))
2562 type = ntohs (msg[1].header.type);
2563 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n", GC_m2s (type));
2564 SPRINTF (buf, "# received payload of type %hu", type);
2565 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
2569 ch = GCT_get_channel (t, ntohl (msg->chid));
2572 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2574 LOG (GNUNET_ERROR_TYPE_DEBUG, "channel 0x%X unknown\n", ntohl (msg->chid));
2575 send_channel_destroy (t, ntohl (msg->chid));
2579 GCCH_handle_data (ch, msg, fwd);
2584 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2586 * @param t Tunnel on which the DATA ACK came.
2587 * @param msg DATA ACK message.
2588 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2589 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2590 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2591 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2594 handle_data_ack (struct CadetTunnel *t,
2595 const struct GNUNET_CADET_DataACK *msg,
2598 struct CadetChannel *ch;
2602 size = ntohs (msg->header.size);
2603 if (size != sizeof (struct GNUNET_CADET_DataACK))
2610 ch = GCT_get_channel (t, ntohl (msg->chid));
2613 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2615 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2620 GCCH_handle_data_ack (ch, msg, fwd);
2625 * Handle channel create.
2627 * @param t Tunnel on which the message came.
2628 * @param msg ChannelCreate message.
2631 handle_ch_create (struct CadetTunnel *t,
2632 const struct GNUNET_CADET_ChannelCreate *msg)
2634 struct CadetChannel *ch;
2638 size = ntohs (msg->header.size);
2639 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2641 GNUNET_break_op (0);
2646 ch = GCT_get_channel (t, ntohl (msg->chid));
2647 if (NULL != ch && ! GCT_is_loopback (t))
2649 /* Probably a retransmission, safe to ignore */
2650 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2652 ch = GCCH_handle_create (t, msg);
2654 GCT_add_channel (t, ch);
2660 * Handle channel NACK: check correctness and call channel handler for NACKs.
2662 * @param t Tunnel on which the NACK came.
2663 * @param msg NACK message.
2666 handle_ch_nack (struct CadetTunnel *t,
2667 const struct GNUNET_CADET_ChannelManage *msg)
2669 struct CadetChannel *ch;
2673 size = ntohs (msg->header.size);
2674 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2681 ch = GCT_get_channel (t, ntohl (msg->chid));
2684 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2686 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2691 GCCH_handle_nack (ch);
2696 * Handle a CHANNEL ACK (SYNACK/ACK).
2698 * @param t Tunnel on which the CHANNEL ACK came.
2699 * @param msg CHANNEL ACK message.
2700 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2701 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2702 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2703 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2706 handle_ch_ack (struct CadetTunnel *t,
2707 const struct GNUNET_CADET_ChannelManage *msg,
2710 struct CadetChannel *ch;
2714 size = ntohs (msg->header.size);
2715 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2722 ch = GCT_get_channel (t, ntohl (msg->chid));
2725 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2727 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2732 GCCH_handle_ack (ch, msg, fwd);
2737 * Handle a channel destruction message.
2739 * @param t Tunnel on which the message came.
2740 * @param msg Channel destroy message.
2741 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2742 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2743 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2744 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2747 handle_ch_destroy (struct CadetTunnel *t,
2748 const struct GNUNET_CADET_ChannelManage *msg,
2751 struct CadetChannel *ch;
2755 size = ntohs (msg->header.size);
2756 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2763 ch = GCT_get_channel (t, ntohl (msg->chid));
2766 /* Probably a retransmission, safe to ignore */
2770 GCCH_handle_destroy (ch, msg, fwd);
2775 * Free Axolotl data.
2780 destroy_ax (struct CadetTunnel *t)
2785 GNUNET_free_non_null (t->ax->DHRs);
2786 GNUNET_free_non_null (t->ax->kx_0);
2787 while (NULL != t->ax->skipped_head)
2788 delete_skipped_key (t, t->ax->skipped_head);
2789 GNUNET_assert (0 == t->ax->skipped);
2791 GNUNET_free (t->ax);
2794 if (NULL != t->rekey_task)
2796 GNUNET_SCHEDULER_cancel (t->rekey_task);
2797 t->rekey_task = NULL;
2799 if (NULL != t->ephm_h)
2801 GCC_cancel (t->ephm_h);
2808 * The peer's ephemeral key has changed: update the symmetrical keys.
2810 * @param t Tunnel this message came on.
2811 * @param msg Key eXchange message.
2814 handle_ephemeral (struct CadetTunnel *t,
2815 const struct GNUNET_CADET_KX_Ephemeral *msg)
2817 LOG (GNUNET_ERROR_TYPE_INFO, "<== EPHM for %s\n", GCT_2s (t));
2819 /* Some old versions are still around, don't log as error. */
2820 if (GNUNET_OK != check_ephemeral (t, msg))
2823 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2827 t->enc_type = CADET_OTR;
2828 if (NULL != t->rekey_task)
2829 GNUNET_SCHEDULER_cancel (t->rekey_task);
2830 if (GNUNET_OK != create_kx_ctx (t))
2836 rekey_tunnel (t, NULL);
2837 GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2841 * If the key is different from what we know, derive the new E/D keys.
2842 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2844 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2845 sizeof (msg->ephemeral_key)))
2847 #if DUMP_KEYS_TO_STDERR
2848 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2849 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
2850 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2851 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &msg->ephemeral_key));
2853 t->peers_ephemeral_key = msg->ephemeral_key;
2855 if (GNUNET_OK != create_kx_ctx (t))
2862 if (CADET_TUNNEL_KEY_OK == t->estate)
2864 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2866 if (NULL != t->rekey_task)
2867 GNUNET_SCHEDULER_cancel (t->rekey_task);
2868 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2870 if (CADET_TUNNEL_KEY_SENT == t->estate)
2872 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2874 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2877 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2881 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2882 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2883 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2884 send_pong (t, nonce);
2890 * Peer has answer to our challenge.
2891 * If answer is successful, consider the key exchange finished and clean
2892 * up all related state.
2894 * @param t Tunnel this message came on.
2895 * @param msg Key eXchange Pong message.
2898 handle_pong (struct CadetTunnel *t,
2899 const struct GNUNET_CADET_KX_Pong *msg)
2903 LOG (GNUNET_ERROR_TYPE_INFO, "<== PONG for %s\n", GCT_2s (t));
2904 if (NULL == t->rekey_task)
2906 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2909 if (NULL == t->kx_ctx)
2911 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2915 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2916 if (challenge != t->kx_ctx->challenge)
2918 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2919 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2920 challenge, msg->nonce, t->kx_ctx->challenge);
2924 GNUNET_SCHEDULER_cancel (t->rekey_task);
2925 t->rekey_task = NULL;
2927 /* Don't free the old keys right away, but after a delay.
2928 * Rationale: the KX could have happened over a very fast connection,
2929 * with payload traffic still signed with the old key stuck in a slower
2931 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2935 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2940 * Handle Axolotl handshake.
2942 * @param t Tunnel this message came on.
2943 * @param msg Key eXchange Pong message.
2946 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2948 struct CadetTunnelAxolotl *ax;
2949 struct GNUNET_HashCode key_material[3];
2950 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2951 const char salt[] = "CADET Axolotl salt";
2952 const struct GNUNET_PeerIdentity *pid;
2955 LOG (GNUNET_ERROR_TYPE_INFO, "<== { AX_KX} on %s\n", GCT_2s (t));
2959 /* Something is wrong if ax is NULL. Whose fault it is? */
2960 GNUNET_break_op (CADET_OTR == t->enc_type);
2961 GNUNET_break (CADET_Axolotl == t->enc_type);
2966 pid = GCT_get_destination (t);
2967 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2968 am_I_alice = GNUNET_YES;
2969 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2970 am_I_alice = GNUNET_NO;
2973 GNUNET_break_op (0);
2977 if (0 != (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2979 if (NULL != t->rekey_task)
2981 GNUNET_SCHEDULER_cancel (t->rekey_task);
2982 t->rekey_task = NULL;
2984 GCT_send_ax_kx (t, GNUNET_NO);
2987 if (0 == memcmp (&ax->DHRr, &msg->ratchet_key, sizeof(msg->ratchet_key)))
2989 LOG (GNUNET_ERROR_TYPE_INFO, " known ratchet key, exit\n");
2993 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2995 ax->DHRr = msg->ratchet_key;
2998 if (GNUNET_YES == am_I_alice)
3000 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
3001 &msg->ephemeral_key, /* B0 */
3006 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
3007 &pid->public_key, /* A */
3012 if (GNUNET_YES == am_I_alice)
3014 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
3015 &pid->public_key, /* B */
3020 GNUNET_CRYPTO_eddsa_ecdh (id_key, /* A */
3021 &msg->ephemeral_key, /* B0 */
3028 /* (This is the triple-DH, we could probably safely skip this,
3029 as A0/B0 are already in the key material.) */
3030 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
3031 &msg->ephemeral_key, /* B0 or A0 */
3034 #if DUMP_KEYS_TO_STDERR
3037 for (i = 0; i < 3; i++)
3038 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
3039 i, GNUNET_h2s (&key_material[i]));
3044 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
3045 salt, sizeof (salt),
3046 &key_material, sizeof (key_material), NULL);
3048 if (0 == memcmp (&ax->RK, &keys[0], sizeof(ax->RK)))
3050 LOG (GNUNET_ERROR_TYPE_INFO, " known handshake key, exit\n");
3054 if (GNUNET_YES == am_I_alice)
3060 ax->ratchet_flag = GNUNET_YES;
3068 ax->ratchet_flag = GNUNET_NO;
3069 ax->ratchet_allowed = GNUNET_NO;
3070 ax->ratchet_counter = 0;
3071 ax->ratchet_expiration =
3072 GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
3077 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
3078 send_queued_data (t);
3083 * Demultiplex by message type and call appropriate handler for a message
3084 * towards a channel of a local tunnel.
3086 * @param t Tunnel this message came on.
3087 * @param msgh Message header.
3088 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
3089 * #GNUNET_YES if message is FWD on the respective channel (loopback)
3090 * #GNUNET_NO if message is BCK on the respective channel (loopback)
3091 * #GNUNET_SYSERR if message on a one-ended channel (remote)
3094 handle_decrypted (struct CadetTunnel *t,
3095 const struct GNUNET_MessageHeader *msgh,
3101 type = ntohs (msgh->type);
3102 LOG (GNUNET_ERROR_TYPE_DEBUG, "<-- %s on %s\n", GC_m2s (type), GCT_2s (t));
3103 SPRINTF (buf, "# received encrypted of type %hu (%s)", type, GC_m2s (type));
3104 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
3108 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3109 /* Do nothing, connection aleady got updated. */
3110 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3113 case GNUNET_MESSAGE_TYPE_CADET_DATA:
3114 /* Don't send hop ACK, wait for client to ACK */
3115 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3118 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3119 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3122 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3123 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3126 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3127 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3130 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3131 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3134 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3135 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3139 GNUNET_break_op (0);
3140 LOG (GNUNET_ERROR_TYPE_WARNING,
3141 "end-to-end message not known (%u)\n",
3142 ntohs (msgh->type));
3143 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3148 /******************************************************************************/
3149 /******************************** API ***********************************/
3150 /******************************************************************************/
3152 * Decrypt old format and demultiplex by message type. Call appropriate handler
3153 * for a message towards a channel of a local tunnel.
3155 * @param t Tunnel this message came on.
3156 * @param msg Message header.
3159 GCT_handle_encrypted (struct CadetTunnel *t,
3160 const struct GNUNET_MessageHeader *msg)
3162 uint16_t size = ntohs (msg->size);
3166 const struct GNUNET_MessageHeader *msgh;
3169 type = ntohs (msg->type);
3172 case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3174 const struct GNUNET_CADET_Encrypted *emsg;
3175 size_t payload_size;
3177 GNUNET_STATISTICS_update (stats, "# received OTR", 1, GNUNET_NO);
3178 emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3179 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3180 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3181 emsg->iv, &emsg->hmac);
3184 case GNUNET_MESSAGE_TYPE_CADET_AX:
3186 const struct GNUNET_CADET_AX *emsg;
3188 GNUNET_STATISTICS_update (stats, "# received Axolotl", 1, GNUNET_NO);
3189 emsg = (const struct GNUNET_CADET_AX *) msg;
3190 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3194 GNUNET_break_op (0);
3198 if (-1 == decrypted_size)
3200 GNUNET_break_op (0);
3201 GNUNET_STATISTICS_update (stats, "# unable to decrypt", 1, GNUNET_NO);
3202 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto on tunnel %s\n", GCT_2s (t));
3203 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3206 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
3208 /* FIXME: this is bad, as the structs returned from
3209 this loop may be unaligned, see util's MST for
3210 how to do this right. */
3212 while (off + sizeof (struct GNUNET_MessageHeader) <= decrypted_size)
3216 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3217 msize = ntohs (msgh->size);
3218 if (msize < sizeof (struct GNUNET_MessageHeader))
3220 GNUNET_break_op (0);
3223 if (off + msize < decrypted_size)
3225 GNUNET_break_op (0);
3228 handle_decrypted (t, msgh, GNUNET_SYSERR);
3235 * Demultiplex an encapsulated KX message by message type.
3237 * @param t Tunnel on which the message came.
3238 * @param message Payload of KX message.
3241 GCT_handle_kx (struct CadetTunnel *t,
3242 const struct GNUNET_MessageHeader *message)
3247 type = ntohs (message->type);
3248 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3249 sprintf (buf, "# received KX of type %hu (%s)", type, GC_m2s (type));
3250 GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
3253 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3254 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3257 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3258 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3261 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3262 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3266 GNUNET_break_op (0);
3267 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3272 * Initialize the tunnel subsystem.
3274 * @param c Configuration handle.
3275 * @param key ECC private key, to derive all other keys and do crypto.
3278 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3279 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3281 int expected_overhead;
3283 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3285 expected_overhead = 0;
3286 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3287 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3288 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3289 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3292 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3295 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3296 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3300 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3303 rekey_period = GNUNET_TIME_UNIT_DAYS;
3306 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3309 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3310 "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3311 ratchet_messages = 64;
3314 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3317 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3318 "CADET", "RATCHET_TIME", "USING DEFAULT");
3319 ratchet_time = GNUNET_TIME_UNIT_HOURS;
3325 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3326 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3327 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3328 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3329 otr_kx_msg.origin_identity = my_full_id;
3330 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3331 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3336 * Shut down the tunnel subsystem.
3341 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down tunnels\n");
3342 if (NULL != rekey_task)
3344 GNUNET_SCHEDULER_cancel (rekey_task);
3347 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3348 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3355 * @param destination Peer this tunnel is towards.
3357 struct CadetTunnel *
3358 GCT_new (struct CadetPeer *destination)
3360 struct CadetTunnel *t;
3362 t = GNUNET_new (struct CadetTunnel);
3364 t->peer = destination;
3367 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3368 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3374 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3376 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3382 * Change the tunnel's connection state.
3384 * @param t Tunnel whose connection state to change.
3385 * @param cstate New connection state.
3388 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3392 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3393 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3394 if (myid != GCP_get_short_id (t->peer) &&
3395 CADET_TUNNEL_READY != t->cstate &&
3396 CADET_TUNNEL_READY == cstate)
3399 if (CADET_TUNNEL_KEY_OK == t->estate)
3401 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3402 send_queued_data (t);
3404 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3406 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3407 GCT_send_ax_kx (t, GNUNET_NO);
3411 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3416 if (CADET_TUNNEL_READY == cstate
3417 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3419 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3420 GCP_stop_search (t->peer);
3426 * Change the tunnel encryption state.
3428 * If the encryption state changes to OK, stop the rekey task.
3430 * @param t Tunnel whose encryption state to change, or NULL.
3431 * @param state New encryption state.
3434 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3436 enum CadetTunnelEState old;
3443 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3444 GCP_2s (t->peer), estate2s (old));
3445 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3446 GCP_2s (t->peer), estate2s (t->estate));
3448 if (CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3450 if (NULL != t->rekey_task)
3452 GNUNET_SCHEDULER_cancel (t->rekey_task);
3453 t->rekey_task = NULL;
3455 /* Send queued data if tunnel is not loopback */
3456 if (myid != GCP_get_short_id (t->peer))
3457 send_queued_data (t);
3463 * @brief Check if tunnel has too many connections, and remove one if necessary.
3465 * Currently this means the newest connection, unless it is a direct one.
3466 * Implemented as a task to avoid freeing a connection that is in the middle
3467 * of being created/processed.
3469 * @param cls Closure (Tunnel to check).
3470 * @param tc Task context.
3473 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3475 struct CadetTunnel *t = cls;
3477 t->trim_connections_task = NULL;
3479 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3482 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3484 struct CadetTConnection *iter;
3485 struct CadetTConnection *c;
3487 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3489 if ((iter->created.abs_value_us > c->created.abs_value_us)
3490 && GNUNET_NO == GCC_is_direct (iter->c))
3497 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3499 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3512 * Add a connection to a tunnel.
3515 * @param c Connection.
3518 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3520 struct CadetTConnection *aux;
3522 GNUNET_assert (NULL != c);
3524 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3525 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3526 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3530 aux = GNUNET_new (struct CadetTConnection);
3532 aux->created = GNUNET_TIME_absolute_get ();
3534 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3536 if (CADET_TUNNEL_SEARCHING == t->cstate)
3537 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3539 if (NULL != t->trim_connections_task)
3540 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3545 * Remove a connection from a tunnel.
3548 * @param c Connection.
3551 GCT_remove_connection (struct CadetTunnel *t,
3552 struct CadetConnection *c)
3554 struct CadetTConnection *aux;
3555 struct CadetTConnection *next;
3558 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3559 GCC_2s (c), GCT_2s (t));
3560 for (aux = t->connection_head; aux != NULL; aux = next)
3565 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3570 conns = GCT_count_connections (t);
3572 && NULL == t->destroy_task
3573 && CADET_TUNNEL_SHUTDOWN != t->cstate
3574 && GNUNET_NO == shutting_down)
3576 if (0 == GCT_count_any_connections (t))
3577 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3579 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3582 /* Start new connections if needed */
3583 if (CONNECTIONS_PER_TUNNEL > conns
3584 && CADET_TUNNEL_SHUTDOWN != t->cstate
3585 && GNUNET_NO == shutting_down)
3587 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3588 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3592 /* If not marked as ready, no change is needed */
3593 if (CADET_TUNNEL_READY != t->cstate)
3596 /* Check if any connection is ready to maintain cstate */
3597 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3598 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3604 * Add a channel to a tunnel.
3607 * @param ch Channel.
3610 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3612 struct CadetTChannel *aux;
3614 GNUNET_assert (NULL != ch);
3616 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3618 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3620 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3625 aux = GNUNET_new (struct CadetTChannel);
3627 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3628 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3630 if (NULL != t->destroy_task)
3632 GNUNET_SCHEDULER_cancel (t->destroy_task);
3633 t->destroy_task = NULL;
3634 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3640 * Remove a channel from a tunnel.
3643 * @param ch Channel.
3646 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3648 struct CadetTChannel *aux;
3650 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3651 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3655 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3656 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3665 * Search for a channel by global ID.
3667 * @param t Tunnel containing the channel.
3668 * @param chid Public channel number.
3670 * @return channel handler, NULL if doesn't exist
3672 struct CadetChannel *
3673 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3675 struct CadetTChannel *iter;
3680 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3682 if (GCCH_get_id (iter->ch) == chid)
3686 return NULL == iter ? NULL : iter->ch;
3691 * @brief Destroy a tunnel and free all resources.
3693 * Should only be called a while after the tunnel has been marked as destroyed,
3694 * in case there is a new channel added to the same peer shortly after marking
3695 * the tunnel. This way we avoid a new public key handshake.
3697 * @param cls Closure (tunnel to destroy).
3698 * @param tc Task context.
3701 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3703 struct CadetTunnel *t = cls;
3704 struct CadetTConnection *iter;
3706 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3707 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3709 LOG (GNUNET_ERROR_TYPE_WARNING,
3710 "Not destroying tunnel, due to shutdown. "
3711 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3714 t->destroy_task = NULL;
3715 t->cstate = CADET_TUNNEL_SHUTDOWN;
3717 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3719 GCC_send_destroy (iter->c);
3726 * Tunnel is empty: destroy it.
3728 * Notifies all connections about the destruction.
3730 * @param t Tunnel to destroy.
3733 GCT_destroy_empty (struct CadetTunnel *t)
3735 if (GNUNET_YES == shutting_down)
3736 return; /* Will be destroyed immediately anyway */
3738 if (NULL != t->destroy_task)
3740 LOG (GNUNET_ERROR_TYPE_WARNING,
3741 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3743 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3745 /* should never happen, tunnel can only become empty once, and the
3746 * task identifier should be NO_TASK (cleaned when the tunnel was created
3747 * or became un-empty)
3752 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3755 // FIXME make delay a config option
3756 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3757 &delayed_destroy, t);
3758 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %p\n",
3759 t, t->destroy_task);
3764 * Destroy tunnel if empty (no more channels).
3766 * @param t Tunnel to destroy if empty.
3769 GCT_destroy_if_empty (struct CadetTunnel *t)
3771 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3772 if (0 < GCT_count_channels (t))
3775 GCT_destroy_empty (t);
3780 * Destroy the tunnel.
3782 * This function does not generate any warning traffic to clients or peers.
3785 * Cancel messages belonging to this tunnel queued to neighbors.
3786 * Free any allocated resources linked to the tunnel.
3788 * @param t The tunnel to destroy.
3791 GCT_destroy (struct CadetTunnel *t)
3793 struct CadetTConnection *iter_c;
3794 struct CadetTConnection *next_c;
3795 struct CadetTChannel *iter_ch;
3796 struct CadetTChannel *next_ch;
3797 unsigned int keepalives_queued;
3802 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3804 GNUNET_break (GNUNET_YES ==
3805 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3806 GCP_get_id (t->peer), t));
3808 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3810 next_c = iter_c->next;
3811 GCC_destroy (iter_c->c);
3813 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3815 next_ch = iter_ch->next;
3816 GCCH_destroy (iter_ch->ch);
3817 /* Should only happen on shutdown, but it's ok. */
3819 keepalives_queued = 0;
3820 while (NULL != t->tq_head)
3822 /* Should have been cleaned by destuction of channel. */
3823 struct GNUNET_MessageHeader *mh;
3826 mh = (struct GNUNET_MessageHeader *) &t->tq_head[1];
3827 type = ntohs (mh->type);
3828 if (0 == keepalives_queued && GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE == type)
3830 keepalives_queued = 1;
3831 LOG (GNUNET_ERROR_TYPE_DEBUG,
3832 "one keepalive left behind on tunnel shutdown\n");
3834 else if (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY == type)
3836 LOG (GNUNET_ERROR_TYPE_WARNING,
3837 "tunnel destroyed before a CHANNEL_DESTROY was sent to peer\n");
3842 LOG (GNUNET_ERROR_TYPE_ERROR,
3843 "message left behind on tunnel shutdown: %s\n",
3846 unqueue_data (t->tq_head);
3850 if (NULL != t->destroy_task)
3852 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %p\n", t->destroy_task);
3853 GNUNET_SCHEDULER_cancel (t->destroy_task);
3854 t->destroy_task = NULL;
3857 if (NULL != t->trim_connections_task)
3859 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %p\n",
3860 t->trim_connections_task);
3861 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3862 t->trim_connections_task = NULL;
3865 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3866 GCP_set_tunnel (t->peer, NULL);
3868 if (NULL != t->rekey_task)
3870 GNUNET_SCHEDULER_cancel (t->rekey_task);
3871 t->rekey_task = NULL;
3873 if (NULL != t->kx_ctx)
3875 if (NULL != t->kx_ctx->finish_task)
3876 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3877 GNUNET_free (t->kx_ctx);
3888 * @brief Use the given path for the tunnel.
3889 * Update the next and prev hops (and RCs).
3890 * (Re)start the path refresh in case the tunnel is locally owned.
3892 * @param t Tunnel to update.
3893 * @param p Path to use.
3895 * @return Connection created.
3897 struct CadetConnection *
3898 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *path)
3900 struct CadetConnection *c;
3901 struct GNUNET_CADET_Hash cid;
3902 unsigned int own_pos;
3904 if (NULL == t || NULL == path)
3910 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3916 for (own_pos = 0; own_pos < path->length; own_pos++)
3918 if (path->peers[own_pos] == myid)
3921 if (own_pos >= path->length)
3923 GNUNET_break_op (0);
3927 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3928 c = GCC_new (&cid, t, path, own_pos);
3931 /* Path was flawed */
3934 GCT_add_connection (t, c);
3940 * Count all created connections of a tunnel. Not necessarily ready connections!
3942 * @param t Tunnel on which to count.
3944 * @return Number of connections created, either being established or ready.
3947 GCT_count_any_connections (struct CadetTunnel *t)
3949 struct CadetTConnection *iter;
3955 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3963 * Count established (ready) connections of a tunnel.
3965 * @param t Tunnel on which to count.
3967 * @return Number of connections.
3970 GCT_count_connections (struct CadetTunnel *t)
3972 struct CadetTConnection *iter;
3978 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3979 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3987 * Count channels of a tunnel.
3989 * @param t Tunnel on which to count.
3991 * @return Number of channels.
3994 GCT_count_channels (struct CadetTunnel *t)
3996 struct CadetTChannel *iter;
3999 for (count = 0, iter = t->channel_head;
4001 iter = iter->next, count++) /* skip */;
4008 * Get the connectivity state of a tunnel.
4012 * @return Tunnel's connectivity state.
4014 enum CadetTunnelCState
4015 GCT_get_cstate (struct CadetTunnel *t)
4020 return (enum CadetTunnelCState) -1;
4027 * Get the encryption state of a tunnel.
4031 * @return Tunnel's encryption state.
4033 enum CadetTunnelEState
4034 GCT_get_estate (struct CadetTunnel *t)
4039 return (enum CadetTunnelEState) -1;
4045 * Get the maximum buffer space for a tunnel towards a local client.
4049 * @return Biggest buffer space offered by any channel in the tunnel.
4052 GCT_get_channels_buffer (struct CadetTunnel *t)
4054 struct CadetTChannel *iter;
4055 unsigned int buffer;
4056 unsigned int ch_buf;
4058 if (NULL == t->channel_head)
4060 /* Probably getting buffer for a channel create/handshake. */
4061 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
4062 return MIN_TUNNEL_BUFFER;
4066 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4068 ch_buf = get_channel_buffer (iter);
4069 if (ch_buf > buffer)
4072 if (MIN_TUNNEL_BUFFER > buffer)
4073 return MIN_TUNNEL_BUFFER;
4075 if (MAX_TUNNEL_BUFFER < buffer)
4078 return MAX_TUNNEL_BUFFER;
4085 * Get the total buffer space for a tunnel for P2P traffic.
4089 * @return Buffer space offered by all connections in the tunnel.
4092 GCT_get_connections_buffer (struct CadetTunnel *t)
4094 struct CadetTConnection *iter;
4095 unsigned int buffer;
4097 if (GNUNET_NO == is_ready (t))
4099 if (count_queued_data (t) >= 3)
4106 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4108 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
4112 buffer += get_connection_buffer (iter);
4120 * Get the tunnel's destination.
4124 * @return ID of the destination peer.
4126 const struct GNUNET_PeerIdentity *
4127 GCT_get_destination (struct CadetTunnel *t)
4129 return GCP_get_id (t->peer);
4134 * Get the tunnel's next free global channel ID.
4138 * @return GID of a channel free to use.
4141 GCT_get_next_chid (struct CadetTunnel *t)
4143 CADET_ChannelNumber chid;
4144 CADET_ChannelNumber mask;
4147 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
4148 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
4149 * If peer's ID is bigger, start at 0x4... bit 30 = 1
4151 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4156 t->next_chid |= mask;
4158 while (NULL != GCT_get_channel (t, t->next_chid))
4160 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4161 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4162 t->next_chid |= mask;
4164 chid = t->next_chid;
4165 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4166 t->next_chid |= mask;
4173 * Send ACK on one or more channels due to buffer in connections.
4175 * @param t Channel which has some free buffer space.
4178 GCT_unchoke_channels (struct CadetTunnel *t)
4180 struct CadetTChannel *iter;
4181 unsigned int buffer;
4182 unsigned int channels = GCT_count_channels (t);
4183 unsigned int choked_n;
4184 struct CadetChannel *choked[channels];
4186 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4187 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4188 if (NULL != t->channel_head)
4189 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4191 if (NULL != t->tq_head)
4192 send_queued_data (t);
4194 /* Get buffer space */
4195 buffer = GCT_get_connections_buffer (t);
4201 /* Count and remember choked channels */
4203 for (iter = t->channel_head; NULL != iter; iter = iter->next)
4205 if (GNUNET_NO == get_channel_allowed (iter))
4207 choked[choked_n++] = iter->ch;
4211 /* Unchoke random channels */
4212 while (0 < buffer && 0 < choked_n)
4214 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4216 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4219 choked[r] = choked[choked_n];
4225 * Send ACK on one or more connections due to buffer space to the client.
4227 * Iterates all connections of the tunnel and sends ACKs appropriately.
4232 GCT_send_connection_acks (struct CadetTunnel *t)
4234 struct CadetTConnection *iter;
4237 uint32_t allow_per_connection;
4239 unsigned int buffer;
4241 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4250 if (CADET_TUNNEL_READY != t->cstate)
4253 buffer = GCT_get_channels_buffer (t);
4254 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4256 /* Count connections, how many messages are already allowed */
4257 cs = GCT_count_connections (t);
4258 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4260 allowed += get_connection_allowed (iter);
4262 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4264 /* Make sure there is no overflow */
4265 if (allowed > buffer)
4268 /* Authorize connections to send more data */
4269 to_allow = buffer - allowed;
4271 for (iter = t->connection_head;
4272 NULL != iter && to_allow > 0;
4275 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4276 || get_connection_allowed (iter) > 64 / 3)
4280 allow_per_connection = to_allow/cs;
4281 to_allow -= allow_per_connection;
4283 GCC_allow (iter->c, allow_per_connection,
4284 GCC_is_origin (iter->c, GNUNET_NO));
4289 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4290 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4296 * Cancel a previously sent message while it's in the queue.
4298 * ONLY can be called before the continuation given to the send function
4299 * is called. Once the continuation is called, the message is no longer in the
4302 * @param q Handle to the queue.
4305 GCT_cancel (struct CadetTunnelQueue *q)
4309 GNUNET_assert (NULL == q->tqd);
4311 /* tun_message_sent() will be called and free q */
4313 else if (NULL != q->tqd)
4315 unqueue_data (q->tqd);
4317 if (NULL != q->cont)
4318 q->cont (q->cont_cls, NULL, q, 0, 0);
4329 * Check if the tunnel has queued traffic.
4331 * @param t Tunnel to check.
4333 * @return #GNUNET_YES if there is queued traffic
4334 * #GNUNET_NO otherwise
4337 GCT_has_queued_traffic (struct CadetTunnel *t)
4339 return (NULL != t->tq_head) ? GNUNET_YES : GNUNET_NO;
4344 * Sends an already built message on a tunnel, encrypting it and
4345 * choosing the best connection if not provided.
4347 * @param message Message to send. Function modifies it.
4348 * @param t Tunnel on which this message is transmitted.
4349 * @param c Connection to use (autoselect if NULL).
4350 * @param force Force the tunnel to take the message (buffer overfill).
4351 * @param cont Continuation to call once message is really sent.
4352 * @param cont_cls Closure for @c cont.
4354 * @return Handle to cancel message. NULL if @c cont is NULL.
4356 struct CadetTunnelQueue *
4357 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4358 struct CadetTunnel *t, struct CadetConnection *c,
4359 int force, GCT_sent cont, void *cont_cls)
4361 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4366 * Send an Axolotl KX message.
4368 * @param t Tunnel on which to send it.
4369 * @param force_reply Force the other peer to reply with a KX message.
4372 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4374 struct GNUNET_CADET_AX_KX msg;
4375 enum GNUNET_CADET_AX_KX_Flags flags;
4377 LOG (GNUNET_ERROR_TYPE_INFO, "==> { AX_KX} on %s\n", GCT_2s (t));
4378 if (NULL != t->ephm_h)
4380 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
4384 msg.header.size = htons (sizeof (msg));
4385 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4386 flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4388 flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4389 msg.flags = htonl (flags);
4390 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4391 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4393 t->ephm_h = send_kx (t, &msg.header);
4394 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
4395 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4400 * Sends an already built and encrypted message on a tunnel, choosing the best
4401 * connection. Useful for re-queueing messages queued on a destroyed connection.
4403 * @param message Message to send. Function modifies it.
4404 * @param t Tunnel on which this message is transmitted.
4407 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4408 struct CadetTunnel *t)
4410 struct CadetConnection *c;
4413 c = tunnel_get_connection (t);
4416 /* TODO queue in tunnel, marked as encrypted */
4417 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4420 fwd = GCC_is_origin (c, GNUNET_YES);
4421 GNUNET_break (NULL == GCC_send_prebuilt_message (message, UINT16_MAX, 0,
4423 GNUNET_YES, NULL, NULL));
4428 * Is the tunnel directed towards the local peer?
4432 * @return #GNUNET_YES if it is loopback.
4435 GCT_is_loopback (const struct CadetTunnel *t)
4437 return (myid == GCP_get_short_id (t->peer));
4442 * Is the tunnel this path already?
4447 * @return #GNUNET_YES a connection uses this path.
4450 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4452 struct CadetTConnection *iter;
4454 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4455 if (path_equivalent (GCC_get_path (iter->c), p))
4463 * Get a cost of a path for a tunnel considering existing connections.
4466 * @param path Candidate path.
4468 * @return Cost of the path (path length + number of overlapping nodes)
4471 GCT_get_path_cost (const struct CadetTunnel *t,
4472 const struct CadetPeerPath *path)
4474 struct CadetTConnection *iter;
4475 const struct CadetPeerPath *aux;
4476 unsigned int overlap;
4484 GNUNET_assert (NULL != t);
4486 for (i = 0; i < path->length; i++)
4488 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4490 aux = GCC_get_path (iter->c);
4494 for (j = 0; j < aux->length; j++)
4496 if (path->peers[i] == aux->peers[j])
4504 return path->length + overlap;
4509 * Get the static string for the peer this tunnel is directed.
4513 * @return Static string the destination peer's ID.
4516 GCT_2s (const struct CadetTunnel *t)
4521 return GCP_2s (t->peer);
4525 /******************************************************************************/
4526 /***************************** INFO/DEBUG *******************************/
4527 /******************************************************************************/
4530 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4532 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4533 struct CadetTunnelSkippedKey *iter;
4535 LOG2 (level, "TTT RK \t %s\n",
4536 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
4538 LOG2 (level, "TTT HKs \t %s\n",
4539 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
4540 LOG2 (level, "TTT HKr \t %s\n",
4541 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
4542 LOG2 (level, "TTT NHKs\t %s\n",
4543 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
4544 LOG2 (level, "TTT NHKr\t %s\n",
4545 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
4547 LOG2 (level, "TTT CKs \t %s\n",
4548 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
4549 LOG2 (level, "TTT CKr \t %s\n",
4550 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
4552 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4553 LOG2 (level, "TTT DHRs\t %s\n",
4554 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
4555 LOG2 (level, "TTT DHRr\t %s\n",
4556 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
4558 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4559 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4560 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4562 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4564 LOG2 (level, "TTT HK\t %s\n",
4565 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
4566 LOG2 (level, "TTT MK\t %s\n",
4567 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
4572 * Log all possible info about the tunnel state.
4574 * @param t Tunnel to debug.
4575 * @param level Debug level to use.
4578 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4580 struct CadetTChannel *iterch;
4581 struct CadetTConnection *iterc;
4584 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4586 __FILE__, __FUNCTION__, __LINE__);
4590 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4591 LOG2 (level, "TTT cstate %s, estate %s\n",
4592 cstate2s (t->cstate), estate2s (t->estate));
4593 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4594 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4595 #if DUMP_KEYS_TO_STDERR
4596 if (CADET_Axolotl == t->enc_type)
4598 ax_debug (t->ax, level);
4602 LOG2 (level, "TTT my EPHM\t %s\n",
4603 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
4604 LOG2 (level, "TTT peers EPHM:\t %s\n",
4605 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
4606 LOG2 (level, "TTT ENC key:\t %s\n",
4607 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
4608 LOG2 (level, "TTT DEC key:\t %s\n",
4609 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
4612 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4613 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->e_key_old));
4614 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4615 GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->d_key_old));
4619 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4620 LOG2 (level, "TTT destroy %p\n", t->destroy_task);
4622 LOG2 (level, "TTT channels:\n");
4623 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4625 GCCH_debug (iterch->ch, level);
4628 LOG2 (level, "TTT connections:\n");
4629 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4631 GCC_debug (iterc->c, level);
4634 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4639 * Iterate all tunnels.
4641 * @param iter Iterator.
4642 * @param cls Closure for @c iter.
4645 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4647 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4652 * Count all tunnels.
4654 * @return Number of tunnels to remote peers kept by this peer.
4657 GCT_count_all (void)
4659 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4664 * Iterate all connections of a tunnel.
4666 * @param t Tunnel whose connections to iterate.
4667 * @param iter Iterator.
4668 * @param cls Closure for @c iter.
4671 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4673 struct CadetTConnection *ct;
4675 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4681 * Iterate all channels of a tunnel.
4683 * @param t Tunnel whose channels to iterate.
4684 * @param iter Iterator.
4685 * @param cls Closure for @c iter.
4688 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4690 struct CadetTChannel *cht;
4692 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4693 iter (cls, cht->ch);